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
| 218 | 2.71875 | 3 |
[] |
no_license
|
/* La sentencia FOR */
#include <iostream>
#include <conio.h>
using namespace std;
int main(){
for(int i = 1, j = 100; i <= 100 && j >= 1; i++, j--){
cout << i << " " << j << endl;
}
getch();
return 0;
}
|
TypeScript
|
UTF-8
| 2,103 | 3.34375 | 3 |
[
"MIT"
] |
permissive
|
// Copyright (c) Dolittle. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
import { BehaviorSubject, Subject } from 'rxjs';
import { ObservableCollectionIterator } from './ObservableCollectionIterator';
/**
* Represents a collection of items that can be observed for changes.
*/
export class ObservableCollection<T> extends BehaviorSubject<T[]> implements Iterable<T> {
private readonly _added: Subject<T[]>;
private readonly _removed: Subject<T[]>;
/**
* Initializes a new instance of the {ObservableCollection<T>} class.
*/
constructor() {
super([]);
this._added = new Subject<T[]>();
this._removed = new Subject<T[]>();
}
/**
* Gets the added {Subject<T>}.
*/
get added(): Subject<T[]> {
return this._added;
}
/**
* Gets the removed {Subject<T>}.
*/
get removed(): Subject<T[]> {
return this._removed;
}
/** @inheritdoc */
[Symbol.iterator]() {
return new ObservableCollectionIterator<T>(this);
}
/**
* Gets the length of the collection.
* @returns {number} Length of the collection.
*/
get length(): number {
return this.value.length;
}
/**
* Get a specific item at a specific index.
* @param {number} index - Index to get.
* @returns {T} The item at the index.
*/
item(index: number): T {
return this.value[index];
}
/**
* Push items to the collection.
* @param {T[]} items - Rest of items.
* @returns {number} - Number of items in the collection after push.
*/
push(...items: T[]): number {
const result = this.value.push(...items);
this.added.next(items);
return result;
}
remove(...items: T[]): number {
let current = this.value;
items.forEach(item => {
current = current.filter(_ => _ !== item);
});
this.next(current);
this.removed.next(items);
return this.length;
}
}
|
C#
|
UTF-8
| 775 | 3.25 | 3 |
[] |
no_license
|
using Gemstone.Definitions.Enums;
namespace Gemstone.Classes.Functional
{
public class DamageDice
{
public Die Die { get; private set; }
public DamageType Type { get; private set; }
public bool IsMagic { get; private set; }
public DamageDice(Die die, DamageType type, bool isMagic)
{
Die = die;
Type = type;
IsMagic = isMagic;
}
public Damage RollDamage(bool isCritical = false)
{
return new Damage(Die.Roll(isCritical), Type, IsMagic);
}
public string DamageString(int modifier = 0)
{
return modifier > 0
? Die + "+" + modifier + " " + Type
: Die + " " + Type;
}
}
}
|
C#
|
UTF-8
| 1,432 | 3.03125 | 3 |
[
"MIT"
] |
permissive
|
// ***********************************************************************
// Copyright (c) Charlie Poole and TestCentric contributors.
// Licensed under the MIT License. See LICENSE in root directory.
// ***********************************************************************
namespace TCLite.Constraints
{
/// <summary>
/// OrConstraint succeeds if either member succeeds{{
/// </summary>
public class OrConstraint : BinaryConstraint
{
/// <summary>
/// Create an OrConstraint from two other constraints
/// </summary>
/// <param name="left">The first constraint</param>
/// <param name="right">The second constraint</param>
public OrConstraint(IConstraint left, IConstraint right) : base(left, right) { }
public override string Description => $"{Left.Description} or {Right.Description}";
/// <summary>
/// Apply the member constraints to an actual value, succeeding
/// succeeding as soon as one of them succeeds.
/// </summary>
/// <param name="actual">The actual value</param>
/// <returns>True if either constraint succeeded</returns>
protected override ConstraintResult ApplyConstraint<T>(T actual)
{
bool hasSucceeded = Left.ApplyTo(actual).IsSuccess || Right.ApplyTo(actual).IsSuccess;
return new ConstraintResult(this, actual, hasSucceeded);
}
}
}
|
C#
|
UTF-8
| 488 | 3.171875 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _17_Unmanaged_Code
{
class Unsafe1App
{
public static unsafe void GetValues(int* x, int* y)
{
*x = 6;
*y = 42;
}
public static unsafe void MainMain()
{
int a = 1, b = 2;
Console.WriteLine("Before : a={0},b={1}", a, b);
GetValues(&a, &b);
Console.WriteLine("After : a={0},b={1}", a, b);
}
}
}
|
JavaScript
|
UTF-8
| 2,071 | 2.703125 | 3 |
[] |
no_license
|
import {Game} from './gameController.js'
export class Terminal {
terminalBox = null;
game = null;
constructor(instance, terminalBox){
this.terminalBox = $(instance).find(terminalBox)[0]
for(var element in this.commands) {
this.commands[element].vm = this;
};
this.refreshTerminalCommands()
}
commands = {
help: {
exec: function(commandName){
if(commandName in this.vm.commands ){
this.vm.pushText(this.vm.commands[commandName].description)
}
else{
for(var element in this.vm.commands) {
this.vm.pushText(this.vm.commands[element].description);
};
}
},
description: 'help [command-name] - outputs individual commands help'
},
clear : {
exec: function (){
console.log(this)
console.log(this.vm.terminalBox)
$(this.vm.terminalBox).empty();
},
description: 'clear - Clears the terminal output window.'
},
game: {
exec: function(args){
if(args == 'exit' && this.vm.game != null){
this.vm.game.exit()
}
else if(args == 'exit' && this.vm.game == null ){
this.vm.pushText('No game has been loaded');
}
else {
this.vm.game = new Game(this.vm, args);
}
},
description:'game [game-name] - load game via its name .e.g "game ./maze"'
}
}
pushText(text){
$(this.terminalBox).append(("<p class='col-12 m-0'>" + text + "</p>"));
$(this.terminalBox).scrollTop($(this.terminalBox)[0].scrollHeight);
}
refreshTerminalCommands() {
for(var element in this.commands) {
this.commands[element].vm = this;
};
}
}
|
Markdown
|
UTF-8
| 43,212 | 2.890625 | 3 |
[] |
no_license
|
# 4 Implementatie
## 4.1 Testing checklist
### 4.1.1 Overzicht
Dit is de kern van het project. Het was de bedoeling dat er een lijst werd opgesteld waarin alle paradigma's die getest moesten worden onder elkaar weergegeven werden. In de "testing guideline" staat voor elk element in deze lijst beschreven hoe dat specifieke paradigma moet getest worden. Daarnaast is er in een apart excel document voor elke pagina opgelijst welke specifieke paradigma's op die bepaalde pagina aanwezig zijn. Op die manier wordt er per pagina in een matrix bijgehouden of een bepaald paradigma volledig getest is, moet getest worden of niet van toepassing is.
>Naar het einde van de bachelorproef toe werd er een automatisatie van dit process in ontwikkeld, er werd gehoopt dat deze volledig af zou zijn tegen het einde van de stage. Uiteindelijk zijn de tools niet volledig afgeraakt. Al zijn ze wel functioneel. Meer informatie over deze tools vindt je terug in de "Gebruikte tools en technologieën" sectie van het "Introductie" hoofdstuk.
### 4.1.2 Werkwijze
Er werd gestart met de basispagina’s die de meest gebruikte paradigma's/besturingselementen bevatten (die zo goed als overal terugkomen).
Voor elke gevonden besturingselement/paradigma werd dan ge-analyseerd hoe deze zo effecient mogelijk getest kon worden. Deze methode werd dan gedocumenteerd zodat eventuele opvolgers deze altijd terug kunnen raadplegen wanneer nodig. Er werd ook gedocumenteerd welke besturingselementen en paradigma's reeds getest zijn geweest, tot alles getest is voor de specifieke pagina. Op het moment dat alle paradigma's op alle besturingselementen die deze paradigma's toepassen getest zijn, wordt een pagina als volledig getest verklaard.
Indien er op een volgende pagina weer een nieuwe besturingselement/paradigma tevoorschijn komt, zetten we deze bij onderaan onze checklist met gevonden besturingselementen/paradigma's. Het is dan weer opnieuw de bedoeling om uit te zoeken hoe deze getest kan worden en alle voorgaande pagina’s opnieuw af te gaan en te controleren of ook dit element aanwezig is op de pagina en te testen indien nodig, zodat de pagina weer als getest verklaard kan worden.
### 4.1.3 General checklist
Deze checklist bevat de algemene paradigma's die op elke pagina aanwezig zijn. Ze zijn onderverdeeld in een aantal subcategorieën, die later verder onderverdeeld zullen worden.
Op de general checklist staat voor elke pagina een kolom, met daaronder voor elk paradigma of dit volledig getest is voor deze pagina of niet. Men verklaard een pagina als volledig getest wanneer de pagina specifieke checklist, die verder besproken wordt, volledig is afgewerkt.
Onderaan de general checklist staat ook een legende met een letter en een kleur die de test-status voorstelt van een paradigma (bijvoorbeeld: Y van Yes = getest, D van Do = nog te doen, E van Error = probleem bij testen,...)
### 5.1.4 Paradigm checklist
Aangezien het de bedoeling is dat er paradigma's gaan gezocht worden, en dat er dan voor elk paradigma uitgezocht wordt hoe dit moet getest worden, en dit nadien gedocumenteerd moet worden, leek het handig om een aparte paradigma-checklist te maken. Hier staan alle paradigma's, onderverdeeld tot op het niveau van specifieke scenario's, die getest moeten worden. Vervolgens staat er een kolom naast deze lijst, met dezelfde kleurcode als in de legende. Deze geeft dus aan of dit paradigma ge-analyseerd is en dus bekend is hoe dit moet getest worden.
Wanneer er een nieuw paradigma bijkomt, zal deze dus altijd eerst op groen moeten komen in de paradigma-checklist, vooraleer dit getest kan worden op de rest van de pagina's. Uiteraard zal dit dan wel op één pagina al getest zijn, namelijk de pagina waarop dit paradigma gevonden is en ge-analyseerd is.
### 4.1.5 Example-page + Page checklists
Vervolgens is er de pagina-specifieke checklist. Hierin staan de algemene paradigma's van de general checklist verder onderverdeeld zoals bij de paradigma-checklist. Bovenaan wordt de pagina dan opgesplitst in al zijn aparte besturingselementen, die worden gebruikt om tests uit te voeren. Voor elk besturingselement is ook het parent-besturingselement gedocumenteerd, zodat het duidelijk is over welke besturingselement het gaat.
Op de example-page zijn enkele besturingselementen aanwezig die op elke pagina terugkomen, zoals de backbutton of de home-knop.
Wanneer een nieuw paradigma gevonden wordt, zal dit eerst in de paradigm checklist terecht komen. Vervolgens komt paradigma op de example-page en nadien op alle andere page-checklists. Wanneer er begonnen wordt met een nieuwe pagina te testen en dus een page-checklist gemaakt wordt voor deze pagina, kan de example-page rechtstreeks gekopiërd en geplakt worden, en kunnen vervolgens alle pagina-specifieke besturingselementen toegevoegd worden.
Op de page checklist staat opnieuw aangeduid welk paradigma getest is en welk niet, volgens de kleurcode in de legende op de general checklist, met als verschil dat deze hier nog eens onderverdeeld worden per besturingselement. Er wordt dus voor elk besturingselement ge-analyseerd welk paradigma van toepassing is en dan wordt de status volgens de kleurcode aangeduid.
### 4.1.6 Full checklist (eerste versie)
In de guideline staat de volledig uitgeschreven versie van de checklist. Hierin staat voor elk puntje in de lijst beschreven wat het exact inhoud onder "what?". Dit is een korte beschrijving van wat er getest wordt en wat de elementen die in de test gebruikt worden horen te doen.
Vervolgens staat onder "how?" een stappenplan beschreven dat je moet volgen om die specifieke test uit te voeren.
In deze checklist hoort zo specifiek en zo duidelijk mogelijk te zijn, zodat het ook voor een eventuele opvolger helemaal duidelijk is wat exact de bedoeling is van deze test en wat de verschillende besturingselementen en elementen horen te doen wanneer ze gebruikt worden op de beschreven manier.
Merk op dat deze checklist later nogmaals veranderd is. Bij deze de uitleg over de eerste versie van de checklist (de uiteindelijke volgt nog):
#### 4.1.6.1 Content
In deze sectie worden alle paradigma's beschreven die betrekking hebben tot de inhoud van besturingselementen en tekstvelden. Alle informatie die in de user-interface beschikbaar is die uit de database komt, of aangepast kan worden, komt onder het paradigma "content".
Er zijn 4 verschillende handelingen die uitgevoerd kunnen worden op info in de besturingselementen. Deze 4 staan beter bekend als de CRUD-acties. (Create, Read, Update, Delete)
##### A. Create
"Create" wil zeggen dat je nieuwe data gaat toevoegen aan de database. Een voorbeeld hiervan is het toevoegen van een nieuwe patiënt of een nieuwe studie. Je vult alle velden in die relevant zijn en klikt dan op "toevoegen", wat ervoor zorgt dat er in de database een patiënt bijkomt die nog niet bestond.
Om dit paradigma te testen, moet eerst uitgezocht worden op welk deel van de applicatie het toevoegen van nieuwe data invloed heeft. Vervolgens kan data toegevoegd worden (door tekstveldjes in te vullen, staat beschreven in de guideline). tot slot moet gecontroleerd worden of de data veranderd is waar deze moest veranderen. Voor die controle is een "Read"-functie nodig, dus create en read zijn deels verweven met elkaar.
>Voorbeeld: Ik voeg een nieuwe studie toe. Dit doe ik door een overlay te openen waarin een aantal tekstveldjes staan en een knop "toevoegen". Ik vul deze veldjes in en klik op de knop. Vervolgens navigeer ik naar de pagina waar de lijst met alle studies staat en loop ik over deze lijst om te controleren dat de studie die ik net heb toegevoegd aanwezig is in de lijst. Wanneer al deze stappen succesvol zijn uitgevoerd, is mijn test geslaagd.
##### B. Read
"Read" wil zeggen dat je gaat controleren of bestaande data, die aanwezig zou moeten zijn in de user-interface, ook effectief aanwezig is. Om dit te testen moet uitgezocht worden hoe enerzijds tekstvelden en eventueel andere besturingselementen uitgelezen kunnen worden, en anderzijds hoe deze vergeleken kunnen worden met de effectieve data in de database.
Er zijn verschillende scenario's die onder "Read" vallen.
**Weergegeven data**
Buiten het zoek-algoritme, welke een speciaal geval van "read" is, bestaat een read-test eruit om te gaan controleren dat de data die weergegeven wordt in de user-interface correct is.
Een voorbeeld is dat er naar de TrialHubPage genavigeerd wordt. Hierin staat alle data die te maken heeft met een bepaalde studie. Deze pagina gedraagt zich qua functionaliteit altijd hetzelfde, maar de data die weergegeven wordt hangt af van de studie waarop geklikt is. De bedoeling van de read-test is dan om te gaan controleren of de data die zichtbaar is in de user-interface dezelfde is als de data die verwacht wordt na een bepaalde navigatie.
Dit kan enerzijds hardcoded gecontroleerd worden, door eerst manueel de navigatie uit te voeren en dan alle data die zichtbaar is in code te schrijven als assertions (assertions worden later uitgelegd). Anderzijds kunnen datadriven tests geschreven worden, waarbij de data die we gebruiken in de test afkomstig is van een database (wordt ook later uitgelegd).
##### C. Update/delete
Update wil zeggen dat je reeds bestaande data gaat aanpassen en deze aanpassingen opslaan.
Delete is het verwijderen van bestaande data in de database.
Update en delete vallen binnen deze applicatie onder dezelfde tab, aangezien het deleten van data in de UI een update naar de database stuurt met een indicatie dat deze data niet meer bestaat.
##### D. Custom
Onder deze tab worden alle speciale gevallen geplaatst die nog bij content horen. Onder deze speciale gevallen horen bijvoorbeeld: het zoek-algoritme, de partpickers (wordt zo meteen besproken),...
**Zoek-algoritme**
Dit het algoritme dat de zoekfunctie doet werken. Er zijn 3 verschillende testscenario's die hierop uitgevoerd moeten worden.
1. Er moet getest worden of alle mogelijke parameters waarop we kunnen zoeken zoekresultaten opleveren. Het kan bijvoorbeeld zijn dat het zoekalgoritme zo is ingesteld dat je kan zoeken op de studienaam, patientnaam,...
Het soort parameters waarop gezocht kan worden moet manueel ge-analyseerd worden. Nadien worden hier tests voor geschreven.
2. Vervolgens moet gecontroleerd worden of alle zoekresultaten die weergegeven worden het zoekwoord bevatten dat ingegeven is. Hiervoor moet een speciaal soort read-functie geschreven worden, waar later meer over verteld wordt.
3. Als derde moeten gecontroleerd worden of alle objecten in de database, die voldoen aan de zoekterm, ook effectief worden weergegeven. Het is één ding dat alle zoekresultaten de zoekterm bevatten, maar het zou natuurlijk altijd kunnen dat een aantal zoekresultaten die in de database wel effectief bestaan, niet worden weergegeven. In dat geval zou de vorige test wel werken, maar zou er toch nog een fout in het zoek-algoritme zitten. Vandaar dat deze derde test noodzakelijk is om het zoek-algoritme volledig te testen.
##### E. Part-pickers
Part-pickers zijn speciale knoppen waarmee je een datum of een tijd kan instellen. Door op de knop te klikken, verschijnt er een popup-venster. In dit venster staan een aantal verschillende tabs. Elk van deze tabs bevat een aantal blokken met waarden gaande van bijvoorbeeld 0-30/maandag-vrijdag/januari-december/... Door over deze blokken te hoveren met de muis en te scrollen, verschuiven ze, waardoor je de waarde aanpast. Er is altijd 1 van tab geselecteerd die je kan aanpassen. Bij het hoveren met de muis wordt de tab waarover je hovert automatisch geselecteerd. Je kan echter ook met de pijltjestoetsen van links naar rechts gaan om andere tabs te selecteren. Als je met de pijltjestoetsen van boven naar beneden gaat verschuif je de geselecteerde tab altijd met 2 waardes per keer. Met het scroll-wiel van de muis verplaats je de geselecteerde tab met 1 waarde per keer.
Onderaan het popup-venster staan 2 knoppen, een vinkje en een kruisje. Door op het vinkje te klikken accepteer je de datum/tijd die je net hebt ingesteld en zal deze verschijnen in de Part-picker waarmee je net gewerkt hebt. Door op het kruisje te klikken wordt de verandering geanuleerd en blijft de waarde van de part-picker staan zoals die voordien stond.
De aangepaste waarde accepteren kan ook door op enter te klikken.
Telkens je een waarde accepteert/weigert verdwijnt het popup-venster terug.
Het testen van deze partpickers is tot nu toe nog niet gelukt, aangezien er geen enkele manier gevonden is om in testcode de partpicker te kunnen zien.
#### 4.1.6.2 Navigations
Het volgende grote paradigma zijn de navigaties binnen de applicatie. Onder navigaties vallen alle acties die ervoor zorgen dat de applicatie een ander scherm opendoet. Ook de zoekfunctie behoort tot navigaties, aangezien we hier ook naar een ander scherm gaan. Het verschil tussen de CRUD-tests voor de zoekfunctie en de navigatietests is echter dat bij de navigatietests niet gecontroleerd wordt welke zoekdata weergegeven wordt, maar enkel of er naar de zoekresultatenpagina genavigeerd wordt (ClinicSearch).
Om een navigatie te testen zijn er dus in grote lijnen 2 handelingen die we moeten uitvoeren. Enerzijds moete de actie uitvoerd worden die zorgt voor de navigatie (meestal klikken op een besturingselement). Anderzijds moeten gecontroleerd worden of de juiste pagina wordt geopend nadat deze actie is uitgevoerd.
Deze controle kan voor elke pagina anders zijn, maar de werkwijze is steeds dezelfde: er wordt een besturingselement of een set van besturingselementen die uniek zijn voor de desbetreffende pagina gezocht, en gecontroleerd of deze besturingselementen aanwezig zijn, of dat ze de juiste waarde bevatten (bijvoorbeeld: titels).
##### A. Soorten navigations
Paradigmagewijs zijn alle navigations natuurlijk hetzelfde. Maar in manier van testen zijn de navigaties verder onderverdeeld in sub-paradigma's, waarbij elk sub-paradigma een lichtjes andere manier van testen omvat.
**Variabele besturingselementen**
Hieronder valt het concept van een lijst, waarin zich allemaal verschillende gevallen bevinden van een bepaald opject. Dit kan bijvoorbeeld zijn: een lijst van studies, een lijst van patienten,... Het aantal items in de lijst staat nooit vast, aangezien het afhangt van hoeveel studies/patienten/... er zich in de database bevinden. Dit kan voortdurend wijzigen. Ook de tekst op deze besturingselementen hangt af van de data in de database.
Als je op één van de besturingselementen in deze lijst klikt, zal je altijd op dezelfde pagina terecht komen. Hoe deze pagina is ingevuld hangt echter af van de besturingselement waarop je geklikt hebt.
Om dit te testen moet er dus enerzijds voor gezorgd worden dat het besturingselement aanklikbaar is, en nadien moet gecontroleerd worden of de titel van de pagina naarwaar genavigeerd werd overeen stemt met de besturingselement waarop geklikt is.
**Vaste besturingselementen**
Vaste besturingselementen zijn besturingselementen die altijd op een pagina aanwezig zijn, ongeacht de data in de database. De navigatie is uniek voor elk van deze besturingselementen. Soms kan het wel zijn dat meerdere vaste besturingselementen naar dezelfde pagina navigeren maar ze zorgen dan elk apart voor een andere state van de desbetreffende pagina. Ze openen bijvoorbeeld allemaal een aparte tab van dezelfde pagina of zorgen ervoor dat de pagina anders ge-ordend is.
Het aantal vaste besturingselementen op een pagina is altijd dezelfde, en deze staan ook altijd op dezelfde plaats gepositioneerd, enkel kan het zijn dat de tekst in deze besturingselementen varieert op basis van de data die zich in de database bevind.
Om deze besturingselementen te testen moet ook geklikt worden op de besturingselement, maar de concrete klikfunctie voor deze testmethode zal lichtjes verschillen van de variabele besturingselementen, aangezien de manier om toegang te krijgen tot het besturingselement anders zal zijn. De controle of de navigatie juist gebeurd is is opnieuw een controle op de titel van de pagina waarnaar genavigeerd werd, en eventueel een controle op de state van deze pagina (bijvoorbeeld: staat de juiste tab open? Staan de elementen in de pagina juist ge-ordend? ...).
**Zoekfunctie**
De zoekfunctie vanuit de ClinicHubPage kan ook beschouwd worden als een navigatie. Als puur het navigatiegedeelte hiervan getest wordt, moet er geen rekening gehouden worden met het algoritme dat zorgt voor de correcte zoekresultaten, maar enkel met het feit dat er genavigeerd wordt naar de zoekresultatenpagina.
Opnieuw zal dit een klein verschil geven in het schrijven van code, aangezien er deze keer niet moet geklikt worden op een besturingselementen, maar er eerst een zoekwoord moet ingeven worden en nadien ge-enterd moet worden of geklikt moet worden op het vergrootglas naast het zoekvak.
De controle gebeurt opnieuw op de titel van de zoekresultatenpagina.
**Hyperlink-navigatie**
Op pagina's die data bevatten die te maken heeft met één bepaalde studie of één bepaalde patiënt (of eventueel nog andere objecten die in de toekomst zouden kunnen tevoorschijn komen), staat bovenaan steeds een hyperlink met de naam van dit object. Als hierop geklikt wordt, verschijnt de overzichtpagina van dat object (bijvoorbeeld: studie->TrialHub, patiënt->PatientHub, ...)
Het schrijven van navigatiecode zal hier opnieuw lichtjes verschillen omdat de toegankelijkheid van de hyperlink lichtjes verschilt van de vorige navigaties. De controle gebeurt opnieuw op de titel.
>Voor al deze verschillende navigaties wordt steeds onderzocht hoe het besturingselement gevonden kan worden in code, hoe een verwachte waarde gecreëerd kan worden aan de hand van welke gecontroleerd kan worden of de juiste navigatie uitgevoerd werd, hoe dan deze control gebruikt kan worden (meestal klikken, aangezien de verschillende functionaliteiten zoals tab-enter bij navigaties nog niet van belang zijn, deze komen later terug bij functionality) en hoe dan gecontroleerd kan worden dat deze verwachtte waarde aanwezig is na de navigatie. Na elk van deze tests wordt dan ook nog de omgekeerde test gedaan met de backbutton, opnieuw met een verwachtte waarde en een effectieve waarde. Dit zorgt ervoor dat alle mogelijke back-navigaties in de applicatie uiteindelijk getest zijn. Dit geheel wordt zoveel mogelijk in één grote functie per soort navigatie geschreven, zodat als nadien dit soort navigatie nog tevoorschijn komt, de geschreven functie gewoon éénmaal aangeroepen moet worden en er dus geen extra werk meer is.
#### 4.1.6.3 States
De verschillende states van een pagina zijn de verschillende soorten toestanden waarin die pagina zich kan bevinden. Dit zijn:
* Semantic zoom
* Zoomed in
* Zoomed out
* Overlay
* Overlay is open
* Overlay is gesloten
* Filtering search
* Verschillende orderingen
* Multiselect
* Meerdere geselecteerde elementen
##### A. Semantic zoom
De semantic zoom is een parent-besturingselement, die de mogelijkheid bezit om zichzelf in en uit te zoomen. Meestal bevind er zich in de semantic zoom een hub, die onderverdeeld wordt in verschillende hubsecties. Dit zijn allemaal aparte blokken waarin zich een aantal besturingselementen bevinden. Bovenaan een hubsectie staat dan de titel van deze hubsectie. Het aantal hubsecties is niet van belang, en ook het aantal besturingselementen die in een hubsectie geimplementeerd worden is niet van belang. Dat zijn er zoveel of zo weinig als je zelf wil.
Wanneer naar een pagina met een semantic zoom genavigeerd wordt, staat deze automatisch ingezoomd. Alle hubsecties zijn dan volledig zichtbaar met hun titel en alle besturingselementen. Uitzoomen wordt gedaan door "Ctrl-", Ctrl & scrollen, klikken op de hubsectie-titels, PgUp/PgDn&Enter en Tab&Enter. Wanneer uitgezoomd wordt verdwijnen alle volledige hubsecties en komt er in de plaats een lijst met listitems tevoorschijn, waarin alle titels van de hubsecties weergegeven zijn. Zo kan er makkelijk genavigeerd worden naar een hubsectie die helemaal rechts op het scherm staat en dus nog niet zichtbaar was in de zoomed-in state (toen moest er naartoe gescrolld worden).
Het terug inzoomen kan op dezelfde manier, door te klikken op de listitems, "Ctrl+", Ctrl & scrollen, , PgUp/PgDn&Enter en Tab&Enter. Als er terug ingezoomd wordt op een bepaalde hubsectie zal deze links van het scherm getoond worden.
Wat er dus moet getest worden is dat deze semantic zoom altijd in- en uitzoomt wanneer de beschreven actie uitgevoerd wordt. Dit moet opnieuw één keer volledig manueel ge-analyseerd worden, en nadien op zo een manier beschreven worden in een functie dat deze functie voor alle pagina's die een semantic zoom bevatten bruikbaar is zonder moeite.
Wat echter ook moet getest worden bij de semantic zoom, is het feit dat de hubsectietitels die in de zoomed-in state weergegeven zijn, ook overeenkomen met de titels die te zien is in de lijst als we uitzoomen. Ook moet gecontroleerd worden of alle hubsecties aanwezig zijn in de zoomed-in en zoomed-out state en dat deze aantallen dus overeen komen.
Op sommige pagina's bevat de semantic zoom dan ook nog eens content die gebaseerd is op de content veranderingen in de gehele pagina. Zo is het bijvoorbeeld zo dat op de PatientScript page een checkbox in de semantic zoom staat, die aan uit uitgevinkt staat afhankelijk van het feit dat bepaalde info in de pagina is ingevuld of nog leeg is. Er moet dus ook getest worden dat deze checkboxes bij de zoomed-in en de zoomed-out state overeen komen.
Ook deze inhoudelijke tests moeten eerst manueel uitgevoerd worden en daarna in een functie weggeschreven worden zodat deze later hergebruikt kan worden zonder teveel denkwerk.
##### B. Overlay
Een overlay is een extra stuk scherm dat bovenop een weergegeven scherm komt, wanneer er op een bepaalde knop geklikt wordt. De intentie van de overlay is dat bepaalde data toegevoegd kan worden (create) of aangepast kan worden (Update). Meestal bestaat de overlay uit een aantal inputveldjes en een uitvoer-knop. Door deze inputveldjes in te vullen en op de uitvoer-knop te klikken wordt de data die jij net hebt ingevuld toegevoegd of aangepast in de database.
Wat hier moet getest worden zijn verschillende dingen. Eerst en vooral moet getest worden of de overlay initieel niet zichtbaar is. Dan moet er gekeken worden dat de knop die de bedoeling heeft de overlay te openen dit ook effectief doet. Dan moeten er gecontroleerd worden of de functionaliteit op de overlay zelf werkt naar behoren. Dit kan bijvoorbeeld zijn dat de uitvoer-knop pas actief wordt als bepaalde veldjes zijn ingevuld. Als laatste moet er getest worden of de overlay ook terug sluit als er op de sluit-knop of de uitvoer-knop geklikt wordt. Als er op de uitvoerknop geklikt wordt moet er gecontroleerd worden of de data die ingevoerd is doorgevoerd wordt naar de applicatie.
#### 4.1.6.4 Functionality
Onder functionaliteit valt: alles dat te maken heeft met hoe de applicatie werkt, hoe besturingselementen werken,...
##### A. Speed
Speed heeft alles te maken met de snelheid waarmee de pagina's geladen zijn. Er zijn twee speed paradigmas die getest worden.
* Reaction-speed
* Reactivity
**Reaction speed**
De "reaction-speed" of reactiesnelheid is de snelheid waarmee een pagina geladen wordt. Dit is een speciaal soort test, die niet slaagt of faalt, maar een bepaalde waarde moet teruggeven.
Om dit te testen moet dus eerst uitgezocht worden hoe je nagaat of een pagina geladen is of niet. Vervolgens moet er uitgezocht worden hoe dit kan getimed worden en tot slot hoe deze getimede tijd opgeslagen en gerapporteerd kan worden.
**Reactivity**
Reactiviteit is het kunnen gebruiken van besturingselementen vooraleer de pagina volledig geladen is.
Om dit te testen moet een manier gevonden worden om te controleren of de pagina al geladen is of nog niet, nadat het besturingselement gebruikt is. Als de vorige test succesvol uitgevoerd is, is bekend hoe gecontroleerd moet worden of een pagina geladen is of niet, dus zou dit voor deze test geen probleem mogen zijn.
##### B. Scrolling
De scroll-functie wordt bij heel veel verschillende soorten vensters gebruikt. Het wordt gebruikt binnen een hub, binnen een combobox, sommige dropdown of popup-menus,...
Om de scroll-functie te testen, moet een manier gevonden worden om te controleren of de besturingselementen op het scherm dat getest wordt verplaatsen of zijn verplaatst. Vervolgens moet dan een manier gezocht worden om de verschillende soorten scroll-functies uit te voeren. Deze zijn onderandere het muis-scroll-wiel, de scrollbar,...
##### C. Control state verification
Dit is het controleren of de visuele toestand van de besturingselementen is hoe deze hoort te zijn. Enkele toestanden kunnen zijn: enabled/disabled, de kleur, de helptext,...
Er zijn ook verschillende scenarios waarvoor deze toestanden moeten gecontroleerd worden. Je kunt klikken op een besturingselement, klikken en vasthouden, hoveren over het besturingselement, ... Ook heb je nog de initiele toestand waarin het besturingselement zich bevind.
De tests zullen dus bestaan uit 2 delen, in het eerste deel wordt het scenario gecreëerd dat getest gaat worden (initeel, hover,...)
In het tweede deel wordt de toestand van het besturingselement gecontroleerd, zich bevindend in dit scenario.
##### D. Control accessibility
Als de toestand van een besturingselement getest wordt, wordt natuurlijk ook de toegankelijkheid getest. Dit wil zeggen dat er getest wordt of je het besturingselement kan selecteren door middel van de tab en pijltjes toetsen. Het werd duidelijk dat dit voor sommige besturingselementen mogelijk is maar voor andere niet. Indien het mogelijk is moet er uitgezocht worden hoe er gecontroleerd kan worden of er een stippelijn rondom het besturingselement zichtbaar is wanneer deze geselecteerd is. Vervolgens moet er automatisch getabt worden of op de pijltjestoetsen gedrukt worden in code en gecontroleerd worden of op een gegeven moment dit besturingselement geselecteerd is.
Later wordt er ook gecontroleerd of het besturingselement gebruikt kan worden met enkele toetsen op het toetsenbord als deze geselecteerd is.
##### E. Custom
Onder custom valt alle functionaliteit die specifiek te maken heeft met de besturingselementen zelf, en voor elk type van besturingselement alle tests die enkel gelden voor dit soort besturingselement.
#### 4.1.6.5 Config
Alle config-pagina's van Maät, zijn veruit de meest unieke pagina's in de applicatie. Dit zijn de pagina's met de meeste maar ook de meest complexe functionaliteit, die nergens anders in de applicatie te vinden is. Daarom is er beslist om voor deze pagina's een apart paradigma te maken, waarin al deze unieke gevallen beschreven worden en er automatische functies van gemaakt worden. Deze functies kunnen dan op alle config-pagina's toepast worden. Dit is mogelijk omdat veel besturingselementen en elementen op exact dezelfde plaats en in exact dezelfde hiërarchie voorkomen op al deze pagina's.
### 4.1.7 Full checklist (nieuw)
Na een tijdje te werken met deze checklist, begonnen meer en meer paradigmas in verschillende categorieën elkaar te overlappen. Daarom is de beslissing genomen om de checklist nogmaals aan te passen en deels uit te breiden, om zoveel mogelijk paradigma's apart te houden en zo dus een overzichtelijke checklist te creëren. Het resultaat was volgende nieuwe indeling:
#### 4.1.7.1 Content
Content krijgt een nieuwe onderverdeling, waarbij alle normale CRUD-operaties onder 1 subcategorie "CRUD" worden geplaatst met dan de verdere onderverdeling in Create, Read, Update en Delete. Onder "normaal" verstaan we gewone content die weergegeven wordt door besturingselementen.
Alle "niet-normale" CRUD-operaties zijn interactieve functies zoals bijvoorbeeld de zoekfunctie. Deze worden onder de tab "Custom CRUD" geplaatst.
Resultaat:
* CRUD
* Create
* Read
* Update
* Delete
* Custom CRUD
* General
* Search algorithm
#### 4.1.7.2 Navigations
Onder navigations waren er 2 subcategorieën, namelijk het navigeren zelf en het creëren van een bepaalde state van een pagina bij een navigatie. Het lijkt echter logisch dat ook de loadspeed (die voordien onder Functionality stond) ook bij navigations wordt geplaatst, aangezien dit iets is dat getest moet worden onmiddelijk na een navigatie.
Resultaat
* Navigate to page
* Navigate to page-state
* Loadspeed
#### 4.1.7.3 States
Bij states zijn er een hele hoop aanpassingen gebeurd. Na het analyseren van de applicatie is duidelijk geworden dat alle mogelijke states buiten overlay-state enkel voor kunnen komen wanneer een pagina niet in overlay-state is. Daarom is dit paradigma nu onderverdeeld in twee grote hoofdcategorieën: Overlay-state en no-overlay-state. Alle andere mogelijke states komen dan onder no-overlay-state. Het resultaat ziet er als volgt uit:
Resultaat:
* No overlay state
* Zoomed in state
* Alle mogelijke zoom-acties vanuit een zoomed in state
* Zoomed out state
* Alle mogelijk zoom-acties vanuit een zoomed out state
* Filtering search state (page ordering
* Multiselect state
* Overlay state
* Alle mogelijke overlay-acties in een overlay state
#### 4.1.7.4 Control state appearance
Dit was een onderdeel van functionality in de oude checklist, maar het lijkt logischer om ook dit paradigma apart te plaatsen. Onder control state appearance vallen alle tests die de toestand van een besturingselement (zowel visueel als functioneel) gaan controleren. Dit kan bijvoorbeeld zijn: de kleur van besturingselementen, het feit dat deze ge-enabled zijn, de waarde die zich in het besturingselement bevind,... Deze toestand moet voor verschillende handelingen gecontroleerd worden. Volgende handelingen zijn alle handelingen die de state van een besturingselement kunnen veranderen:
* Initial (= de oorspronkelijke toestand, voor er een handeling uitgevoerd is)
* Hovered (= wanneer de muis over het besturingselement zweeft)
* Clicked (= wanneer er op het besturingselement geklikt is)
* Click & hold (= wanneer er op het besturingselement geklikt wordt maar de muis ingedrukt gehouden wordt)
* Filled in (= wanneer er data in het besturingselement wordt geplaatst door de gebruiker)
#### 4.1.7.5 Control functionality
Hieronder vallen alle andere functionality tests van de oude checklist, maar deze zijn anders geördend en meer veralgemeend (niet meer specifiek per type besturingselement, maar gewoon algemene tests) aangezien de volledige analyse voor elk type besturingselement moet gebeuren.
De nieuwe indeling is als volgt:
* General: Hieronder vallen alle algemene functionaliteiten, namelijk het selecteren van een besturingselement door click/tab/pijltjestoetsen, en het gebruiken van een besturingselement met click/enter/spatie.
* Execution functionality: Hieronder zijn alle functionaliteiten geplaatst die mogelijk zijn met besturingselementen in de applicatie. Dit kan gaan van het doen verschijnen van andere besturingselementen tot het scrollen doorheen de childs van een besturingselement.
#### 4.1.7.6 Custom functionality
Deze categorie was oorspronkelijk bedoeld voor de config-pagina's, maar de naam is veralgemeend aangezien er op andere pagina's ook nog speciale functionaliteit zou kunnen bestaan. Deze categorie is echter nog niet voldoende geanalyseerd.
## 4.2 Testing Maät
Tijdens het schrijven van tests zijn er verschillende moeilijkheden en dingen die het testen moeilijker maken aan het licht gekomen. Daarom bevat de guideline ook een sectie waarin voor elke pagina het testproces beschreven wordt. Hierin wordt dus beschreven hoe er voor de specifieke pagina in kwestie te werk gegaan wordt om alle tests te analyseren en hoe bepaalde tests moeten geschreven worden om deze zo autonoom mogelijk te maken. Ook als duidelijk wordt dat bepaalde tests niet kunnen geschreven worden door gebrek aan ondersteuning of bijvoorbeeld slechte UIMapping, wordt dit in deze sectie uitgelegd. Zo kan de eventuele opvolger van het project makkelijk de draad oppikken.
### 4.2.1 General workmethod
Hierin wordt het algemene plan van aanpak beschreven die voor elke pagina hetzelfde blijft. Zo staat er bijvoorbeeld beschreven hoe de baseclass voor elke pagina moet opgebouwd zijn en wat hier het nut van is (namelijk het aanroepen van variabelen zodat deze in alle testprojecten van deze pagina kunnen gebruikt worden, en eventueel het schrijven van private functies voor de desbetreffende pagina).
### 4.2.2 Page specific workmethod
Hier staat voor elke pagina apart beschreven hoe er te werk gegaan wordt om deze specifieke pagina te testen (of een specifieke groep van pagina's).
## 4.3 How To Test
In dit onderdeel word algemeen beschreven hoe een test opgebouwd wordt en hoe deze werkt. Hier gaat het dus niet meer om hoe de applicatie Maät getest moet worden, maar echt hoe het Coded UI framework van Visual Studio in elkaar zit.
### 4.3.1 Basics
In de basics wordt beschreven hoe een testproject aangemaakt wordt, welke parameters er in dit project moeten staan om dit te laten runnen, hoe je deze parameters moet aanroepen en dergelijke.
Ook hoe besturingselementen toegevoegd worden aan een testproject wordt hier beschreven. Dit is dus eigelijk het eerste hoofdstuk dat de eventuele opvolger moet lezen om aan het project te kunnen beginnen. Zonder deze basis is het onmogelijk om de rest van de guideline te begrijpen.
### 4.3.2 Generating controls
Onder generating controls staat alles wat nodig is om besturingselementen in een test aan te roepen en waardes van dit besturingselement te verifiëren. Dit is uiteindelijk de essentie van alle tests, namelijk dat we bepaalde waardes gaan controleren op hun correctheid.
### 4.3.3 Commonly used variables and methods
Hier staan een aantal variabelen en methoden beschreven die vaak nodig zijn om bepaalde tests uit te voeren. Een voorbeeld hiervan is de "StopWatch"-variabele.
### 4.3.4 Commonly used controls
Dit hoofdstuk gaat al terug iets specifieker. Hier staan een aantal speciale besturingselementen beschreven die vaak terugkomen in de applicatie en vaak gebruikt worden in tests. Het kan bijvoorbeeld gaan om de "ProgressBar", die aangeeft wanneer een pagina volledig geladen is.
### 4.3.5 BaseClassCodedUI
In dit hoofdstuk staan wel iets specifiekere zaken beschreven rond de applicatie Maät. Om het effectieve testen van de applicatie zo efficient mogelijk te laten verlopen, zijn er functies beschreven in een algemene baseclass (namelijk BaseClassCodedUI) die bepaalde tests automatisch uitvoeren. Het is tijdens de analyse de taak van de tester om bepaalde paradigma's te gaan uitzoeken (bijvoorbeeld: navigatie naar een andere pagina). Wanneer geanalyseerd is hoe dit moet getest worden wordt dit in een functie geschreven in de BaseClassCodedUI, waardoor dit paradigma bij de volgende test in één of enkele lijnen kan getest worden in plaats van elke keer opnieuw een hele blok code te schrijven.
## 4.4 Result Management Tools
In dit hoofdstuk wordt beschreven hoe de result management tools tot stand zijn gekomen. Het draait hier voornamelijk over het feit dat er nooit echt een goed beeld kan worden gegeven van de status van testing. Deze tools zijn ontwikkeld om de ontwikkelaar en de klant te bewijzen dat tests wel degelijk uitgevoerd werden, en garanderen dat de resultaten onvervalst zijn.
Er zijn twee tools die dit mogelijk maken:
- TRX 2 XML Parser
- Testresult Parser
### 4.4.1 TRX 2 XML Parser
Wanneer Coded UI Tests uitgevoerd worden via MSTest of via Visual Studio zal er een .trx document gegenereerd worden. Dit document bevat alle resultaten en andere informatie omtrent de tests. Het .trx document is opgesteld in een XML-structuur. Omdat dit document teveel informatie bevat wordt er enkel de essentiele informatie uitgehaald en in een nieuw aangemaakt XML document gezet.
#### 4.4.1.1 RegisterTest
RegisterTest is een methode, gedefineerd in de BaseTestClass, die altijd als eerste moet worden aangeroepen binnen een testmethode. Deze methode zorgt ervoor dat er nog meer noodzakelijke informatie in de XML terecht zal komen. Het neemt namenlijk de scherm en paradigma ID op in zijn methode en schrijft deze dan bij uitvoering van de test mee weg in het .trx document. Op deze manier is er een link tussen de test, het scherm en het paradigma waarbij een test-resultaat wordt gegeven.
#### 4.4.1.2 Running tests
In dit onderdeeltje is kort uitgelegd hoe er manueel voor gezorgd werd dat het .trx bestand gegenereerd werd. De bedoeling is uiteraard in de toekomst dat dit mee in de build-straat komt en het zo automatisch gebeurd.
#### 4.4.1.3 Running the TRX 2 XML tool
Omdat er manueel nog variabelen moeten meegegeven worden in het stadium waar de tool zich op het einde van de stage zich bevond, is er duidelijk beschreven hoe dit moet gebeuren.
#### 4.4.1.4 Result XML
Deze XML zal het gegenereerde XML bestand zijn dat voortkomt uit het .trx bestand dat de tests zelf op hun beurt voortbrachten. Belangrijk is om te weten wat er in dit bestand aanwezig is. Het Result XML bestand bevat volgende syntax:
```
<Test TestId=”Test Name” CategoryId =”Category GUID” ObjectId=”Object GUID” ResultLabel=”Outcome”>
```
* TestId
* De test naam (test methode naam) die gegeven was in de code van de test
* CategoryId
* De ID van de category, geschreven als een GUID
* ObjectId
* De ID van het object, geschreven als een GUID
* ResultLabel
* Bevat één van de vier verschillende mogelijke statusen:
* Passed (De test is geslaagd)
* Failed (De test is gefaald)
* Aborted (De test die uitgevoerd werd is manueel geanuleerd)
* Not Executed (De test is niet uitgevoerd geweest)
### 4.4.2 Testresult Parser
Deze tool is de tool waar het allemaal om te doen is als men spreekt over het weergeven van de vooruitgang bij testing. Het neemt drie XML bestanden als input en genereerd hieruit een HTML bestand dat de stand van zake weergeeft.
#### 4.4.2.1 HTML bestand: Result tabel
Om te begrijpen hoe de tool werkt is het noodzakelijk de output te begrijpen. In dit geval genereerd de tool een HTML bestand. Hierin wordt een tabel weergegeven die de progressie van het testen van de applicatie weergeeft. De tabel is opgebouwd uit twee assen die de schermen en paradigma's weerrgeven en heel wat cellen die de status van elke testcase weergeven. Een cel kent 5 staten:
* Passed (100% Completion of test case)
* Failed (< 100% Completion of test case)
* To Do (This test case does not have a test written for it)
* Not To Do (This test case does not need a test written for it)
* Unknown (This test case is not yet been analyzed)
#### 4.4.2.2 Definition XML
De Definition XML is het document waar manueel de assen van de tabel worden gedefineerd. Hier worden de GUID's toegewezen aan elk scherm of besturingselement en elke paradigma. Het Definition XML bestand bevat volgende syntax:
```
<Category id="Category GUID" name="Paradigm" info="Description" level="">
<Object id="Object GUID" name="Screen / Control" info="Description" level="">
```
* CategoryId / ObjectId
* Het ID, geschreven als een GUID
* Name
* Paradigma of scherm/besturingselement naam
* Moet uniek zijn
* Level
* Het level object zal gecalculeerd worden en moet daarom dus niet gedefineerd worden aangezien het toch overschreven zal worden
#### 4.4.2.3 Target XML
Het Target XML bestand defineerd een doel voor elke testcase. Het Target XML bestand bevat volgende syntax:
```
<Target TargetName="Description" CategoryId="Category GUID" ObjectId="Object GUID" TargetLabel="Label"/>
```
* TargetName
* Descriptieve naam van de category of het object (in leesbare tekst)
* Gedaan, enkel om het beter begrijpbaar te maken (GUID alleen is niet leesbaar genoeg)
* CategoryId
* Het ID van de category, geschreven als een GUID
* ObjectId
* Het ID van het object, geschreven als een GUID
* TargetLabel
* Bevat één van vier mogelijke staten:
* To Do (Deze testcase vereist een test)
* Not To Do (Deze testcase vereist geen test)
* Unknown (Deze testcase is nog niet geanalyseerd)
* Done (Deze testcase is manueel toegekend als zijnde 100% compleet)
#### 4.4.2.4 XSD Files
Achter elk XML bestand zit een XSD schema in deze tools. Deze zijn toegevoegd voor een zeer goede reden. Zoals besproken bij de gebruikte tools en software, werd in het project gebruik gemaakt van Xsd2Code++. Deze tool zorgt voor de omzetting van XML objecten naar objecten in Visual Studio. Deze objecten zijn van belang bij de opbouw van de matrix die de resultaten uiteindelijk zal weergeven in een HTML bestand.
#### 4.4.2.5 Running the Testresult Parser tool
De tool werkt in verschillende fasen. Elk in aparte methoden gegoten om een maximaal overzicht te bewaren en een efficiente werking te garanderen.
##### Fase 1: Genereren van matrix in het geheugen
Bestaat uit drie methoden:
- ProcessCategories
- Gebruikt Definition XML om categorieën te maken op de verticale as
- ProcessObjects
- Gebruikt Definition XML om objecten te maken op de horizontale as
- CreateCells
- Maakt cellen en houdt parents en children bij
##### Fase 2: Matrix populeren
Bestaat uit twee methoden:
- ProcessTargetData
- Vult Target XML data in de matrix in aan de hand van de GUID's
- ProcessResultData
- Vult Result XML data in de matrix in aan de hand van de GUID's
##### Fase 3: HTML genereren
Bestaat uit nog eens acht verschillende methoden
* ProduceHtml
* CreateHtmlHead
* Maken van metadata
* CreateHtmlBody
* Maken van de tabel, legende en lijst met gefaalde tests
* CreateTestResultDiv
* Maken van de tabel wrapper
* CreateTestResultTableHead
* Maken van de tabel header (Objecten/Schermen)
* CreateTestResultTableBody
* Maken van tabel body (Cellen / Categorieën)
* CreateLegendDiv
* Maken van legende wrapper
* CreateFailedDiv
* Maken van gefaalde tests wrapper
#### 4.4.2.5 Extra functionaliteit
Er is ook veel tijd gekropen in het "bruikbaar" maken van de matrix. Een oneindig doorlopende reeks van schermen en besturingselementen langs de ene, en een hele hoop paradigmas op de andere as zou resulteren in miljoenen cellen. Deze moeten allemaal zichtbaar gemaakt **kunnen** worden. Maar het is niet handig om een overzicht te krijgen met miljoenen cellen als we maar kort willen kijken hoe de testprocedure ervoor staat. Dus, als oplossing, was het noodzakelijk dat de schermen en besturingselementen, alsook de paradigmas inklapbaar werden gemaakt zodat er een beter overzicht kon gecreërd worden indien de gebruiker dit wenst.
In de toekomst was het ook gepland om de headers te laten zweven, zodat het ten alle tijden duidelijk was waar men zich bevond tijdens het scrollen. Heirvoor was echter niet genoeg tijd weggelegd.
#### 4.4.2.6 Resultaat
Het resultaat is dan de HTML tabel met alle resultaten van de tests, zichtbaar in onderstaande afbeelding.

|
Java
|
UTF-8
| 871 | 2.609375 | 3 |
[] |
no_license
|
package eclipsenetbeans.gui;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import javax.swing.JFrame;
public class ScreenRenderer {
private static Screen screen;
private static JFrame frame = null;
public static void render(Graphics2D g2, Rectangle bounds, double off) {
g2.setColor(Color.gray);
g2.fill(bounds);
screen.render(g2, bounds, off);
}
public static void setFrame(JFrame frame) {
ScreenRenderer.frame = frame;
}
public static void setScreen(Screen s) {
if(screen != null) {
frame.removeMouseMotionListener(screen);
frame.removeMouseListener(screen);
frame.removeMouseWheelListener(screen);
}
screen = s;
frame.addMouseMotionListener(screen);
frame.addMouseListener(screen);
frame.addMouseWheelListener(screen);
}
public static Screen getScreen(Screen s) {
return screen;
}
}
|
Java
|
UTF-8
| 4,712 | 2.078125 | 2 |
[] |
no_license
|
package com.pengheng.core.datasource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import com.pengheng.core.SpringContextUtil;
import com.pengheng.util.Toolkits;
public class ManualTransaction {
public static final int PROPAGATION_REQUIRED = 0;
public static final int PROPAGATION_SUPPORTS = 1;
public static final int PROPAGATION_MANDATORY = 2;
public static final int PROPAGATION_REQUIRES_NEW = 3;
public static final int PROPAGATION_NOT_SUPPORTED = 4;
public static final int PROPAGATION_NEVER = 5;
public static final int PROPAGATION_NESTED = 6;
public static final int ISOLATION_DEFAULT = -1;
public static final int ISOLATION_READ_UNCOMMITTED = 1;
public static final int ISOLATION_READ_COMMITTED = 2;
public static final int ISOLATION_REPEATABLE_READ = 4;
public static final int ISOLATION_SERIALIZABLE = 8;
private TransactionStatus transactionStatus = null;
private DataSourceTransactionManager dataSourceTransactionManager = null;
private static final Logger logger = LoggerFactory.getLogger(ManualTransaction.class);
public ManualTransaction() { this(3, 2); }
public ManualTransaction(int paramInt1, int paramInt2) { this(null, paramInt1, paramInt2); }
public ManualTransaction(String paramString, int paramInt1, int paramInt2) {
if (SpringContextUtil.getApplicationContext() != null) {
if ("".equals(Toolkits.defaultString(paramString))) {
paramString = "dataSourceTransactionManager.default";
}
if (this.dataSourceTransactionManager == null) {
this.dataSourceTransactionManager = (DataSourceTransactionManager)SpringContextUtil.getBean(paramString);
}
DefaultTransactionDefinition defaultTransactionDefinition = new DefaultTransactionDefinition();
defaultTransactionDefinition.setPropagationBehavior(paramInt1);
defaultTransactionDefinition.setIsolationLevel(paramInt2);
this.transactionStatus = this.dataSourceTransactionManager.getTransaction(defaultTransactionDefinition);
if (logger.isDebugEnabled()) {
logger.debug("Create transaction with[" + paramString + "], propagation behavior[" + paramInt1 + "], isolation level[" + paramInt2 + "]");
}
} else {
throw new IllegalStateException("Transaction init failure, spring context is invalid");
}
}
public void commit() {
if (this.dataSourceTransactionManager != null && this.transactionStatus != null) {
this.dataSourceTransactionManager.commit(this.transactionStatus);
if (logger.isDebugEnabled()) {
logger.debug("Commit transaction.");
}
}
}
public void rollback() {
if (this.dataSourceTransactionManager != null && this.transactionStatus != null) {
this.dataSourceTransactionManager.rollback(this.transactionStatus);
if (logger.isDebugEnabled()) {
logger.debug("Rollback.");
}
}
}
public Object createSavepoint() {
Object object = null;
if (this.transactionStatus != null) {
object = this.transactionStatus.createSavepoint();
if (logger.isDebugEnabled()) {
logger.debug("Create savepoint: " + object.getClass().getName());
}
}
return object;
}
public void rollbackToSavepoint(Object paramObject) {
if (this.transactionStatus != null) {
this.transactionStatus.rollbackToSavepoint(paramObject);
if (logger.isDebugEnabled()) {
logger.debug("Rollback to savepoint: " + paramObject.getClass().getName());
}
}
}
public void releaseSavepoint(Object paramObject) {
if (paramObject != null) {
this.transactionStatus.releaseSavepoint(paramObject);
if (logger.isDebugEnabled()) {
logger.debug("Release savepoint: " + paramObject.getClass().getName());
}
}
}
public void setRollbackOnly() {
if (this.transactionStatus != null) {
this.transactionStatus.setRollbackOnly();
if (logger.isDebugEnabled()) {
logger.debug("Set rollback only.");
}
}
}
public void transaction(Runnable paramRunnable) {
try {
paramRunnable.run();
commit();
if (logger.isDebugEnabled()) {
logger.debug("Transaction commit");
}
} catch (Exception exception) {
rollback();
if (logger.isDebugEnabled()) {
logger.debug("Transaction rollback");
}
}
}
}
|
Java
|
UTF-8
| 813 | 1.9375 | 2 |
[
"Apache-2.0"
] |
permissive
|
package app.coronawarn.datadonation.services.ppac.ios.controller.validation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.validation.Constraint;
import javax.validation.Payload;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
@Constraint(validatedBy = EdusOneTimePasswordRequestIosValidator.class)
@Documented
public @interface ValidEdusOneTimePasswordRequestIos {
/**
* Validation message.
*/
String message() default "Invalid payload for otp creation.";
/**
* Validation groups.
*/
Class<?>[] groups() default {};
/**
* Payload type.
*/
Class<? extends Payload>[] payload() default {};
}
|
C++
|
UTF-8
| 2,173 | 2.9375 | 3 |
[] |
no_license
|
#pragma once
#ifndef MPL_DEMO_TWIST_HPP
#define MPL_DEMO_TWIST_HPP
#include <Eigen/Dense>
namespace mpl::demo {
template <class S>
class Twist {
using Scalar = S;
Eigen::Matrix<Scalar, 6, 1> m_;
public:
Twist() {
}
template <typename V, typename R>
Twist(const Eigen::MatrixBase<V>& v, const Eigen::MatrixBase<R>& r) {
m_.template head<3>() = v;
m_.template tail<3>() = r;
}
template <typename R>
static Twist rotation(const Eigen::MatrixBase<R>& axis) {
return Twist(Eigen::Matrix<Scalar, 3, 1>::Zero(), axis);
}
template <typename T>
static Twist translation(const Eigen::MatrixBase<T>& dir) {
return Twist(dir, Eigen::Matrix<Scalar, 3, 1>::Zero());
}
decltype(auto) velocity() {
return m_.template head<3>();
}
decltype(auto) velocity() const {
return m_.template head<3>();
}
decltype(auto) rotation() {
return m_.template tail<3>();
}
decltype(auto) rotation() const {
return m_.template tail<3>();
}
void setZero() {
m_.setZero();
}
const auto& matrix() const {
return m_;
}
template <class V>
Twist refPoint(const Eigen::MatrixBase<V>& vBaseAB) {
return Twist(
velocity() + rotation().cross(vBaseAB),
rotation());
}
static Twist diff(
const Eigen::Transform<Scalar, 3, Eigen::AffineCompact>& a,
const Eigen::Transform<Scalar, 3, Eigen::AffineCompact>& b)
{
Eigen::AngleAxis<Scalar> aa(a.linear().transpose() * b.linear());
return Twist(
b.translation() - a.translation(),
a.linear() * (aa.axis() * aa.angle()));
}
};
template <class M, class S>
Twist<S> operator * (const Eigen::MatrixBase<M>& m, const Twist<S>& tw) {
return { m * tw.velocity(), m * tw.rotation() };
}
}
#endif
|
Java
|
UTF-8
| 743 | 2.265625 | 2 |
[] |
no_license
|
package com.example.demo.dao.Model;
import javax.persistence.*;
import java.util.List;
@Entity
public class Zespol {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@ManyToMany(targetEntity = Pracownik.class, mappedBy = "zespoly", cascade = CascadeType.ALL)
private List<Pracownik> pracownicy;
public Zespol() {
}
public Zespol(Long id, String name) {
this.id = id;
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
|
C
|
UTF-8
| 3,796 | 2.53125 | 3 |
[] |
no_license
|
/***********************************************************************
* FILENAME : SmartLock.c
* AUTHOR: Justin Barnitz, Kevin Loeffler
* DATE: NOV 2016
* DESCRIPTION: LPC 1115 xpresso board. Recieves bluetooth commands to
* control servo motor, to lock/unlock door.
*
* PIN LAYOUT:
* Pin 2.0 => PWM for servo
* Pin 2.1 => Red LED
* Pin 2.2 => Green LED
***********************************************************************/
#ifdef __USE_CMSIS
#include "LPC11xx.h"
#endif
#include "driver_config.h"
#include "target_config.h"
#include "timer32.h"
#include "gpio.h"
#include "uart.h"
#include <cr_section_macros.h>
#include <stdio.h>
volatile uint32_t duty = 49;
volatile uint32_t counter = 0;
volatile uint32_t period = 300; // Signal Period is 3ms (333Hz)
volatile uint32_t isLocked = 0;
volatile uint32_t isUART = 0;
volatile uint32_t turned = 0;
extern volatile uint32_t UARTCount;
extern volatile uint8_t UARTBuffer[BUFSIZE];
void TIMERInit()
{
LPC_SYSCON->SYSAHBCLKCTRL |= (1<<9); //enable CT32B0 32-bit counter/timer 0 in System AHB clock control register
LPC_IOCON->PIO1_5 &= ~0x07; /* Timer0_32 I/O config */
LPC_IOCON->PIO1_5 |= 0x02; /* Timer0_32 CAP0 */
// Clear the EMR
LPC_TMR32B0->EMR &= ~(0xFF<<4);
// Set External Match Control 0,1,2,3 to Toggle the corresponding External Match bit/output
LPC_TMR32B0->EMR |= ((0x3<<4)|(0x3<<6)|(0x3<<8)|(0x3<<10));
/*
The Match register values are continuously compared to the Timer Counter value. When
the two values are equal, actions can be triggered automatically. The action possibilities
are to generate an interrupt, reset the Timer Counter, or stop the timer. Actions are
controlled by the settings in the MCR register.
*/
//LPC_TMR32B0->MR0 = SystemCoreClock/1000-1; //ticks every 1 ms
LPC_TMR32B0->MR0 = SystemCoreClock/100000-1; //ticks every 1/100 ms
LPC_TMR32B0->TCR = 0x01; // start the timer(s)
/* Bit 0 -> Interrupt on MR0: an interrupt is generated when MR0 matches the value in the TC */
/* Bit 1 -> Reset on MR0: the TC will be reset if MR0 matches it. */
LPC_TMR32B0->MCR = 0x03;
NVIC_EnableIRQ(TIMER_32_0_IRQn);
NVIC_SetPriority(TIMER_32_0_IRQn, 0);
return;
}
void TIMER32_0_IRQHandler(void)
{
counter++;
if( counter == 1 )
{
// start off a new period, turn on signal
GPIOSetValue(2, 0, 1);
}
else if( counter == (( duty * period ) / 100 ))
{
// end of duty cycle turn off signal
GPIOSetValue(2, 0, 0);
}
else if( counter >= period )
{
counter = 0;
turned++;
}
// clear the register
LPC_TMR32B0->IR = (0x1<<0);
return;
}
void Lock()
{
//if(!isLocked)
//{
enable_timer32(0);
turned = 0;
duty = 25;
counter = 0;
while(turned < 100){}
duty = 49;
disable_timer32(0);
GPIOSetValue(2, 2, 0); // turn off grn LED
GPIOSetValue(2, 1, 1); // turn on red LED
isLocked = 1;
//}
}
void Unlock()
{
//if(isLocked)
//{
enable_timer32(0);
turned = 0;
duty = 70;
counter = 0;
while(turned < 100){} //old 75 = about 90 deg
duty = 49;
disable_timer32(0);
GPIOSetValue(2, 1, 0); // turn off red LED
GPIOSetValue(2, 2, 1); // turn on grn LED
isLocked = 0;
//}
}
int main(void)
{
TIMERInit();
GPIOInit();
UARTInit(115200);
GPIOSetDir(2, 0, 1); // output Pin 2 port 0 for servo control
GPIOSetDir(2, 1, 1); // output pin 2.1 red LED for locked
GPIOSetDir(2, 2, 1); // output pin 2.2 green LED for unlock
disable_timer32(0);
while(1)
{
if (UARTCount != 0)
{
LPC_UART->IER = IER_THRE | IER_RLS; /* Disable RBR */
UARTSend( (uint8_t *)UARTBuffer, UARTCount );
if(UARTBuffer[0] == 'c')
{
Lock();
}
else if(UARTBuffer[0] == 'o')
{
Unlock();
}
UARTCount = 0;
LPC_UART->IER = IER_THRE | IER_RLS | IER_RBR; /* Re-enable RBR */
}
}
}
|
Markdown
|
UTF-8
| 382 | 2.5625 | 3 |
[] |
no_license
|
# 登录记录(t_sys_login_log)
| 列名 | 类型 | KEY | 可否为空 | 注释 |
| ---- | ---- | ---- | ---- | ---- |
|id|int(65)|PRI|否|主键|
|logname|varchar(255)||是|日志名称|
|userid|int(65)||是|管理员id|
|create_time|datetime||是|创建时间|
|succeed|varchar(255)||是|是否执行成功|
|message|text||是|具体消息|
|ip|varchar(255)||是|登录ip|
|
C#
|
UTF-8
| 6,672 | 3.03125 | 3 |
[
"MIT"
] |
permissive
|
// ############################################################################
// # Galen Lanphier #
// # https://github.com/lanphiergm/AdventOfCodeCS #
// # MIT License. See LICENSE file #
// ############################################################################
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace AdventOfCode.Puzzles.Year2020
{
/// <summary>
/// Day 23: Crab Cups
/// https://adventofcode.com/2020/day/23
/// </summary>
[TestClass]
public class Day23CrabCups
{
/// <summary>
/// Part 1 of the puzzle using sample input
/// </summary>
[TestMethod]
public void Part1_SampleInput()
{
Assert.AreEqual("67384529", ExecutePart1(sampleInput));
}
/// <summary>
/// Part 1 of the puzzle using my actual puzzle input
/// </summary>
[TestMethod]
public void Part1_PuzzleInput()
{
Assert.AreEqual("65432978", ExecutePart1(puzzleInput));
}
/// <summary>
/// Part 2 of the puzzle using sample input
/// </summary>
[TestMethod]
public void Part2_SampleInput()
{
Assert.AreEqual(149245887792L, ExecutePart2(sampleInput));
}
/// <summary>
/// Part 2 of the puzzle using my actual puzzle input
/// </summary>
[TestMethod]
public void Part2_PuzzleInput()
{
Assert.AreEqual(287230227046L, ExecutePart2(puzzleInput));
}
/// <summary>
/// Executes part 1 of the puzzle
/// </summary>
/// <param name="initialLabels">The starting labels</param>
/// <returns>The labels of the cups after cup 1</returns>
/// <remarks>
/// TODO: this part takes ~30 seconds to execute. Find a faster solution?
/// </remarks>
private static string ExecutePart1(string initialLabels)
{
var (labels, nodeIndex) = GetInitialLabels(initialLabels);
PerformMoves(labels, nodeIndex, 100);
var builder = new StringBuilder();
var node1 = nodeIndex[1];
var node = node1.Next ?? labels.First;
while (node != node1)
{
builder.Append(node.Value);
node = node.Next ?? labels.First;
}
return builder.ToString();
}
/// <summary>
/// Executes part 2 of the puzzle
/// </summary>
/// <param name="initialLabels">The starting labels</param>
/// <returns>The product of the labels of the two cups clockwise of cup 1</returns>
private static long ExecutePart2(string initialLabels)
{
var (labels, nodeIndex) = GetInitialLabels(initialLabels);
for (int i = 10; i <= 1000000; i++)
{
labels.AddLast(i);
nodeIndex[i] = labels.Last;
}
PerformMoves(labels, nodeIndex, 10000000);
var node = nodeIndex[1];
var nodePlus1 = node.Next ?? labels.First;
var nodePlus2 = nodePlus1.Next ?? labels.First;
return (long)nodePlus1.Value * nodePlus2.Value;
}
/// <summary>
/// Performs the specified number of moves
/// </summary>
/// <param name="labels">The list of labels</param>
/// <param name="nodeIndex">The indexes of the nodes</param>
/// <param name="count">The number of moves to make</param>
private static void PerformMoves(LinkedList<int> labels,
Dictionary<int, LinkedListNode<int>> nodeIndex, int count)
{
int max = labels.Max();
var currNode = labels.First;
int[] pickedUp = new int[3];
for (int i = 0; i < count; i++)
{
// Select the cards to pick up and remove them
for (int j = 0; j < 3; j++)
{
if (currNode == labels.Last)
{
pickedUp[j] = labels.First.Value;
labels.RemoveFirst();
}
else
{
pickedUp[j] = currNode.Next.Value;
labels.Remove(currNode.Next);
}
}
// Determine the target number
int destination = currNode.Value - 1;
if (destination == 0)
{
destination = max;
}
while (pickedUp.Contains(destination))
{
destination--;
if (destination == 0)
{
destination = max;
}
}
// Insert the picked up cups after the target and update the node index
var destinationNode = nodeIndex[destination];
labels.AddAfter(destinationNode, pickedUp[0]);
nodeIndex[pickedUp[0]] = destinationNode.Next;
labels.AddAfter(destinationNode.Next, pickedUp[1]);
nodeIndex[pickedUp[1]] = destinationNode.Next.Next;
labels.AddAfter(destinationNode.Next.Next, pickedUp[2]);
nodeIndex[pickedUp[2]] = destinationNode.Next.Next.Next;
// Move to the next cup, wrapping around to the beginning if necessary
currNode = currNode.Next ?? labels.First;
}
}
/// <summary>
/// Creates the necessary structures from the initial labels
/// </summary>
/// <param name="initialLabels">The starting labels</param>
/// <returns>The initialized data structures</returns>
private static (LinkedList<int> labels, Dictionary<int, LinkedListNode<int>> nodeIndex)
GetInitialLabels(string initialLabels)
{
var labels = new LinkedList<int>();
var nodeIndex = new Dictionary<int, LinkedListNode<int>>();
foreach (char c in initialLabels)
{
labels.AddLast(int.Parse(c.ToString()));
nodeIndex[labels.Last.Value] = labels.Last;
}
return (labels, nodeIndex);
}
private const string sampleInput = "389125467";
private const string puzzleInput = "962713854";
}
}
|
Markdown
|
UTF-8
| 7,294 | 2.921875 | 3 |
[
"CC-BY-4.0",
"MIT"
] |
permissive
|
---
title: Manage secrets in Azure Container Apps
description: Learn to store and consume sensitive configuration values in Azure Container Apps.
services: container-apps
author: craigshoemaker
ms.service: container-apps
ms.topic: how-to
ms.date: 09/29/2022
ms.author: cshoe
ms.custom: event-tier1-build-2022, ignite-2022
---
# Manage secrets in Azure Container Apps
Azure Container Apps allows your application to securely store sensitive configuration values. Once secrets are defined at the application level, secured values are available to container apps. Specifically, you can reference secured values inside scale rules. For information on using secrets with Dapr, refer to [Dapr integration](./dapr-overview.md)
- Secrets are scoped to an application, outside of any specific revision of an application.
- Adding, removing, or changing secrets doesn't generate new revisions.
- Each application revision can reference one or more secrets.
- Multiple revisions can reference the same secret(s).
An updated or deleted secret doesn't automatically affect existing revisions in your app. When a secret is updated or deleted, you can respond to changes in one of two ways:
1. Deploy a new revision.
2. Restart an existing revision.
Before you delete a secret, deploy a new revision that no longer references the old secret. Then deactivate all revisions that reference the secret.
> [!NOTE]
> Container Apps doesn't support Azure Key Vault integration. Instead, enable managed identity in the container app and use the [Key Vault SDK](../key-vault/general/developers-guide.md) in your app to access secrets.
## Defining secrets
# [ARM template](#tab/arm-template)
Secrets are defined at the application level in the `resources.properties.configuration.secrets` section.
```json
"resources": [
{
...
"properties": {
"configuration": {
"secrets": [
{
"name": "queue-connection-string",
"value": "<MY-CONNECTION-STRING-VALUE>"
}],
}
}
}
```
Here, a connection string to a queue storage account is declared in the `secrets` array. In this example, you would replace `<MY-CONNECTION-STRING-VALUE>` with the value of your connection string.
# [Azure CLI](#tab/azure-cli)
When you create a container app, secrets are defined using the `--secrets` parameter.
- The parameter accepts a space-delimited set of name/value pairs.
- Each pair is delimited by an equals sign (`=`).
```bash
az containerapp create \
--resource-group "my-resource-group" \
--name queuereader \
--environment "my-environment-name" \
--image demos/queuereader:v1 \
--secrets "queue-connection-string=$CONNECTION_STRING"
```
Here, a connection string to a queue storage account is declared in the `--secrets` parameter. The value for `queue-connection-string` comes from an environment variable named `$CONNECTION_STRING`.
# [PowerShell](#tab/powershell)
When you create a container app, secrets are defined as one or more Secret objects that are passed through the `ConfigurationSecrets` parameter.
```azurepowershell
$EnvId = (Get-AzContainerAppManagedEnv -ResourceGroupName my-resource-group -EnvName my-environment-name).Id
$TemplateObj = New-AzContainerAppTemplateObject -Name queuereader -Image demos/queuereader:v1
$SecretObj = New-AzContainerAppSecretObject -Name queue-connection-string -Value $QueueConnectionString
$ContainerAppArgs = @{
Name = 'my-resource-group'
Location = '<location>'
ResourceGroupName = 'my-resource-group'
ManagedEnvironmentId = $EnvId
TemplateContainer = $TemplateObj
ConfigurationSecret = $SecretObj
}
New-AzContainerApp @ContainerAppArgs
```
Here, a connection string to a queue storage account is declared. The value for `queue-connection-string` comes from an environment variable named `$QueueConnectionString`.
---
## <a name="using-secrets"></a>Referencing secrets in environment variables
After declaring secrets at the application level as described in the [defining secrets](#defining-secrets) section, you can reference them in environment variables when you create a new revision in your container app. When an environment variable references a secret, its value is populated with the value defined in the secret.
## Example
The following example shows an application that declares a connection string at the application level. This connection is referenced in a container environment variable and in a scale rule.
# [ARM template](#tab/arm-template)
In this example, the application connection string is declared as `queue-connection-string` and becomes available elsewhere in the configuration sections.
:::code language="json" source="code/secure-app-arm-template.json" highlight="11,12,13,27,28,29,30,31,44,45,61,62":::
Here, the environment variable named `connection-string` gets its value from the application-level `queue-connection-string` secret. Also, the Azure Queue Storage scale rule's authentication configuration uses the `queue-connection-string` secret as to define its connection.
To avoid committing secret values to source control with your ARM template, pass secret values as ARM template parameters.
# [Azure CLI](#tab/azure-cli)
In this example, you create a container app using the Azure CLI with a secret that's referenced in an environment variable. To reference a secret in an environment variable in the Azure CLI, set its value to `secretref:`, followed by the name of the secret.
```bash
az containerapp create \
--resource-group "my-resource-group" \
--name myQueueApp \
--environment "my-environment-name" \
--image demos/myQueueApp:v1 \
--secrets "queue-connection-string=$CONNECTIONSTRING" \
--env-vars "QueueName=myqueue" "ConnectionString=secretref:queue-connection-string"
```
Here, the environment variable named `connection-string` gets its value from the application-level `queue-connection-string` secret.
# [PowerShell](#tab/powershell)
In this example, you create a container using Azure PowerShell with a secret that's referenced in an environment variable. To reference the secret in an environment variable in PowerShell, set its value to `secretref:`, followed by the name of the secret.
```azurecli
$EnvId = (Get-AzContainerAppManagedEnv -ResourceGroupName my-resource-group -EnvName my-environment-name).Id
$SecretObj = New-AzContainerAppSecretObject -Name queue-connection-string -Value $QueueConnectionString
$EnvVarObjQueue = New-AzContainerAppEnvironmentVarObject -Name QueueName -Value myqueue
$EnvVarObjConn = New-AzContainerAppEnvironmentVarObject -Name ConnectionString -SecretRef queue-connection-string -Value secretref
$TemplateObj = New-AzContainerAppTemplateObject -Name myQueueApp -Image demos/myQueueApp:v1 -Env $EnvVarObjQueue, $EnvVarObjConn
$ContainerAppArgs = @{
Name = 'myQueueApp'
Location = '<location>'
ResourceGroupName = 'my-resource-group'
ManagedEnvironmentId = $EnvId
TemplateContainer = $TemplateObj
ConfigurationSecret = $SecretObj
}
New-AzContainerApp @ContainerAppArgs
```
Here, the environment variable named `ConnectionString` gets its value from the application-level `$QueueConnectionString` secret.
---
## Next steps
> [!div class="nextstepaction"]
> [Containers](containers.md)
|
Markdown
|
UTF-8
| 2,344 | 3.140625 | 3 |
[
"Unlicense"
] |
permissive
|
# Relevance logic
**Relevance logic** (also relevant logic) is a substructural logic that requires that antecedent and consequent of implications be relevantly related.
Relevance logic aims to capture aspects of implication that are ignored by the "material implication" operator in classical truth-functional logic, namely the notion of relevance between antecedent and conditional of a true implication.
This idea is not new: C. I. Lewis was led to invent modal logic, and specifically strict implication, on the grounds that classical logic grants paradoxes of material implication such as the principle that a falsehood implies any proposition.
Hence "if I'm a donkey, then two and two is four" is true when translated as a material implication, yet it seems intuitively false since a true implication must tie the antecedent and consequent together by some notion of relevance. And whether or not I'm a donkey seems in no way relevant to whether two and two is four.
How does relevance logic formally capture a notion of relevance? In terms of a syntactical constraint for a propositional calculus, it is necessary, but not sufficient, that premises and conclusion share atomic formulae (formulae that do not contain any logical connectives).
In a predicate calculus, relevance requires sharing of variables and constants between premises and conclusion. This can be ensured (along with stronger conditions) by, e.g., placing certain restrictions on the rules of a natural deduction system.
In particular, a Fitch-style natural deduction can be adapted to accommodate relevance by introducing tags at the end of each line of an application of an inference indicating the premises relevant to the conclusion of the inference.
Gentzen-style sequent calculi can be modified by removing the weakening rules that allow for the introduction of arbitrary formulae on the right or left side of the sequents.
A notable feature of relevance logics is that they are paraconsistent logics: the existence of a contradiction will not cause "explosion".
This follows from the fact that a conditional with a contradictory antecedent that does not share any propositional or predicate letters with the consequent cannot be true (or derivable).
---
https://en.wikipedia.org/wiki/Relevance_logic
http://plato.stanford.edu/entries/logic-relevance/
|
Markdown
|
UTF-8
| 1,038 | 2.8125 | 3 |
[
"BSD-3-Clause",
"CC-BY-4.0"
] |
permissive
|
# SI 506: Lab Exercise 06
This week's lab focuses on a new data construct, tuples, and on implementing a quick function for the quiz.
You will complete two exercises involving tuples so that you can become familiar with how they work,
and why they are so important to python. You will also get to implement a function on your own and call it.
This will be a timed activity in the lab to familiarize you with the format of the midterm.
Retrieve the lab exercise 06 template file and README in Canvas Files or from the Github
[SI506-2020Winter](https://github.com/umsi-arwhyte/SI506-2020Winter/tree/master/code/lab_exercise_06)
repo.
When you have completed the problem set click on the Gradescope link in Canvas and upload your
`lab_exercise_06.py` file to the Gradescope site. Your submission will be auto-graded and any runtime
errors encountered will be recorded and displayed. You may re-submit your exercise as many
times as is necessary before the close date. Late submissions will be penalized as described
in the syllabus.
|
PHP
|
UTF-8
| 2,394 | 2.921875 | 3 |
[] |
no_license
|
<?php
namespace App\Service;
use Symfony\Component\HttpFoundation\File\Exception\FileException;
use Symfony\Component\HttpFoundation\File\UploadedFile;
class FileUploader
{
/**
* @var
*/
private $targetDirectoryActualite;
/**
* @var
*/
private $targetDirectorySpectacle;
/**
* FileUploader constructor.
* @param $targetDirectoryActualite
* @param $targetDirectorySpectacle
*/
public function __construct($targetDirectoryActualite, $targetDirectorySpectacle) {
$this->targetDirectoryActualite = $targetDirectoryActualite;
$this->targetDirectorySpectacle = $targetDirectorySpectacle;
}
/**
* @param UploadedFile $file
* @return string
*/
public function uploadImgActualite(UploadedFile $file)
{
$originalFilename = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
$safeFilename = transliterator_transliterate(
'Any-Latin; Latin-ASCII; [^A-Za-z0-9_] remove; Lower()',
$originalFilename
);
$fileName = $safeFilename.'-'.uniqid().'.'.$file->guessExtension();
try {
$file->move($this->getTargetDirectoryActulite(), $fileName);
} catch (FileException $e) {
// ... handle exception if something happens during file upload
}
return $fileName;
}
/**
* @param UploadedFile $file
* @return string
*/
public function uploadImgSpectacle(UploadedFile $file)
{
$originalFilename = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
$safeFilename = transliterator_transliterate(
'Any-Latin; Latin-ASCII; [^A-Za-z0-9_] remove; Lower()',
$originalFilename
);
$fileName = $safeFilename.'-'.uniqid().'.'.$file->guessExtension();
try {
$file->move($this->getTargetDirectorySpectacle(), $fileName);
} catch (FileException $e) {
// ... handle exception if something happens during file upload
}
return $fileName;
}
/**
* @return mixed
*/
public function getTargetDirectoryActulite()
{
return $this->targetDirectoryActualite;
}
/**
* @return mixed
*/
public function getTargetDirectorySpectacle()
{
return $this->targetDirectorySpectacle;
}
}
|
Python
|
UTF-8
| 1,079 | 4.46875 | 4 |
[] |
no_license
|
#1. Integer
# add(+), subtract(-), multiply(*) and divide(/)
2 + 3
3-2
2*3
3/2
# multiplication
3 ** 2 # result = 9
print(3**2)
3 ** 3 # result = 27
print(3**3)
# multiple operation
(2+ 3)*4
# 2. Floats
# same integer
# 3. Integer and Floats
# Divide always get a Float
4/2 # result = 2.0
print(4/2)
# mix an integer and float then output is float
print(1 + 2.0)
print(2*3.0)
print(3.0 ** 2)
# 4. Underscores in Numbers
# Python ignore the underscores when storing value of integer and float;
underscores_value = 2900_0000
print(underscores_value)
# 1_00 == 1_0_0 = 10_0 Only available in Python 3.6 and later
# 5 Multiple Assignment
x, y, z = 0, 0, 0
print(x)
print(y)
print(z)
m, n, k = 'a', 'b', 'c'
print(m)
print(n)
print(k)
# 6. Constants
# A constants like a variable but all capital letters and never be changed.
MAX_CONNECTION = 5000;
print(MAX_CONNECTION)
MAX_CONNECTION = 500
print(MAX_CONNECTION) # result = 500;
# Python doesn't build-in constant type. It use all capital letter to indicate
# a variable as constant and you remember not change value of it.
|
C++
|
UTF-8
| 964 | 2.515625 | 3 |
[] |
no_license
|
#ifndef TCPCLIENT_H
#define TCPCLIENT_H
//System Includes
#include <netdb.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <pthread.h>
#include <queue>
#include <semaphore.h>
//User Includes
#include "../Core/comm/globals.h"
#include "../Core/comm/data/servermessage.h"
#include "../Core/Logger.h"
#include "../Core/comm/tcpconnection.h"
class TCPClient
{
public:
bool Connect(const std::string& ip, const std::string& port);
void Disconnect();
void StartRdThread(std::queue<ServerMessage> *msgQueue, sem_t *semSM);
ServerMessage Login(std::string playerName);
void SendMessage(std::string message);
bool IsConnected();
void Logout();
void setClientId(int id) { clientId_ = id; }
private:
static void* ReadThread(void*);
bool connected_;
std::queue<ServerMessage> *msgBuff_;
sem_t *semSM_;
int tcpSocket_;
int clientId_;
pthread_t rThread_;
};
#endif // TCPCLIENT_H
|
C++
|
UTF-8
| 832 | 2.6875 | 3 |
[] |
no_license
|
#include<iostream>
using namespace std;
main()
{
int t;
scanf("%d",&t);
while(t--)
{
int a[105]={0},n=3,i;
long long int j;
long long int sum=0;
cin>>n;
for(i=0;i<n;i++)
{
cin>>a[i];
sum+=a[i];
}
bool prev[sum+2],curr[sum+2];
for(j=1;j<=sum;j++)
prev[j]=0;//base condition 1 : if sum is not zero prev[j]=0
prev[0]=1;//base condition 2 : if sum is zero prev[0]=1
for(i=1;i<=n;i++)
{
int lastelement=a[i-1];
prev[0]=1;
for(j=1;j<=sum;j++)
{
if(j<lastelement)
curr[j]=prev[j];
else
curr[j]=prev[j] || prev[j-lastelement];
}
for(int k=1;k<=sum;k++)
{
prev[k]=curr[k];//update previous array with the current array
//value for the next iteration
}
}
long long int sum1=0;
for(j=1;j<=sum;j++)
{
sum1+=(curr[j])?(j):(0);
}
cout<<sum1<<endl;
}
}
|
JavaScript
|
UTF-8
| 1,394 | 2.9375 | 3 |
[
"MIT"
] |
permissive
|
/* global PubSub, test, ok, equal, deepEqual, start, asyncTest, expect */
test('test listener length', function () {
var pubSub = new PubSub();
equal(pubSub.listeners.length, 0, 'unused pubSub has no listeners');
var token1 = pubSub.subscribe(function () {}, function () {});
pubSub.subscribe(function () {}, function () {});
pubSub.subscribe(function () {}, function () {});
equal(pubSub.listeners.length, 3, 'pubSub has 3 listeners after 3 subscriptions');
pubSub.unsubscribe(token1);
equal(pubSub.listeners.length, 2, 'listeners length decreases by one after unsubscribe');
pubSub.unsubscribeAll();
equal(pubSub.listeners.length, 0, 'unused pubSub has no listeners after unsubscribeAll');
});
asyncTest('test publish/subscribe', function () {
expect(3);
var message1 = { num: 0 };
var message2 = { num: 1 };
var pubSub = new PubSub();
var callback1 = function (message) {
// this is called for every message (2 times)
ok(true, 'callback1 has been called');
};
var callback2 = function (message) {
// this should be called exactly _once_ when message1 is published
deepEqual(message, message1, 'callback2 receives the right message');
start();
};
pubSub.subscribe(callback1, function (message) {
return true;
});
pubSub.subscribe(callback2, function (message) {
return message.num === 0;
});
pubSub.publish(message1);
pubSub.publish(message2);
});
|
Java
|
UTF-8
| 1,183 | 3 | 3 |
[] |
no_license
|
package com.XPeru.chess;
import java.util.ArrayList;
import java.util.List;
public class Queen extends ChessPieceBase {
public Queen(int xPosition, int yPosition) {
super(xPosition, yPosition);
this.setNamePiece('Q');
}
@Override
boolean canBeChecked() {
// TODO Auto-generated method stub
return false;
}
@Override
boolean isSupportCastle() {
// TODO Auto-generated method stub
return false;
}
@Override
List<Point> possiblePositions() {
int x = this.xPosition;
int y = this.yPosition;
List<Point> possiblePositions = new ArrayList<Point>();
for (int j = 0; j <= 7; j++) {
if (j != y) {
possiblePositions.add(new Point(x, j));
}
if (j != x) {
possiblePositions.add(new Point(j, y));
}
}
int i = 1;
while (x - i > 0) {
if (y + i <= 7) {
possiblePositions.add(new Point(x - i, y + i));
}
if (y - i >= 0) {
possiblePositions.add(new Point(x - i, y - i));
}
i++;
}
i = 1;
while (x + i <= 7) {
if (y + i <= 7) {
possiblePositions.add(new Point(x + i, y + i));
}
if (y - i >= 0) {
possiblePositions.add(new Point(x + i, y - i));
}
i++;
}
return possiblePositions;
}
}
|
Python
|
UTF-8
| 281 | 2.734375 | 3 |
[] |
no_license
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
""" Login management script """
from getpass import getpass
def get_username():
return input("Username: ")
def get_password():
return getpass("Password: ")
if __name__ == "__main__":
print("Not directly executable")
|
TypeScript
|
UTF-8
| 1,160 | 2.578125 | 3 |
[
"MIT"
] |
permissive
|
import { BeerType } from '../enums/beer-type.enum';
import { BeerService } from './beer.service';
describe('BeerService', () => {
it('should insert new beer', async () => {
const srv = new BeerService();
srv.insert({ name: 'banana', beerType: BeerType.LAGER }).subscribe();
srv.fetchAllBeers().subscribe((col) => expect(col.length).toEqual(1));
});
it('should find new beer by name after search', async () => {
const srv = new BeerService();
srv.insert({ name: 'banana', beerType: BeerType.LAGER }).subscribe();
srv.searchBeers('bAn').subscribe((col) => expect(col.length).toEqual(1));
});
it('should update new beer', async () => {
const srv = new BeerService();
let collection;
srv.insert({ name: 'banana', beerType: BeerType.LAGER }).subscribe();
srv.searchBeers('bAn').subscribe((col) => (collection = col));
expect(collection.length).toBe(1);
expect(srv.findById(collection[0].id)).not.toBeUndefined();
srv.update({...collection[0], ...{ rating: 5 } });
srv.searchBeers('bAn').subscribe((col) => (collection = col));
expect(collection[0].rating).toEqual(5);
});
});
|
PHP
|
UTF-8
| 12,536 | 2.5625 | 3 |
[] |
no_license
|
<?php
require_once('../../clases/includes/dbmanejador.php');
class Modelo {
function Modelo(){
}
function consulta_familia($nombre_familia, $modelo_familia, $estilo_id){
$con = new DBmanejador;
if($con->conectar() == true){
$consulta = '
SELECT f.familia_id, i.marca, i.modelo, e.nombre_estilo, f.nombre_familia
FROM `tipo_producto` tp, `familia` f, `estilo` e, `familia_integrante` fi, `integrante` i
WHERE tp.producto_id = f.producto_id AND
f.estilo_id = e.estilo_id AND
f.familia_id = fi.familia_id AND
fi.integrante_id = i.integrante_id AND
f.estado = 1 AND
e.estado = 1 AND
i.estado = 1 AND
(i.marca LIKE "%'.$nombre_familia.'%" or i.modelo LIKE "%'.$modelo_familia.'%") AND
e.estilo_id = '.$estilo_id.'
ORDER BY i.marca';
//echo "<br>consulta es.....".$consulta;
$resultado = mysql_query($consulta) or die ('La consulta -consulta familia- falló: ' . mysql_error());
if (!$resultado)
return false;
else {
while($row = mysql_fetch_array($resultado)){
$respuesta[$row[0]]["ffamilia_id"] = $row['familia_id'];
$respuesta[$row[0]]["imarca"][$row[1]] = $row['marca'];
$respuesta[$row[0]]["imodelo"][$row[1]][] = $row['modelo'];
$respuesta[$row[0]]["enombre_estilo"] = $row['nombre_estilo'];
$respuesta[$row[0]]["fnombrefamilia"] = $row['nombre_familia'];
}
return $respuesta;
}
}
}
//verificar estilos
function verificar_estilo($descrip){
$con = new DBmanejador;
if($con->conectar() == true){
$consulta = "
SELECT estilo_id
FROM estilo
WHERE nombre_estilo ='". $descrip ."'";
$resultado = mysql_query($consulta) or die('La consulta -verificar estilo- falló: ' . mysql_error());
if (!$resultado)
return false;
else {
$contador = 0;
while($row = mysql_fetch_array($resultado)){
$estilo_id = $row['estilo_id'];
$contador ++;
}
if($contador == 0)
$estilo_id = -1;
}
return $estilo_id;
}
}
function consulta_familia_existe($nombre_familia, $modelo_familia, $estilo_id){
$con = new DBmanejador;
if($con->conectar() == true){
$consulta = '
SELECT f.familia_id, i.marca, i.modelo, e.nombre_estilo, f.nombre_familia
FROM `tipo_producto` tp, `familia` f, `estilo` e, `familia_integrante` fi, `integrante` i
WHERE tp.producto_id = f.producto_id AND
f.estilo_id = e.estilo_id AND
f.familia_id = fi.familia_id AND
fi.integrante_id = i.integrante_id AND
f.estado = 1 AND
e.estado = 1 AND
i.estado = 1 AND
i.marca = "'.$nombre_familia.'" and i.modelo = "'.$modelo_familia.'" AND
e.estilo_id = '.$estilo_id.'
ORDER BY i.marca';
//echo "<br>consulta es.....".$consulta;
$resultado = mysql_query($consulta) or die ('La consulta -consultar familia existe- falló: ' . mysql_error());
if (!$resultado)
return false;
else {
while($row = mysql_fetch_array($resultado)){
$respuesta[$row[0]]["ffamilia_id"] = $row['familia_id'];
$respuesta[$row[0]]["imarca"][$row[1]] = $row['marca'];
$respuesta[$row[0]]["imodelo"][$row[1]][] = $row['modelo'];
$respuesta[$row[0]]["enombre_estilo"] = $row['nombre_estilo'];
$respuesta[$row[0]]["fnombrefamilia"] = $row['nombre_familia'];
}
return $respuesta;
}
}
}
function consulta_familia_cadena($familia_id, $estilo_id){
$con = new DBmanejador;
if($con->conectar() == true){
$consulta = '
SELECT f.familia_id, UPPER(i.marca) as marca , UPPER(i.modelo) as modelo, e.nombre_estilo, f.nombre_familia , i.marca as marca1 , i.modelo as modelo1
FROM `tipo_producto` tp, `familia` f, `estilo` e, `familia_integrante` fi, `integrante` i
WHERE tp.producto_id = f.producto_id AND
f.estilo_id = e.estilo_id AND
f.familia_id = fi.familia_id AND
fi.integrante_id = i.integrante_id AND
f.estado = 1 AND
e.estado = 1 AND
i.estado = 1 AND
f.familia_id = '.$familia_id.' AND
e.estilo_id = '.$estilo_id.'
ORDER BY marca1, i.modelo';
//echo "<br>consulta es.....".$consulta;
$resultado = mysql_query($consulta) or die ('La consulta -consulta familia cadena- falló: ' . mysql_error());
if (!$resultado)
return false;
else {
while($row = mysql_fetch_array($resultado)){
$respuesta[$row[0]]["ffamilia_id"] = $row['familia_id'];
$respuesta[$row[0]]["imarca"][$row['marca']] = trim($row['marca1']);
$respuesta[$row[0]]["imodelo"][$row['marca']][] = trim($row['modelo1']);
$respuesta[$row[0]]["enombre_estilo"] = $row['nombre_estilo'];
$respuesta[$row[0]]["fnombrefamilia"] = $row['nombre_familia'];
}
return $respuesta;
}
}
}
function devolver_cadena($valores){
/*
echo "<pre>";
print_r ($valores);
echo "</pre>";
*/
$cadena = "";
foreach($valores as $vitem){
$familia = "";
foreach($vitem["imarca"] as $mitem){
$familia = $familia . $mitem . " ";
$integrantes = "";
foreach($vitem["imodelo"][strtoupper($mitem)] as $moitem){
$integrantes = $integrantes . $moitem . ", ";
}
$integrantes = substr ($integrantes, 0, -2);
$familia = $familia . $integrantes . " | ";
}
$familia = substr ($familia, 0, -3);
$cadena = $cadena . $familia;
}
//$cadena = substr ($cadena, 0, -3);
//echo "<br>La cadena es: ". $cadena;
return $cadena;
}
function consulta_tipo(){
$con = new DBmanejador;
if($con->conectar() == true){
$consulta = '
SELECT tp.producto_id, tp.nombre
FROM `tproductos` tp
ORDER BY tp.nombre';
//echo "<br>consulta es.....".$consulta;
$resultado = mysql_query($consulta) or die ('La consulta -consulta tipo- falló: ' . mysql_error());
if (!$resultado)
return false;
else {
$contador = 0;
while($row = mysql_fetch_array($resultado)){
$respuesta[$contador]["tpproducto_id"] = $row['producto_id'];
$respuesta[$contador]["tpnombre"] = $row['nombre'];
$contador ++;
}
return $respuesta;
}
}
}
//insertar a una nueva familia
function ingresar_tipo($producto_id, $nombre_estilo, $marca, $modelo){
$con = new DBmanejador;
if($con->conectar() == true){
$consulta_estilo = '
SELECT estilo_id
FROM `estilo`
WHERE nombre_estilo = "'.$nombre_estilo.'"';
//echo "<br>sql tipo: ". $consulta_estilo;
$resultado_estilo = mysql_query($consulta_estilo) or die('La consulta -select estilo id- falló: ' . mysql_error());
if ($row = mysql_fetch_array($resultado_estilo)){
$estilo_id = $row[0];
}
$insertar_familia = '
INSERT
INTO familia (producto_id, estilo_id)
VALUES ('.$producto_id.','.$estilo_id.')';
$resultado = mysql_query($insertar_familia) or die('La consulta -insert into familia- falló: ' . mysql_error());
//echo "<br>sql familia: ". $insertar_familia;
$integrante_id = $this->adicionar_integrante($marca, $modelo);
//echo "<br>integrante id:".$integrante_id;
$consulta_codigo_familia ='
SELECT MAX(familia_id)
FROM familia';
$resultado_codigo_familia = mysql_query($consulta_codigo_familia) or die('La consulta -select max familia- falló: ' . mysql_error());
if ($row = mysql_fetch_array($resultado_codigo_familia)){
$familia_id = $row[0];
}
$insertar_familia_integrante = "
INSERT
INTO familia_integrante (familia_id, integrante_id)
VALUES (".$familia_id.",".$integrante_id.")";
$resultado = mysql_query($insertar_familia_integrante) or die('La consulta -insert into integrante- falló: ' . mysql_error());
//echo "<br>familia integrante: ".$insertar_familia_integrante;
return $familia_id;
}
}
//adicionar a una familia existente
function adicionar_integrante($marca, $modelo){
$con = new DBmanejador;
if($con->conectar() == true){
//
$consultar_codigo = '
SELECT integrante_id
FROM integrante
WHERE marca = "'.$marca.'" and
modelo = "'.$modelo.'"';
$resultado_consultar_codigo = mysql_query($consultar_codigo) or die('La consulta -select adicionar integrante- falló: ' . mysql_error());
if ($row = mysql_fetch_array($resultado_consultar_codigo)){
$codigo_integrante = $row[0];
} else {
$ingresar_integrante = '
INSERT
INTO integrante (marca, modelo)
VALUES ("'.$marca.'","'.$modelo.'")';
mysql_query($ingresar_integrante) or die('La consulta -insert adicionar integrante - falló: ' . mysql_error());
$codigo_integrante = mysql_insert_id();
}
return $codigo_integrante;
//
}
}
//adicionar a una familia existente
function adicionar_a_tipo($familia_id, $integrante_id){
$con = new DBmanejador;
if($con->conectar() == true){
$ingresar_familia_integrante = '
INSERT
INTO familia_integrante (familia_id, integrante_id)
VALUES ('.$familia_id.','.$integrante_id.')';
$resultado_familia_integrante = mysql_query($ingresar_familia_integrante) or die('La consulta -adicionar a tipo- falló: ' . mysql_error());
}
}
//buscar si existe un integrante
function buscar_integrante($marca, $modelo){
$con = new DBmanejador;
if($con->conectar() == true){
$consulta_integrante = '
SELECT integrante_id
FROM `integrante`
WHERE marca = "'.$marca.'" and
modelo = "'.$modelo.'"';
$resultado_consulta_integrante = mysql_query($consulta_integrante) or die('La consulta -buscar integrante- falló: ' . mysql_error());
if ($row = mysql_fetch_array($resultado_consulta_integrante)){
return $row['integrante_id'];
} else {
return false;
}
}
}
function actualizar_familia($familia_id, $nombre_familia){
$con = new DBmanejador;
if($con->conectar() == true){
$actualiza_nombre_familia = '
UPDATE familia
SET nombre_familia = "'.$nombre_familia.'"
WHERE familia_id = '.$familia_id;
$resultado_nombre_familia = mysql_query($actualiza_nombre_familia) or die('La consulta -actualizar familia- falló: ' . mysql_error());
}
}
function busqueda_estilos2($cadena,$tipo){
$con = new DBmanejador;
if($con->conectar() == true){
$consulta = "
SELECT e.nombre_estilo
FROM `tipo_producto` tp, `estilo` e
WHERE tp.producto_id = e.producto_id AND
tp.producto_id = ".$tipo." AND
e.nombre_estilo like '%".$cadena."%'
ORDER BY e.nombre_estilo
LIMIT 0, 20";
$resultado = mysql_query($consulta) or die('La consulta -busqueda estilos 2- falló: ' . mysql_error());
if (!$resultado)
return false;
else{
$contador = 0;
while($row = mysql_fetch_array($resultado)){
$respuesta[$contador] = $row['nombre_estilo'];
$contador = $contador + 1;
}
return $respuesta;
}
}
}
/************************************************************************************/
function listar_indicadores_tipo(){
$con = new DBmanejador;
if($con->conectar() == true){
$consulta = "
SELECT it.indicadores_tipo_id, it.clase, it.nombre
FROM `indicadores_tipo` it
ORDER BY it.clase";
$resultado = mysql_query($consulta) or die('La consulta -listar_indicadores_tipo- falló: ' . mysql_error());
if (!$resultado)
return false;
else{
$contador = 0;
while($row = mysql_fetch_array($resultado)){
$respuesta[$contador]['indicadores_tipo_id'] = $row['indicadores_tipo_id'];
$respuesta[$contador]['clase'] = $row['clase'];
$respuesta[$contador]['nombre'] = $row['nombre'];
$contador = $contador + 1;
}
return $respuesta;
}
}
}
/*********** el siguiente autoincrementable ******/
function sacar_auto_incremento($tabla_name) {
$con = new DBmanejador;
if($con->conectar() == true){
$consulta = "SHOW TABLE STATUS LIKE '".$tabla_name."'";
$resultado = mysql_query($consulta) or die('La consulta -auto incremento- falló: ' . mysql_error());
if (!$resultado)
return false;
else {
if ($row = mysql_fetch_assoc($resultado)){
$auto_incremento = $row['Auto_increment'];
}
}
return $auto_incremento;
}
}
/************** insertar nuevo tipo ****************/
function insertar_nuevo_tipo($clase, $nombre) {
$con = new DBmanejador;
if($con->conectar() == true){
$consulta = "
INSERT INTO indicadores_tipo(clase, nombre)
VALUES ('".$clase."', '".$nombre."')
";
//echo "<br>sql: ". $consulta;
$resultado = mysql_query($consulta) or die('La consulta -insertar_nuevo_tipo- falló: ' . mysql_error());
}
}
}
?>
|
Java
|
UTF-8
| 4,473 | 2.46875 | 2 |
[] |
no_license
|
//package ressourceUseless;
//
//import java.io.IOException;
//import java.net.InetAddress;
//import com.badlogic.gdx.ApplicationListener;
//import com.badlogic.gdx.Gdx;
//import com.badlogic.gdx.graphics.GL10;
//import com.esotericsoftware.kryonet.Client;
//import com.esotericsoftware.kryonet.Connection;
//import com.esotericsoftware.kryonet.Listener;
//import com.esotericsoftware.kryonet.Server;
//
//
//public class HostDiscovers implements ApplicationListener
//{
// static public int tcpPort = 54555, udpPort = 54777;
// @Override
// public void create()
// {
// Gdx.app.log("UDPTEST", "STARTED");
//
//// DiscoverServerTest();
// DiscoverServerTestUDPTCP();
// }
//
// public void DiscoverServerTest()
// {
// final Server broadcastServer = new Server();
// broadcastServer.start();
// try
// {
// broadcastServer.bind(0, udpPort);
// }
// catch (IOException e)
// {
// e.printStackTrace();
// }
// broadcastServer.addListener(new Listener()
// {
// public void connected(Connection connection)
// {
// Gdx.app.log("UDPTEST", "UDPSERVER: Client connected");
// }
// public void disconnected(Connection connection)
// {
// Gdx.app.log("UDPTEST", "UDPSERVER: Client disconnected");
// }
// });
//
// final Server server = new Server();
// server.start();
// try
// {
// //just for tcp server
// server.bind(tcpPort);
// }
// catch (IOException e)
// {
// e.printStackTrace();
// }
// server.addListener(new Listener()
// {
// public void connected(Connection connection)
// {
// Gdx.app.log("UDPTEST", "TCPSERVER: Client connected");
// }
// public void disconnected(Connection connection)
// {
// Gdx.app.log("UDPTEST", "TCPSERVER: Client disconnected");
// }
// });
//
// Client client = new Client();
// InetAddress host = client.discoverHost(udpPort, 2000);
// if (host == null)
// {
// Gdx.app.log("UDPTEST", "No servers found.");
// return;
// }
// else
// Gdx.app.log("UDPTEST", "Client: discovered host "+host.getHostAddress());
//
//
// client.addListener(new Listener()
// {
// public void connected(Connection connection)
// {
// Gdx.app.log("UDPTEST", "Client: Client connected");
// }
// public void received(Connection connection, Object object)
// {
// Gdx.app.log("UDPTEST", "Client: Client received");
// }
// public void disconnected(Connection connection)
// {
// Gdx.app.log("UDPTEST", "Client: Client disconnected");
// }
//
//
// });
//
// client.start();
// try
// {
// client.connect(2000, host, tcpPort);
// }
// catch (IOException e)
// {
// e.printStackTrace();
// }
// }
//
//
// public void DiscoverServerTestUDPTCP()
// {
// final Server server = new Server();
// server.start();
// try
// {
// //just for tcp server
// server.bind(54555,udpPort);
// }
// catch (IOException e)
// {
// e.printStackTrace();
// }
// server.addListener(new Listener()
// {
// public void connected(Connection connection)
// {
// Gdx.app.log("UDPTEST", "SERVER: Client connected");
// }
// public void disconnected(Connection connection)
// {
// Gdx.app.log("UDPTEST", "SERVER: Client disconnected");
// }
// });
//
// Client client = new Client();
// InetAddress host = client.discoverHost(udpPort, 2000);
// if (host == null)
// {
// Gdx.app.log("UDPTEST", "No servers found.");
// return;
// }
// else
// Gdx.app.log("UDPTEST", "Client: discovered host "+host.getHostAddress());
//
//
// client.addListener(new Listener()
// {
// public void connected(Connection connection)
// {
// Gdx.app.log("UDPTEST", "Client: Client connected");
// }
// public void received(Connection connection, Object object)
// {
// Gdx.app.log("UDPTEST", "Client: Client received");
// }
// public void disconnected(Connection connection)
// {
// Gdx.app.log("UDPTEST", "Client: Client disconnected");
// }
//
//
// });
//
// client.start();
// try
// {
// client.connect(2000, host, tcpPort, udpPort);
// }
// catch (IOException e)
// {
// e.printStackTrace();
// }
// }
//
// @Override
// public void dispose()
// {
//
// }
//
// @Override
// public void render()
// {
// Gdx.gl.glClearColor(1, 1, 1, 1);
// Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
//
// }
//
// @Override
// public void resize(int width, int height)
// {
// }
//
// @Override
// public void pause()
// {
// }
//
// @Override
// public void resume()
// {
// }
//}
|
C#
|
UTF-8
| 827 | 2.578125 | 3 |
[] |
no_license
|
using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
namespace PresentationLayer.Models
{
public class AddStoreDiscountModel
{
[DisplayName("Minimum Purchase Price For Discount")]
[Required(ErrorMessage = "Please minimum price to recieve discount", AllowEmptyStrings = false)]
public double MinPrice { get; set; }
[DisplayName("Percentage")]
[Required(ErrorMessage = "Please Provide discount percentage", AllowEmptyStrings = false)]
public float Percentage { get; set; }
[DisplayName("Discount Expiration Date"), DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
[Required(ErrorMessage = "Please Provide discount expiration date", AllowEmptyStrings = false)]
public DateTime ExpDate { get; set; }
}
}
|
Python
|
UTF-8
| 982 | 2.71875 | 3 |
[] |
no_license
|
import unittest
import sys
sys.path.append('../../src')
from filter.ArrayExtr.base.ArrayExtr import ArrayExtr, GetArrayExtr
from filter.ArrayExtr.ArrayOddExtr import ArrayOddExtr
from filter.ArrayExtr.ArrayConstantExtr import ArrayConstantExtr
class TestGetArrayExtr(unittest.TestCase):
"""
Тесты получения нужного класса для экстраполяции
"""
def test_ArrayOddExtr(self):
obj = GetArrayExtr([1,2,3,4,5], 'odd')
self.assertIsInstance(obj, ArrayOddExtr)
def test_ArrayConstantExtr(self):
obj = GetArrayExtr([1,2,3,4,5], 'constant', constant = 1)
self.assertIsInstance(obj, ArrayConstantExtr)
def test_unsupported_type(self):
with self.assertRaises(ValueError) as cm:
obj = GetArrayExtr([1,2,3,4,5], 'unsupported type')
the_exception = cm.exception
self.assertIsInstance(the_exception, ValueError)
if __name__ == '__main__':
unittest.main()
|
Swift
|
UTF-8
| 676 | 2.546875 | 3 |
[
"MIT"
] |
permissive
|
//
// UserModel.swift
// ValorantTracker
//
// Created by Aritro Paul on 05/01/21.
//
import Foundation
struct User: Codable {
let country, sub, playerLocale: String
let acct: Account
enum CodingKeys: String, CodingKey {
case country, sub
case playerLocale = "player_locale"
case acct
}
}
// MARK: - Acct
struct Account: Codable {
let type: Int
let state: String
let adm: Bool
let gameName, tagLine: String
let createdAt: Int
enum CodingKeys: String, CodingKey {
case type, state, adm
case gameName = "game_name"
case tagLine = "tag_line"
case createdAt = "created_at"
}
}
|
C++
|
UTF-8
| 284 | 2.703125 | 3 |
[
"MIT"
] |
permissive
|
#include "SpawnPoint.h"
SpawnPoint::SpawnPoint(Vector position,Vector direction) :
position(position),direction(direction) {}
Vector SpawnPoint::getPosition() {
return this->position;
}
Vector SpawnPoint::getDirection() {
return this->direction;
}
SpawnPoint::~SpawnPoint() {}
|
Python
|
UTF-8
| 536 | 3.65625 | 4 |
[] |
no_license
|
from cs50 import get_string
text = get_string("Text: ")
letters = 0
words = 1
sentences = 0
for c in text:
if c.isalpha():
letters += 1
elif c == " ":
words += 1
elif c in [".", "!", "?"]:
sentences += 1
indexL = (letters / words) * 100
indexS = (sentences / words) * 100
index = round(0.0588 * indexL - 0.296 * indexS - 15.8)
print(letters)
print(words)
print(sentences)
if index >= 16:
print("Grade 16+")
elif index < 1:
print("Before Grade 1")
else:
print(f"Grade {index}")
|
Java
|
UTF-8
| 714 | 2.6875 | 3 |
[] |
no_license
|
package operations;
import util.MatrixUtil;
import java.util.Arrays;
import java.util.Collections;
public final class ShiftOperation implements ShuffleOperation {
private Character[][] ma3x;
private final int k;
public ShiftOperation(int k) {
this.k = k;
}
@Override
public void execute() {
final Object[] flatten = MatrixUtil.flatten(ma3x);
Collections.rotate(Arrays.asList(flatten), -k);
ma3x = (Character[][]) MatrixUtil.makeMatrix(flatten, 4, 10);
}
@Override
public Character[][] getMa3x() {
return ma3x;
}
@Override
public void setMa3x(Character[][] ma3x) {
this.ma3x = ma3x;
}
}
|
C++
|
SHIFT_JIS
| 696 | 3.125 | 3 |
[] |
no_license
|
#pragma once
#include "../etc/Vector2.h"
class Game;
class Mouse
{
public:
// fXgN^
~Mouse();
// CX^Xϐ̎擾
static Mouse& Get(void) {
static Mouse instance;
return instance;
}
//
void UpData(void);
// NbN
bool Click(void) {
return (state != 0);
}
// gK[NbN
bool TrigerClick(void) {
return (state != 0 && old_state == 0);
}
// W̎擾
Vec2 GetPos(void) const {
return pos;
}
private:
// RXgN^
Mouse();
Mouse(const Mouse&) {
}
void operator=(const Mouse&) {
}
// W
Vec2 pos;
// ݂̏
int state;
// ߋ̏
int old_state;
};
|
JavaScript
|
UTF-8
| 260 | 3.546875 | 4 |
[] |
no_license
|
// Пиши код ниже этой строки
function addOverNum(number, ...args) {
let total = 0;
for (const arg of args) {
if (arg > number) {
total += arg;
}
}
return total;
}
console.log(addOverNum(10, 12, 4, 11, 48, 10, 8));
|
Python
|
UTF-8
| 2,553 | 2.578125 | 3 |
[] |
no_license
|
from django.db import models
from django.urls import reverse
class Answer(models.Model):
"""Через админку добавляем ответ на вопрос, который отобразится для каждого вопроса."""
title = models.CharField("Ответ", max_length=100)
def __str__(self):
return self.title
class Meta:
verbose_name = "Ответ"
verbose_name_plural = "Ответы"
class Survey(models.Model):
"""Через админку добавляем опрос. Далее читать описание в модели Question"""
title = models.CharField("Опрос", max_length=200)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('take_survey', kwargs={'survey_id': self.id})
class Meta:
verbose_name = "Опрос"
verbose_name_plural = "Опросы"
class Respondent(models.Model):
"""Модель для индентификации респондента."""
ip = models.CharField("IP адрес", max_length=20)
survey = models.ForeignKey(Survey, on_delete=models.CASCADE, verbose_name="Опрос")
def __str__(self):
return self.ip
class Meta:
verbose_name = "Респондент"
verbose_name_plural = "Респонденты"
class Question(models.Model):
"""
Модель для отображения вопросов в опросе. Через админку добавляем вопрос и выбираем опрос,
в котором будет отображаться этот вопрос. Готово, теперь пользователи могут участвовать в опросе.
"""
title = models.CharField("Вопрос", max_length=200)
survey = models.ForeignKey(Survey, on_delete=models.CASCADE)
def __str__(self):
return self.title
class Meta:
verbose_name = "Вопрос"
verbose_name_plural = "Вопросы"
class QuestionAnswer(models.Model):
"""Модель для записи ответов респондента на вопросы."""
question = models.CharField("Вопрос", max_length=200)
answer = models.ForeignKey(Answer, on_delete=models.DO_NOTHING, verbose_name="Ответ")
def __str__(self):
return f'{self.question} - {self.answer}'
class Meta:
verbose_name = "Вопросы и ответы"
verbose_name_plural = "Вопросы и ответы"
|
Python
|
UTF-8
| 1,441 | 3.875 | 4 |
[] |
no_license
|
import time
class timer:
def __init__(self, minutes=int(0), seconds=float(0)):
self.seconds = float(seconds)
self.minutes = int(minutes)
self.hours = int(0)
def __timeUP(self):
if (self.hours == 0 and self.minutes == 0 and round(self.seconds, 2) == 0.00):
return True
else:
return False
# decrement cannot take any arguments. Because it is not available for user.
def __decrement(self):
if self.__timeUP():
raise StopIteration('Seconds < 0')
if self.seconds < 0.00:
self.seconds = 60
self.minutes -= 1
time.sleep(0.01)
self.seconds -= 0.01
def Start(self, console=False): # Capital 'S' means user function.
if self.__timeUP():
print("Timer not set")
return
while (not self.__timeUP()):
print("Working: ", self, end="\r")
self.__decrement()
print(self, "Time's up \a")
def __str__(self):
return "{:02d}:{:02d}:{:05.2f}".format(self.hours, self.minutes, self.seconds)
if __name__ == "__main__":
timerObject = timer(0, 10)
print("Timer: ", timerObject)
start = input("Start (y/n): ")
if start.lower() == 'y':
try:
timerObject.Start()
except KeyboardInterrupt:
print("But why at", timerObject, "?")
else:
print("Good luck!")
|
C
|
UTF-8
| 983 | 3.15625 | 3 |
[
"MIT"
] |
permissive
|
#include <stdio.h>
#define true 1
#define false 0
int popstar(int N[][1000], int j, int n)
{
for (int i = 0; i < n; i++)
{
if (N[i][j] != 1) return false;
}
return true;
}
int main()
{
int N[1000][1000], n, maybe[1000], busca, busca_p, k = 0;
scanf("%i", &n);
for (int i = 0; i < n; i++)
{
busca = true;
for (int j = 0; j < n; j++)
{
scanf("%i", &N[i][j]);
if ((j != i) && (N[i][j] != 0)) busca = false;
else if ((j == i) && (N[i][j] != 1)) busca = false;
//printf("%i\n", busca);
}
if (busca == true)
{
maybe[k] = i;
k++;
}
}
if (k == 0)
{
printf("Nao ha popstar.\n");
return 0;
}
for (int i = 0; i < k; i++)
{
busca_p = popstar(N, maybe[i], n);
if (busca_p == true) printf("Popstar: aluno #%i\n", maybe[i] + 1);
}
return 0;
}
|
Python
|
UTF-8
| 2,398 | 4.1875 | 4 |
[
"MIT"
] |
permissive
|
# Yet Another KMP Problem
#######################################################################################################################
#
# This challenge uses the famous KMP algorithm. It isn't really important to understand how KMP works, but you
# should understand what it calculates.
# A KMP algorithm takes a string S, of length N as input. Let's assume that the characters in S are indexed
# from 1 to N; for every prefix of S, the algorithm calculates the length of its longest valid border in linear
# complexity. In other words, for every i (where 1 <= i <= N ) it calculates the largest l (where 0 <= l <= i - 1)
# such that for every p (where 1 <= p <= l) there is S[p] = S[i-l + p].
# Here is an implementation example of KMP:
#
# kmp[1] = 0;
# for (i = 2; i <= N; i = i + 1){
# l = kmp[i - 1];
# while (l > 0 && S[i] != S[l + 1]){
# l = kmp[l];
# }
# if (S[i] == S[l + 1]){
# kmp[i] = l + 1;
# }
# else{
# kmp[i] = 0;
# }
# }
#
# Given a sequence x1,x2,....,x26, construct a string S, that meets the following conditions:
# The frequency of letter 'a' in S is exactly x1 , the frequency of letter 'b' in S is exactly x2, and so on.
# Let's assume characters of S are numbered from 1 to N, where n E(Summation)i=1 = N. We apply the KMP algorithm
# to S and get a table, kmp, of size N. You must ensure that the sum of kmp[i] for all i is minimal.
#
# If there are multiple strings which fulfill the above conditions, print the lexicographically smallest one.
#
# Input Format
# A single line containing 26 space-separated integers describing sequence x.
#
# Constraints
# The sum of all xi will be a positive integer <= 10^6.
#
# Output Format
# Print a single string denoting S.
#
# Sample Input
# 2 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
#
# Sample Output
# aabb
#
# Explanation
# The output string must have two 'a' and two 'b'. There are several such strings but we must ensure that sum of
# kmp[i] for all 1 <= i <= 4 is minimal. See the figure below:
# [kmp(1).png]
# The minimum sum is 1. Among all the strings that satisfy both the condition,
# "aabb" is the lexicographically smallest.
#
#######################################################################################################################
|
Markdown
|
UTF-8
| 45,840 | 2.71875 | 3 |
[] |
no_license
|
---
layout: default
title: "2345.周恩来李先念接见财贸系统代表的讲话"
weight: 2345
---
李先念1967-3-21
周恩来李先念接见财贸系统代表的讲话
周恩来 李先念
1967.03.21
〖地点:国务院小礼堂。国务院财贸系统革命造反派代表和财贸各部党组成员出席。〗
周总理讲话
同志们,很对不住大家,昨天晚上大家呆了半夜,昨晚搞了两个座谈会,搞了一个是黑龙江的,一个是安徽的,继续下去就不行了。财贸系统座谈会是最多的了,你们自己能解决的问题,还要找我,现在怎么谈法?你先谈还是我先谈。看来财金学院“八·八队”的大字报,提了一些问题,我来解答,你们同意不同意?当然有些不是属于我答复的,财金学院八·八队,有一个批判分队的“从来急”纵队,“匕首纵队”“追穷寇”分队,转抄了一些东西,是三月十七日的东西,时间比较晚了一点问你们的意见,是我问你们问题呢?还是你们提问题我解答(群众说:请总理讲)好!我讲,你们事情比我知道得多,有些问题,你们比我知道得多,我找谁去问问题呢?这二十五个问题,如果可以答复,要我讲,我讲也好,对形势有好处,这样也可以节省时间,街上有大字报,小报。
一、毛主席为什么在接见张春桥同志时说,今年三、四月是决战时期,我们如何理解其深刻的含义?
主席讲话登报了吗?没看见有,大概是传出来的。有这么回事,无产阶级文化大革命已经搞了十个月吗,去年这个时期,毛主席亲自批转聂元梓的马列主义的大字报,全国轰轰烈烈的群众大运动,去年到年底已经七个多月,你们都熟悉嘛,运动本身就是思想革命,思想革命的目的,十六条规定夺党内走资本主义道路当权派的权,前七个月是思想准备,思想动员,树立以毛主席为代表的无产阶级革命路线揭露了以刘邓为代表资产阶级反动路线,这样对立面搞得更清楚了,经过十一中全会,十六条,红卫兵运动,大串连,从学校走向社会,从北京到全国,从城市到乡村,十月一日,林彪同志讲了进行两条路线的斗争,斗争中左派的旗子举得更高,保守势力缩小了,革命派从政治优势,发展到组织优势。不但做了思想准备,而且做了组织准备,这是第一阶段。再前进,进到批判资产阶级反动路线时期,把党内一小撮走资本主义道路的当权派更突出,夺党内走资本主义当权派的权,这是上海工人阶级起了领导作用。所以毛主席抓住上海的《文汇报》《解放日报》发表的十一个团体声明和三十二个团体的紧急通告,和反对经济主义,反对资产阶级反动路线新反扑,以工人阶级领先,一月革命风暴,从上海发起,这是第二阶段。夺权斗争开始了。资产阶级反动路线用经济主义进行反扑,不仅经济主义方面,还有其他方面进行反扑,进一步夺权斗争,夺权是必然的,这是反动阶级向我们挑衅,全面的阶级斗争嘛,党号召我们,毛主席号召我们夺权,夺党内一小撮走资本主义道路当权派的权。上海一月革命风暴所引起的这个夺权斗争,并不是说一些地区,一些企业单位,机关,团体都要夺权,这样就不是一分为二,这就没有阶级分析了。夺权是夺应该夺权的地区,企业单位,机关,团体的权。但是这必然会有连锁反应,农管不该夺也连锁反应了,这些一月份给你们座谈了,二月份也讲了连锁反应,所以势必带来连锁反应,必须要有精神准备,当时设想夺权斗争在二、三、四月份可能看出一些眉目,这是毛主席说的。现在看来,可能时间还要拖长了,到二、三、四、五月份。所谓决战,从某种意义上说,跟党内一小撮走资本主义道路的当权派斗争,跟资产阶级反动路线斗争就是决战,不是一切都解决了,所以主席讲,明年二月三月四月看出结果,夺权首先是地方,全国有二十八个省市,现在又增加了一个直辖市天津,变成了二十九省市,还有专区、县、公社、一般地说,顾不过来,有些地区搞了,最近中共中央发了通知,大队,生产队春耕大忙,不进行夺权,二三四月不能普遍铺开夺权。中央机关里权权斗争已经进行两个月了,现在眉目还未看清楚、企、事业单位更慢了一些,为什么这样?因为是史无前例的运动,最高统帅提倡的由下而上的发动的,在无产阶级专政条件下,在中国共产党的领导下,在中国人民解放军的保卫下,夺权没有历史经验可学,自己摸索,对形势只能作一般的估计,北京革命群众的报纸,我不确切信,我只讲我自己的看法。主席讲主要二、三、四月份看出眉目(记录不清楚)现在只是估计,时间晚一点,早一点,不起决定性的作用。比如,解放战争时期国民党在一九四六年七月搞内战,但内战以前已经有了,四五年日本投降,四六年就进攻,大规模是四六年七月到四九年六月,三年半不到的时间就解放了全中国,四七年主席在陕北时估计的时间还要长一些,时间来得快一些,主要看主席的方向,方针,预言对了。中心是今年看清眉目,明年看出结果来,这是带偶然性的,工作得好,快一点,做得不好,就慢一点。同志们很着急,何必着急,急不行!现在同志们提出问题,觉得三、四月是决战,现在在房子里坐不住了,写给我信,今天是三月二十一日,等不急了,还有四、五月嘛,何必急呢?不是两个月过去就没有日子了。“三结合”,应该夺权的地方都得“三结合”,我从一月份,就讲“三结合”,首先在财贸口讲,在外事口讲,直到现在还没树立起一个典型,不能责怪谁,不是这里出毛病就是那里出毛病,没有经验,我们两个月也在摸索,不断总结,不是这两个月过去了,决战的日子就没有了。全国二十九个省市,我现在给你们讲一讲,现在已经实行“三结合”有临时权力机构的,有上海、贵州、山西、黑龙江、山东五个单位,五个单位建立了临时权力机构革命委员会,就这样,拿黑龙江讲,革命委员会,昨天晚上(二十号)谈之前还没有正式成立,一个夺权组长不是领导干部,一个组长是哈尔滨师大的学生,两个副组长,一个是工人,一个是哈尔滨工大的学生,而不是革命的领导干部,一个十、七、八人的领导小组,虽然省委第一书记潘复生已经站出来了,军区负责人支持革命造反派负责夺权,原来夺权只请他们作顾问,我解释了,才参加“三结合”做委员,直到这时才通,因为革命的学生说,如果让他们做组长,我们就变成阿斗怕做阿斗,就不要诸葛亮了。当然不是所有的领导干部都是诸葛亮,问题在你需要不需要,不在形式,关于“三结合”《红旗》杂志第三、第四、第五期社论都讲过这个问题,革命的领导干部可以成为“三结合”的核心,骨干力量,革命群众为基础,解放军代表为柱石,这样一讲就讲通了,经验和教训大家认识到,五个单位夺权,黑龙江比较早,还是这样反复缺乏经验,问题是方向对不对?是前进,不是后退。目前夺权有十个省市,北京也是准备夺权的单位之一。召开大专院校红代会,就准备夺权,在主席那里汇报,主席说为什么光开大专院校红代会,不开工人代表会,贫下中农代表会,中学生红代会,革命干部代表会呢?过去中学生批评我们只注意大专院校的工作,不注意中学生的工作,三个代表会最近准备召开,开农代会、工代会、中学生红代会,既然开了都是革命造反派大会,三个代表会先分别开,然后再合起来开全体会,成立革命委员会,再开个群众大会祝贺。上海来得快,工人提倡议,后来边开会,上海各农村,不叫上海公社,怕全国都照抄。国家名称也得改变,改成中华人民公社。这没有必要,后来改成革命委员会了,天津也筹备,也在开各种会议,筹备中十个单位另外还有两(记录不清楚)噢!这里我讲错了七个准备夺权的省市,十个条件不成熟,先准备军事管制不成熟,左派组织代表没产生,好多派争执不下。过去是对当权派斗争,主要是对当权派,批判资产阶级反动路线,矛头向上。去年十月、十一月、十二月相比之下,保守势力弱小,造反派力量强起来了,从政治优势发展到组织优势,到今年一、二月份夺权,革命组织内部发生的争论,不易形成左派大联合,这时革命的领导干部没有出来亮相,另一方面革命的领导干部还没同反动的资产阶级反动路线划清界限,批判资产阶级反动路线,彻底批判毫不留情地和党内走资本主义道路当权派划清界限,彻底地毫不留情地亮相,取得群众同意……。人民解放军支持左派……。“三结合”条件不成熟。在当地工作需要抓工业,作业,交通运输,卫生,财贸。春天来了,瘟疫多了,这样就发生需要过多的办法。需要军管,但这种军事管制,必须说明,跟初解放时的军事管制完全是两种性质。那时是共产党领导,打下了天下,把国民党赶出海,由上而下一一排除国民党高级军政人员抛开外,一般企业、事业单位、机关、团体、学校都包下来。新的机构实质是建立在无产阶级专政政权基础上,人事制度也包下来了。四九年不能说是彻底的夺权。因此,继续了十七年夺权斗争,十七年由下而上不断地进行夺权斗争,如农村清匪反帮,城市的三反五反,五七年的反右政治斗争,六二年党内批判,提倡阶级斗争,六三年春起,进行三年社会主义教育活动,四清运动,都是夺权斗争,一般的来说,都是自上而下领导发动的,只有六六年五至六月份,“四大”才是最高领导毛主席发动的,这是真正由下而上彻底地群众大革命运动,是史无前例的群众几万万人起来要把权从党内一小撮走资本主义道路当权派手中夺过来。去年的七个月,就作这样的准备,今年一月上海革命群众进行了夺权。夺权如果说是决战,这就是决战。这样的运动条件,不成熟不能急。抓革命促生产,这是主席的号召,去年生产是好的,农业工业都超额完成了计划,粮食、棉花、油料作物,经济作物都超额完成计划。今年就应该继续增产,……,工农业,第一季度过了,必须赶上,但是夺权斗争还没有抓起来,如果一个地区的工作瘫痪了,过渡的办法就是军管,但是不同四九年,五○年军管。这是自己专政条件下,在毛主席领导下,在解放军保卫的基础上,只夺一小撮党内走资本主义道路的当权派的权。其他的还要一分为二,一九四九年是农村包围城市,城市群众运动本身没有形成,虽然也是敲锣打鼓,但那是群众的热情,而不是行动。这次运动是城市群众自己起来行动,这样夺权,条件不够先等一下,军管促使无产阶级革命派大联合,三结合,建立临时权力机构,地方省市、专区、县都可以这样。条件成熟的有七个省市,还有七个省市情况不明朗,五个省市已经夺权了,十个准备军管和已经军管了,这是全国的情形,不管怎么样,三、四月份准备,五月份再试验,差不多了,这是对全国地区来说的。机关来说财贸口,本身或下属企业单位,个别企业单位,刚才说了条件不成熟,二月份夺权,不管党委是不是党内走资本主义道路的当权派,现在我还不能下结论,财贸口停职已经有多少?(先念同志插话:十六个财贸口,八个单位,健康报不算,财政部,粮食部,商业部,外贸部,银行,供销合作总社,健康报,工商管理局),(群众:不是健康报,是前进报)啊!是前进报。这样八个单位,报社不算还有七个单位,十六个停职反省,数量不少,当然不只此,可能还有,上次希望大家排队,到现在还没有出来。
拿财贸口来说,我首先要求“三结合”第一点没有经验,二月份只能说两句话,算也夺权,现在无产阶级文化大革命的领导权,虽然造反派占优势,开大会,我们支持了,有人说,文化大革命的领导已在造反派手里,文革已不起作用,但保守派已屈服,夺权形势已经造成,经过三个月的斗争已经实现了,从政治上转到组织上的优势,应该算夺权,这早已肯定。第二,业务怎么办?一月中,我建议大家监督业务,中央各部直属中央,是中央的权,有许多机关是机密单位,如外交部,财政部,公安专政等更是中央的,外贸部一部分银行,金库大权,都不该夺,除去让大家监督业务。一月中试验可以,现在还可以监督,二月中出了毛病,外交出了毛病(记录不清)。
中央调查过,泄密很多,对外经委,对外援助项目,不该公开的公开了,再不限制要超过。财贸口表现在财政部,是不容忍的,上次有许多预算机密,预算分配,做什么事,实际上都极端机密的,监督的都看了。这些东西在党中央只能政治局常委同志才能看,政治局委员也不看,不要说中央委员。建国初期,对党外人士当时(记录不清)……党外人士张文升给泄密了,后来经国家最高会议开除出去,财政部××泄的密,不好在这里说了,国防尖端不要算了,……。可以在预算中看出来,我们没料到监督组都看了,原因是主管的长字号都靠边站,阻不住了,青年没重视,犯了这样的错误。外交也有,银行也有,(李先念同志插话:武汉银行)。极端机要的材料要弄走,弄走了我们要负责,为什么不抓呢?十七日不能再等了,如果不是杜向光他闯进来,他来抵抗,现在造反派的信,还在手里,让他们去反省检讨,还没有回答我。财政部杜向光和造反派走到那样极端,是我们不能容忍的,是党和国家不能容忍的,今天我还要讲,已经晚几天了,再晚了就要违背最高指示。许多同志不清楚后果,如不过问,过错太大了,不过问,我就辜负党和国家的委托,就要犯罪,我过问晚了几天因为忙开会了。因为这些事情超过了监督范围,为什么我对杜向光管得那样严呢?因为他是副部长,他知道嘛,财政预算要出去,他拒绝召开党组会议,就不能容忍,这就不能不引起我的警惕,那次取得造反派的支持,财政部当时超过了监督范围,今后对外贸口应规定个范围,整风中提出要求,自己整风提出办法来,夺权斗争的基础吗!你们要联合起来,事情发生后,财政部革命造反司令部垮台了,但战斗组还存在呢!事先我不知道,先念同志也知道晚了,后来方知道。司令部的问题,你们自己解决,可以搞联合机构,希望革命组织还是要联合起来,尽管战斗组在行政单位,上面还是要搞联合组织。两种联合,一个是司、局里有几个战斗组,大方向一致,矛头对准党内一小撮走资本主义道路的当权派,批判资产阶级反动路线,观点一致,局内就可以联合起来,还可以监督业务,形成部内联合,无产阶级革命派大联合。另一种形式,司里有小,上边有大的也可以设临时的监督机构,不妨多试点几次。哪种合适,战斗组不要交叉。便于业务工作,业务时间搞革命,忙大家都忙,不能因为观点不同在工作中吵架,行动系统可以联合,大部分可以联合,总是要把无产阶级革命派大联合搞起来。三月份已有十天,要把各部无产阶级革命派大联合实现,二、三月中整风差不多了,不能再迟了。这些首先请大家实现。至于外边是否来推动呢?这个时期已经过去了,去年是可以的。学校先进一步,财经学院,商业学院,粮食科学院。去年我们支持的财经学院起了主要作用,当然外贸学院、商学院也不落后。今年已到夺权阶段,夺权应本部为主,中共中央二月二十一日有通知,中央和地方一切需要夺权的机关、企业、事业单位都应以本机关单位的无产阶级革命派为主进入夺权斗争,外单位的无产阶级革命派在必要可以协助,不可包办代替。党中央各机关、国防工业各部,公安部、外交部、计委、经委、建委、科委、财政部,各地银行,人民日报、红旗杂志、解放军报、新华社、广播事业局和各地广播电台,不许由外单位人接管。已经进入各机关的外单位人员要立即退去,本单位的造反派已经起来了吗!毛主席在井冈山发起革命,任何运动都是波浪式的发展,不可能是一直高潮,一直高潮从来也没有。立三路线讲革命一直是高潮这是错误的,运动总有高有低,二、三月份整风低了些,现在又起来了嘛!各部大联合要搞成,财政也要搞成。是不是要外单位帮助,由本单位造反派自己决定。比如,财政部是否需要,自己决定。但不能进入联络站了,一般来说,自己学校联合起来。
二、各级领导干部排队,希大家提意见,要一分为二,各单位领导干部,有没有走资本主义道路的当权派,可能有,也可能没有,不能说每个单位企业都有,那是不符合方针的。我们讲夺权是需要夺权的地区、机关、企业、事业单位、团体、也有不需要夺的,包括机关即使需要夺权,也不是所有的权都夺。要夺,只夺党内一小撮走资本主义道路当权派的权。比如,财政部有三个停职嘛!银行两位嘛!粮食部两位嘛,财办两位嘛,当然,停职是否都是走资本主义道路当权派,也不通通都是,要一分为二,经过检讨以后,结论再定。没有走资本主义道路当权派的,也不是没有犯错误的人,错误有轻有重,有多、有少,如执行资产阶级反动路线时间,有长有短,情节有不同,有轻有重,改的有早有晚,责任上边比下边的重。首先,要区别有没有夺权的机关,是否有党内一小撮走资本主义道路的当权派;第二,有多少需要夺权的,一定有不需要夺权的。第三,不需要夺权的,也不是不犯错误的,错误有轻有重,有多有少,也有没有的,没沾上边的,第四,责任一般上边比下边重,所以,矛头向上不向下,几个区别是阶级分析吗,是站在资产阶级当权派一边,还是站在无产阶级当权派一边,站到资产阶级反动路线上,还是站到无产阶级革命路线一边,犯了路线性、方向性错误的同志是否站回来了,要阶级分析,对各级领导干部应分析,各部党组自己也排排队,看两个排队是否相符合吗,可能有相合的,也有不相合的,角度不同的,由下而上,由上而下,再拿到中央来提,我们可以比较,这是从群众中来,然后再到群众中去讨论。首先要求犯错误的干部一定要划清界限,深刻检查,为他们准备时间,严肃批判,已经过去一个月了,各部进行排队的不多,时间在争论中过去了,要看眉目忽视了,我这里再次呼吁你们,认真地做。除停职的外,能说话的部级领导干部,部级开会检讨就行。也可以要学校参加,如商业部可以要商学院参加,司局长一般司局范围里检查,也有个别的部级会上检查,不需要人人过关,人人过关是怀疑一切,打倒一切。怀疑一切,打倒一切是刘邓资产阶级反动路线,是刘邓主张的,他们派工作组把校党委、总支、支部都否定了。去年七、八月份我到清华去调查,从党委、总支、到辅导员都否定了,都靠边站了,是否都是黑帮?北大也如此,调查许多学校也都如此。否定一切精神在中央十一中全会后,国务院各口传达十六条特别是工交口更厉害部级首长都靠边站了。这种思想影响了红卫兵的思想。影响后起的革命造反派,所以到路线斗争都靠边站了,怀疑一切,否定一切,陶铸曾经说,除了毛主席、林副主席外,其他人都可以怀疑,这样,实际上是把毛主席,林副统帅、林彪同志孤立了,中央文革小组也可以怀疑就是从刘邓那里来的。当然,对我们伟大的领袖一切发展都合乎马列主义,有的超过马列主义,副帅林彪同志高举毛泽东思想伟大红旗。对其他同志看他做得对不对,即使有错误,也要善意批评。怀疑包括信任不信任,说错了,可以批评,善意的,同志式的贴大字报也可以,怀疑一切,打倒一切这种思想不是善意的。干部排队要一分为二,两条路线斗争,红旗杂志第四、第五期社论是反右和反对形“左”实右的。否定就是形“左”实右。什么都结合,恢复原状,就是资本主义复辟,是右。二月二十九号,三月初,同时间两条路线展开了,对群众要说服,不要否定一切,不要不一分为二,根据毛泽东思想,用阶级观点,看待干部。另外领导干部不能囫囵吞枣,一切都包过来,有区别嘛!实事求是,通通保不对。财贸口停职反省的十六个,绝大多数是群众提出来的,而且还有。大家可以揭,对干部要看全面历史,还要看发展,例如二月中有的同志犯了严重的错误,改得好,发展了,重新恢复信任,错误也许是偶然的。有的同志历史可……现在犯新错误,比过去更严重,难道还保吗?对每一个人,都要一分为二。对领导干部也要实事求是,过去对,不能今后都对,按主席思想,只要不是反党反社会主义,而又坚持不改和屡教不改的,就要允许他们改过。鼓励他们立功赎罪,将功补过,将功赎罪。干部排队很重要。每个方面都要排,革命群众组织,部党组,排后交换意见。看是大致上一致,一个部十几个左右。三级干部会开完后,问题解决了,工作就更安心,不是开完会就放心,还要看发展。处理可以监督留用,撤职留下,有的要调走。有的完全罢官。提一批。革命群众组织的代表为基础,中级干部的代表,部级的领导干部,组织革命委员会,监督业务,这样监督更容易一点,哪些工作是事务性的,可以不管,哪些是机要东西,可以不监督,避免造成大大小小的错误。有的单位是不能监督业务,如国防工业部,但可以监督政治。政治各组,中央各部门情况比较复杂,要搞典型。将来各部门,另一种设想是如军管。六个国防机构已经军管,前几天在这里宣布三结合,解放军代表,革命的领导代表,革命群众组织代表,不监督业务,政治生活可以监督。工交、财贸系统、农业口、外事一部分,是否实行军管?军事各部还是搞三结合,这两种态度都要摸一摸。你们能够负起责任,真正无产阶级革命派大联合形成,干部检讨很快,做好,可以搞三结合,何必还军管过渡呢?有些部门可以看看,财经各部门,今天我与先念同志商量,不能决定,相信你们能够做好。但时间过两个月了,你们应该做得快些,事情并不难。总之,希望中央各部。各机关把这些事情搞好,紧接着抓业务,促业务,现在已到第二季度了市场供应,外贸供应,财政税收,农作物收购,夏季要到,比第一季度任务大,财贸口不能拖得很久,今天林彪同志在一个地方说,抓革命促生产,从政治统帅业务来说,革命重于业务,从时间上来说,抓业务的时间应大于革命的时间,业务部门一天八小时,革命三小时。但是有时还要加班加点,当然业务重,还要政治挂帅,不能离开政治但时间要多。
(二)毛主席为什么在三月七日关于军训的指示中指出,说服学生实行马克思所说的,只有解放全人类,才能最后解放无产阶级自己的教导?这句话是有的。主席在军训通告上说的,大专院校军训,不仅是造反派训练,非造反派也要训练,这是对于学校的训练。对保的厉害的,也不能歧视他们,要帮助他们嘛,过去我们常说,比、学、赶、帮、超,学校也一样,串联很久了,回去共同过组织生活,学校里造反派在运动里领先了,在学校中也要一块参加军训,加强革命性,科学性,组织纪律性,使三性统一起来。一定要懂得,你们自己是左派,造反派有的还是少数,或者是较多数,要教导他们吗?正如马克思所说:“只有解放全人类,才能解放无产阶级自己。”社会上还有资产阶级,封建主义,小资产阶级,以及各种非无产阶级的思想,不仅要解放他们,还要改造他们。从全面来说,工人阶级还是少数,半无产阶级还是多数,还有资产阶级、封建主义,都要改造,只有改造了他们,资产阶级才能打倒,复辟资本主义的可能性就缩小了。在我们开展无产阶级文化大革命,全世界都这样,进入共产主义就保障得多啦!在这种意义上来讲,无产阶级只有解放全人类,才能最后解放无产阶级自己。
(三)这次为什么提自上而下的资本主义复辟逆流?而不提是资产阶级反动路线的新反扑?这看提什么内容,比如说,很多地方,反动路线搞经济主义,是资产阶级反动路线当权,当政的。上海市人委那时没被夺权,黑帮统治,黑龙江省当时潘复生同志的权还很小呢!他们就搞反抗,向我们挑衅,向无产阶级司令部挑衅,所以上海口号是反对经济主义,粉碎资产阶级反动路线新反扑。二月份,一方面提出对待干部排队,要一分为二吗!不要否定一切。红旗杂志第四期社论讲了,从另一方面一切都保,肯定一切,也不对。否定一切是形“左”实右,这是由上而下来的,这就是两条路线斗争。比如财政部例子可以说,掌了权,超过了监督范围,夺到中央来了。他要夺中央大权,这是资产阶级当权派作法,夺到无产阶级司令部头上来了。夺了无产阶级司令部的权,这些都是一股逆流。资本主义复辟逆流,有各种形式,各地都可以找到这种例子,各方面出现了复辟逆流,我们应该进行批判。原来矛头向一小撮党内走资本主义道路的当权派,矛头向上,批判资产阶级反动路线。革命造反派大联合,对保守派用政治斗争影响他们,教育群众很好。夺权以后,革命派内部,发生了一些问题,私心杂念起来了,有些权不该夺的夺了,有的和党内一小撮走资本主义道路的当权派联合在一起搞假夺权。也有的自己夺了权后,排斥另一派革命派,压制群众,打击革命群众。夺权斗争中出现了些:有的是资产阶级反动路线,有的是新发现的问题。这些都是资产阶级的东西,有一些部门,机关,都可以发现这种情况,在学校中,是另一种形式,过去否定一切什么都不好,当权派,小当权派,一律靠边站。现在,当权派,小当权派又都出来压制群众,这可以叫反扑,复辟,他们要出来,他还想当权,恢复旧的统治,我们无产阶级文化大革命就是打翻打烂一切便于滋长修正主义,资本主义复辟的旧秩序,建立新秩序,凡是复辟也好,反扑也好,就是要恢复旧的东西,恢复旧的思想,从广义上来说,就是复辟。为什么这次提是自上而下的资本主义复辟逆流呢?因为夺权斗争是由上而下的进行,所以提由上而下资本主义复辟。
(四)关于问到戚本禹的讲话,我没有问过他,我不能回答。这问题,我没摸,不能回答,我只看到大字报快报,有待调查。(中间有些问题,总理没有解答)
(五)至(七)……
(八)中央为什么要把学生调回学校整训?为什么“红代会”召开以后,中央又急于要召开工代会、农代会和中学生红代会,还要成立北京市革命委员会,这与当前自上而下的资本主义复辟和三、四月份的大决战有什么联系?学生军训中央把学生调回学校,中央有通知,何必问哪?上次有的学校,要求先念同志派军队支持军训,因为主席批了北大、清华试点,还有北航、矿院、地质学院,还有中学生。(群众:有两个中学:二中,延安中学。)试点经验主席已经批了,训练以后情况就不同了。训练一下,和不训练大不一样。不仅大专院校要训练,中学也要搞,小学高年级、工矿企业、机关也可以办。但是不能同时办,因为解放军目前任务很重,要搞军管,军训还要支援工农业生产,支援左派工作,相当忙,解放军是高举毛泽东思想伟大红旗的,是突出无产阶级政治的,宣传毛泽东思想,是三八作风,四个第一,是活学活用毛主席著作,在用字上狠下功夫的,可能在文化上不如你们大家,院校的知识分子,但是政治上受过训练,三性是很强的,要向他们学学。毛主席、林副主席期待这种精神。工矿企业单位还没开始,我们要把全国办成毛泽东思想的大学校,军训是一个好办法,但不是唯一的,还要有多种办法。希望大家不要轻视,军训并不妨碍整风和社会活动,就看时间,看你们怎么样安排。
(九)《红旗》第五期社论中为什么强调指出:现在摆在全国人民面前的一个大问题就是要把无产阶级文化大革命进行到底还是半途而废。一切革命的同志都必须保持清醒的头脑,切切不可糊涂起来。当然不能半途而废。我讲了,今年三、四月看出眉目,明年三、四、五月看初步结果,也可能会更长一些时间,连批改都搞,各地区、机关企业、事业单位一样,明年三、四、五月才有结果。是否今后就永保太平了,不能那么讲,那是违反毛泽东思想的。这次无产阶级文化大革命,是自下而上发动的轰轰烈烈的群众运动,进行夺党内一小撮走资本主义道路当权派的权。不能永久是革命派的选举,还要搞革命委员会。临时的权力机构要变正式的权力机构,将来还要回到人民代表大会,机关现在搞监督机构,将来仍难免产生停制,如搞到明年,运动轰轰烈烈的,但总要有间隙,过了一年后思想上又有灰尘,又可能出问题,那就还要搞,形成好的制度。大民主的传统,不仅我国,要世世代代传下去,使我们的党永远不变颜色,还要影响全世界。这样,对全世界进入共产主义社会就有保障得多了。想到前途,去掉灰尘的事,应敢于作了。
(十)为什么全国财贸系统的群众,迟迟发动不起来,运动阻力很大,这阻力从何而来?这个问题我不好回答,我回答不起来。我曾经提议过,让财经学院去作调查,在全国去建立联络站。财经学院八·八队派了许多同学到各地去了,到下月五号就到期了,我跟中央说了,要守信用。当然去到各地不是一样都欢迎,有的就不欢迎。有的同学到上海,跟中央文革副组长张春桥领导的上海市革命委员会闹对立,不知怎么搞的我们已经派人去调查,(先念同志插话:财经学院派去上海的不是这样)噢!可能误会。三司出去的也有一些地方犯了错误,回来整风,不能说所有的事情都作对了,我告诉那些地方不要过多地责怪他们,有时我们说话还有失言的地方嘛!革命靠自己,解放靠自己,要按照马克思主义的原则,正如国际歌所唱的一样,不要仅仅相信自己,派人去帮助是对的。说地方运动搞不起来,这种提法是不对的,不能那以说。运动发展不平衡嘛!各地有先有后。我们要相信那些地方一定会搞起来的。
(十一)制定财贸系统三个系统一起来,上下左右一起来的策略,转移斗争的大方向,把矛头指向群众的罪魁祸首是谁?有些历史上的问题,我不很清楚,有些让先念同志回答,先念同志还要作检查的。
(十二)这个问题总理没解答。
(十三)关于陈云批判问题。对中央常委陈云同志的批判,这次文化大革命他没有参加,过去的,我所知道的,财贸上没批判,只是吴波同志写了一个材料。(问吴波:写了吗?)(吴回答:写了)(先念插话,姚依林也写了),吴波只能写他所知道的,中央的他不知道。中央常委内部的问题,由中央决定,我不能回答,不能把中央常委内的事说出来,你们可以结合本单位领导进行批判。如财政部,商业部,银行,粮食部,供销总社等七个单位不能所有的领导都接触,中央常委没有决定拿出批判陈云材料,我不能回答。你们问阻力,我不好回答,陈云这个人思想是右的,这许多人可能知道,有的人去陈云家抄文件,不是财经学院的。(群众说:哲学科学部)当时我打电话都不灵,陈伯达同志就亲自出马,去保护中央文件,把文件拿到中南海了。毛主席没决定,当然要负责保护。随便抄家,打、砸、抢、揪、抓是不允许的。关于这个,中央最近有指示,我们在文件上批判了。
(十四)为什么粮食部等单位在中央军委指示下达几天,烧毁黑材料?中央批转军委指示,十二点指示,两个文件批转以后,不许烧文件,如果再烧,你们揭发出来,告诉我,一定要在后期处理。我总的回答你们,对各部,财贸系统等批判,你们有权力批判嘛!批判一些著作,中央不限制,批判后再定案。也可能批判文章就定性了,但有些不能强调别人接受,那些是一个人的意见,人家也可以驳斥,大民主嘛!大辩论,大鸣大放。
(十五)略……
(十六)(十七)(十八)没回答。引到许多别的同志的谈话,我没听到,我不回答。
(十九)略……
(二十)为什么财贸各部的头头们竟敢步调一致,明目张胆地进行反攻倒算(指二月十七日以后)?财贸各部上次讲完以后,头头们竟敢步调一致,明目张胆地进地反攻倒算,我听到的并不都是一样吧!这个由各部造反派去作结论,你们对干部要排队,哪些不好,各单位造反派具体问题具体分析解决,不要抽象地提问题。财贸系统联络站到底保留不保留,后来我提意见搞联络站是两个,一个财贸系统联络站,一个外事系统联络站,外事系统联络站已经撤销了(群众说,已经撤销了)。财贸系统联络站起了很大作用,历史任务是不是完成了,你们自己决定。外事系统的主动撤销了,财贸的,你们自己讨论一次。学生要回到学校斗批改,过问社会的事件要通过红代会,红代会也没有决定设联络站,他们出来也是暂时的。
你们提出了四点建议。(先念讲,一是撤销,二是不撤销,三是搞一些调查研究,四是办报。总理秘书说,他们要搞监督,监督无法监督了。总理秘书说,他们要变成工会,工会,总工会现在已经垮台了吗)!等一阵再说。至于联络站问题,我们进一步联系,不便回答。同学们可以回学校,是事实,中央决定的。各部是否留一些人,自己决定,如果一定要我回答,中央已有决定,按中央文件答复,没有什么存在的必要了。
商学院同学问:李先念财贸八条(指牛鬼蛇神界限)是你定的,还是姚依林定的? (先念:是政治部的姚依林定的)。问:你看过没有?精神知道吗?(先念:已经收回了。没有必要问了。)
问:商业部党组恢复活动后(二月十八日)发的通知你知道吗?
先念:这个东西是错误的,我没有看过,放在桌子上没看,这是党组的错误,我已批评过党组。
问:姚依林表态。
姚依林:先念同志没看过,这个事情他知道。
工商管理局问:请总理明确,许涤新到底算统战部的还是工商管理局的?
总理:许涤新不在统战部吗?
工商局:运动中统战部搞的很厉害,他跑到了工商局。
总理:那你们工商局不成了防空洞了吗?许涤新这个人我认识,这个人资产阶级思想很严重,我看你们可以批一批。
工商局:我们人太少了。
总理:你们不说没事干吗?可批一批。财经学院不是说冷冷清清吗?可以去帮一帮忙。许涤新是我一个老朋友,很可以批判,这个人是老教条,是修正主义教条,研究了三十年代的经济学,他的东西我有一大堆。他写一本给我一本,最近他们夫妻还给我写了一封信,我还没看呢?
工商局:他老婆包庇他(又问了一些关于许涤新历史上的问题)
总理:财经学院和前进报帮助他们批深。这个人是教条主义,但他比薛暮桥轻一点。薛暮桥的东西一看就使人发困,干巴巴的。许的文章我还喜欢看。你们写一本批判许涤新的书,我倒愿意看一看。
同学:先念保了许涤新,最近把业务权交给许涤新。
先念:没有,我让他们交给黄建南了。
同学:交给许涤新和黄建南,杨树根说那是传达先念的指示。
先念:我记不清了。
总理:一般地对干部批评,还是要抓文化革命的问题,问题比较简单。我再补充一个区别,第五个区别主要是文化大革命中的问题。如果是一小撮走资本主义道路的当权派问题严重就追一下一小撮的历史是可以。这次文化大革命红卫兵小将查出一批叛徒,这是小将们的功劳,这是很大的收获,我们向红卫兵小将学习。历史上犯了左倾、右倾的错误,这是一般的,也搞了一批叛徒,这是严重的,去年我在政治局会议说过,瞿秋白临死前写了我《多余的话》,这是李秀成一样的东西,是叛徒的自白书。最近又发现他枪毙前给反动当局写了一封求饶信。他是个叛徒,对这些人应重新做评价。我也是受戚本禹同志的启发。青年历史学家,戚本禹同志发现了李秀成的问题,年轻人启发了我们这些老头子。(笑声)刘少奇组织路线没按主席思想办事,是刘邓组织路线的错误。安子文在组织部搞了二十多年。陆定一是搞宣传的,他们在表面上搞得比我们还左,实际上是反毛泽东思想,不改是不行的。从此我们对叛徒问题就严格了。对干部问题,也许我讲的五个条件还不够,你们可以补充,叛徒要搞专案,反动学术权威要搞批判。有人说我矛头对下,我什么地方说的?
同学:总理说矛头对上。
总理:我记不清楚了。内外有别,我开始同意了,主要怕大字报上街被外国人看见。就这样他们报告送去,我押了几天,后来,外办催几次我才批,那是五、六月份,后来,很快就改了,现在我看有些还要内外有别,但不能妨碍群众运动。
商学院:商业部党组恢复活动以后,就到处追查政治责任,我们对姚依林很有意见。
总理:姚依林我倒是有点意见。你们有什么错误?就是那个通缉令不好,当面谈谈算了。
同学:我们要炮轰姚依林,到商业部去闹一闹。
总理:我同意炮轰。
同学:我们要炮轰炮打。
总理:(笑着说):炮轰炮打是一回事嘛!到商业部去闹一闹也好,但要一分为二,业务时间不能闹,不要影响业务,一星期留两三天闹一下可以,业务时间外搞文化大革命。
粮科院:资产阶级反动路线新反扑是什么性质?
总理:这是学院式的问题,这些问题斗争中自己会解决。
李尚平:(商业部造反派,司长)总理在二月十七日讲话对我们的批评完全正确,给我们指出了方向,但先念同志在会上说了一些气话。你是国家副总理,应该对革命负责,不该对革命说气话,你讲了气话,我们造反派回去后,受了很大压力,希望先念同志今后不要对革命说气话。
总理:这个意见很好嘛!
先念:我已经道歉。
同学:我向总理转达一个问题。医大红旗希望总理接见他们。李先念在卫生部三月十日讲话稿是否送总理看了。
总理:看了。我那天托先念同志办一件事,卫生部的会开的方向不对头,经过调查确有其实,但我不愿意出面,就交给先念同志去办。我也知道先念同志有个财贸口子就够受了,这件事本来准备交给谢富治同志去办,因为他抓北京市工作很忙,还想找汪东兴同志去,汪东兴同志说卫生系统有部长,党委书记,我去不太好,只好找先念同志去,外边 的大字报写我是对的,先念同志是错的。我看了很难过,我要分担责任。我讲的话你没有听见,你怎么知道我是对的,先念是错的呢?还不是挑拨吗?不能这样写嘛!先念同志有记录,我看了,基本上是好的,我准备还看一遍,他是基本上传达了我们几个人所研究的,中央是知道的,在中央文革小组会上也谈过,他们方向是不对的。我一看到这些大字报就很不安,这件事在这个会上提出来了,我说一下就算了,不要外传,一传就走调了。我准备接见回答他们。
同学:在这次中央会议上,……
总理:你这个问题超过你们会议的范围。这样的问题我不能回答,我能回答的一定回答,不能讲的就不讲。
问:中央负责同志的讲话可否翻印?
总理:中央已经印刷出来的可以翻印,如伯达同志的讲话,林彪同志去年五月在政治局会上的讲话,发下来没有?(群众:没有)发到基层了,正式文本可以翻印,非正式文本不要翻印。过去北京市有好几千个联络站,整天向外地打电话,有的起了一点作用,有的就起了坏作用。现在传出去主席诗词很多,就不是主席写的嘛!(问:前进报是否可以复刊?)
总理:你们提出复刊的理由送先念同志和中央文革小组讨论。现在外边印小报,哪来的纸?二分钱一张,好多是道林纸,用那么好的道林纸印群丑图,这是丑化我们的国家,我们的党嘛!当然这些东西是坏的,但也不应这么搞嘛!这要追究一下责任。
同学:我们炮轰李先念的大标语是否可以上街?
总理有点生气:我不能回答,你们叫我怎么回答呢?你如果非要问我,我是不主张大字报上街的,但我们不能限制你们,现在大民主嘛!现在街上的许多大标语,不都是我同意的。他是我的副总理,中央还信任他嘛!你们的问题我不能回答,我是中央常委嘛!你们提问题经常使我为难,你们要考虑我所处的地位。我们已经半年多了,得有个起码的信任。你们总说我和中央文革口径不一样,就是不一样嘛!你们要揪刘少奇出来斗,当时也不是我一个人保,我对他有什么好感?你们要考虑我的地位吗!
同学:时间不早了。
总理笑了笑说:我看还有什么帐没还,今后贴我的大字报,正面反面我都不主张,一贴又好象我有什么问题似的,能够回答的我都回答,不能回答的我不回答。财贸口要召开大会,李先念同志做检讨,我要参加,早就答应了。我不去就不应该嘛!今后一些小事,就不要找我了。
(同学们强烈要求让总理休息,在掌声中总理、李副总理离开会场。)
刊载于《中央首长讲话》(3),北京玻璃总厂红卫兵联络站编,1967年4月。
CCRADB
|
Python
|
UTF-8
| 7,870 | 2.515625 | 3 |
[] |
no_license
|
# -*- coding:utf-8 -*-
import re
import xlrd
import xlsxwriter
import sys
import os
class colType:
def __init__(self):
#self.filename = sys.argv[1]
#path = os.path.dirname(self.filename)
#name = os.path.basename(self.filename).split('.')[0]
#self.model_name = path +"/"+ name + '_模型.xlsx'
#self.basename="e://files/model-test.xlsx"
#self.basename=self.filename
self.db_columns_type = {}
#特殊的排除在外,单独罗列出来
self.match_type = {'varcahr2': 'varchar',
'varchar2': 'varchar',
'varcahr': 'varchar',
'character': 'char',
'character varying': 'varchar',
'lvarchar':'varchar'
}
self.time_match_type = {
'timestamp with time zone': 'string',
'time':'timestamp',
'timestamp':'timestamp',
'timestampwithtimezone':'timestamp',
}
self.num_match_type = {
'integer': 'bigint',
'number': 'bigint',
'nuber': 'bigint',
'numeric': 'bigint',
'decimal': 'decimal',
'smallint': 'bigint'
}
def get_config_file_source(self):
# 读取配置文件
basefilename = "e://files/types.xlsx"
print("get_interface_index_source 打开" + basefilename)
data = xlrd.open_workbook(basefilename)
# 通过索引获取,例如打开第一个sheet表格
#table = data.sheet_by_name("接口目录")
table = data.sheet_by_index(0)
allrows = 0
types=set()
col_dict={}
all_type=[]
if data.sheet_loaded(0): # 检查某个sheet是否导入完毕
allrows = table.nrows # 获取该sheet中的有效行数
for rowindex in range(1, allrows):
cells = table.row_values(rowindex)
#print(cells)
type_name = cells[0].strip().lower()
#print(type_name) 替换中文的括号,替换掉空括号
type_name=type_name.replace('(','(').replace(')',')').replace('()','').replace(",",",")
if not type_name or type_name=='none':
#print("replace 替换之后的 type_name="+type_name)
continue
##开始处理各个字段类型的映射关系以及位数更正
if type_name.startswith("character varying"):
# print("type_name= character varying")
all_type.append(type_name)
elif type_name.startswith("timestamp"):
all_type.append(type_name)
else:
#type_name = re.sub(",\(", "(", type_name)
#print("type_name ="+type_name)
type_name=type_name.replace(" ","")
all_type.append(type_name)
##看数据项格式是否是含有括号的格式 如 varchar(20)
first = type_name.find("(")
pre_str=''
name=''
if first != -1:
name = type_name[0:first]
pre_str=name
else :
#print ("old 分割之前 "+type_name)
#splits = re.split('\d', name, 1)
#print(splits)
all_num = re.findall("\d+",type_name)
arrlen=len(all_num)
##这里导致了一个bug ,把 decimal15,2 数字替换成空,多了个,
findArr = re.split(r"\d",type_name,1)
pre_str=findArr[0]
if arrlen==2:
##替换掉char5 这种格式,可能是excel写错了的 decimal15,处理得到 decimal(15)
#print("pre decimal="+pre_str)
name=pre_str+"("+all_num[0]+","+all_num[1]+")"
elif arrlen == 1:
name=pre_str+"("+all_num[0]+")"
elif arrlen>2:
print("应该没有这种情况的出现 all_num >3 ")
else :
name=type_name
##把重新拼接好的值赋值给原有的type_name
#print(" 拼接前 type_name1="+type_name)
type_name=name
#print(" 拼接后 type_name="+type_name)
#print(" sub pre_str = "+pre_str)
#if not pre_str:
# pre_str=name
#print('not prestr ='+pre_str)
##开始建立数据项的一一映射关系
if pre_str=="time" or pre_str.startswith("timestamp"):
col_dict[type_name]="string"
#print( "match pre_str %s, %s, => %s" %(pre_str,type_name,"string"))
##处理 varchar这样的数据类型的映射关系
elif pre_str in self.match_type:
#col_dict.
newpre=self.match_type.get(pre_str)
type_name=str(type_name).replace(pre_str,newpre)
#print( "match pre_str %s, %s, => %s" %(pre_str,name,type_name))
col_dict[pre_str]=type_name
##处理 numric(5) numric(6,2)这种数据格式
elif pre_str in self.num_match_type:
#todo
# if pre_str =='decimal':
# #data_type=type_name.replace()
# data='decimal'
# else :
decimal = re.search("\d+\,", type_name)
#print("type_name="+str(decimal))
# print(decimal)
if pre_str.startswith("decimal"):
print('pre_str =%s typename=%s'%(pre_str,type_name))
if type_name =='decimal(17)':
newname='varchar(17)'
else :
#newname = re.sub('\)', ',2)', type_name)
newname = "decimal(20,2)"
data_type=newname
elif decimal:
data_type = type_name.replace(pre_str, "decimal")
else:
data_type = "bigint"
#print( "num match %s,%s => %s" %(pre_str,type_name,data_type))
#data_type=re.sub(',\(','(',data_type)
col_dict[type_name]=data_type
else :
#print("type_name2="+type_name)
col_dict[pre_str]=type_name
types.add(pre_str)
for key,value in col_dict.items():
print(key+" = "+value)
#print(all_type)
def main(self):
# 读取配置文件
self.get_config_file_source()
print("main 执行完成!!!")
# 判断输入参数
def judge_input_parameters_num():
if len(sys.argv) != 2:
print("请输入正确的是参数: aotu_generate_model_config_file.py configuration_files")
#sys.exit(1)
if __name__ == '__main__':
#judge_input_parameters_num()
#分割字符串比查找好,查找如果找不到,返回空数组
print(re.split("\d+", "decimal", 1))
#print(re.findall("\D+", "2344"))
aotu = colType()
aotu.main()
# print(re.findall("([a-z]+)(\,)","hello,(234,23)"))
# print(re.sub(",\(","(","hello,(234,23)"))
# print(re.sub(",\(","(","hello ,"))
|
Java
|
UTF-8
| 498 | 2.03125 | 2 |
[] |
no_license
|
package dao;
import java.util.List;
import org.springframework.transaction.annotation.Transactional;
import model.Responsable;
@Transactional
public interface ResponsableInt {
public void addResponsable(Responsable responsable);
public void updateResponsable(Responsable responsable);
public void deletresponsable(Responsable responsable);
public Responsable getResponsable(Integer id);
public List<Responsable> getListResponsable();
public void deletresponsableId(Integer responsable);
}
|
C++
|
UTF-8
| 1,010 | 3.015625 | 3 |
[] |
no_license
|
#include <iostream>
#include <string>
using namespace std;
typedef long long ll;
string A, B, As(100, 0), Bs(100, 0);
int main() {
cin >> A >> B;
size_t i = 0;
bool result = false;
bool greater;
for (size_t i = 0; i < A.length(); i++) {
char c = A[i];
if ('a' <= c && c <= 'z') {
c += 'A' - 'a';
}
As[i] = c;
}
for (size_t i = 0; i < B.length(); i++) {
char c = B[i];
if ('a' <= c && c <= 'z') {
c += 'A' - 'a';
}
Bs[i] = c;
}
while(!result && (As[i] != 0 || Bs[i] != 0)) {
if (As[i] > Bs[i]) {
greater = true;
result = true;
} else if (As[i] < Bs[i]) {
greater = false;
result = true;
}
i++;
}
if (result) {
if (greater) {
cout << "Greater" << endl;
} else {
cout << "Smaller" << endl;
}
} else {
cout << "Equal" << endl;
}
}
|
Python
|
UTF-8
| 4,814 | 3.328125 | 3 |
[] |
no_license
|
import numpy as np
class Reward():
def __init__(self):
pass
def get_reward(self, data, action):
'''
The main method we call for getting reward
'''
# The data we get from carla
image, depth, seg, velocity, accleration = data
# Our car position in the lane
position = self.lane_position(image)
# The distances of few objects (5-10) from our car
distances = self.object_distances(image, depth)
# The final reward
reward = self.calculate_reward(position, distances, velocity)
# print("Inside get_reward", reward)
# return reward
return 1
def lane_position(self, image):
'''
Detect lanes
calculate our car position wrt the lanes
[Use helper functions to keep this minimal]
Implement in lane_position.py
'''
position = 0
print("Inside lane position", image.shape)
return position
def object_distances(self, image, depth):
'''
We can return the distances of the closest 5-10 objects
Lets say our car is in traffic, our agent should be able to
apply brakes and move at low speed
First find the objects, then calculate distances based on the
depth from our camera
[Use helper functions to keep this minimal]
Implement in object_distances.py
'''
distances = [0,101,20]
print("Inside object_distances", image.shape, depth.shape)
return distances
def detect_signal(self, data):
'''
When detected we reward our agent based on the action performed near the signal
[Use helper functions to keep this minimal]
Implement in detect_signal.py
'''
print("Inside detect_signal", len(data))
return bool
def calculate_reward(self, position, distances, velocity):
'''
Returns the total reward
Each reward helps the agent to learn to perfrom better actions in each case
'''
print("Inside calculate_reward")
###############################################################
'''
Reward for Lane position :
Helps in lane keeping
We penalize according to the percentage occupancy of the lane
[Use helper functions and just get reward here using lane positon]
Implement in lane_reward.py
'''
rew_pos = None
###############################################################
'''
Reward for Distances :
Helps in maintaining minimal distance from other objects and applying brake
We should penalize the car for coming very close to objects like pedestrians
or other moving cars
[Use helper functions and just get reward here from using distances]
Implement in "distances_reward.py"
'''
rew_dis = None
###############################################################
'''
Reward for Speed :
Helps in controling our car speed
1. We should penalize for high speed of the car if we are taking turn or overspeeding
2. We should also consider the object distances to reward the speed of car (speed should be less in traffic or crowded areas)
[Use helper functions and just get reward here using car speed and acceleration]
Implement in "speed_reward.py"
'''
rew_vel = None
###############################################################
'''
Reward at signal :
Helps in understanding when to cross the signal
1. If signal detected we add this to total reward else put it as 0
2. We should give this reward when the car is crossing the signal not just when signal is detected
[Use helper functions and just get reward here using the state of signal and action performed]
Implement in "signal_reward.py"
'''
rew_sig = None
###############################################################
'''
Reward for applying brake at high speed, brake and throttle at the same time, applying reverse gear at high speed :
Helps in learning basic knowledge on how to control a car
[Use helper functions and just get reward using the state of signal and action performed]
Implement in "random_action_reward.py"
'''
rew_wrek = None
###############################################################
# total_reward = rew_pos + rew_dis + rew_vel + rew_sig + rew_wrek
# return total_reward
|
Python
|
UTF-8
| 1,104 | 3.578125 | 4 |
[] |
no_license
|
# parsing in python
#
# format: (c = comment, p CNF = conjunctive normal form)
# c
# c start with comments
# c
# c
# p cnf 5 3
# 1 -5 4 0
# -1 5 3 4 0
# -3 -4 0
def parseDataFile(filePath):
dataFile = open(filePath, "r")
data = dataFile.read()
data = data.split("\n")
nbvar = 0
nbclause = 0
clauses = []
for line in data:
# this line is a comment in the file - can ignore!
if line[0] == "c":
print(line[0])
# p cnf nbvar nbclauses
# cnf = the data type; nbvar = upper bound on the largest index of a variable, and nbclause = number of clauses in the file
elif line[0] == "p":
values = line.split(" ")
nbvar = int(values[2])
nbclause = int(values[3])
else:
# 2D array of clauses, inside array is the disjunction of variables
clause = line.split(" ")
for x in range(0, len(clause)):
clause[x] = int(clause[x])
clauses.append(clause)
return [nbvar, nbclause, clauses]
parseDataFile("test.txt")
|
JavaScript
|
UTF-8
| 1,512 | 3 | 3 |
[
"MIT"
] |
permissive
|
function validateLoginForm() {
var username = document.forms["Login"]["username"].value;
var password = document.forms["Login"]["password"].value;
if (username == "") {
alert("username must be filled");
return false;
}
if (password == "") {
alert("password must be filled");
return false;
}
}
function validateRegisterForm() {
var name = document.forms["Register"]["name"].value;
var regex_name=new RegExp("/^[a-zA-Z]+$/");
var password = document.forms["Register"]["password"].value;
var email = document.forms["Register"]["email"].value;
var cnfpassword = document.forms["Register"]["confirmpassword"].value;
var openBalance = document.forms["Register"]["openBalance"].value;
var numbers = /^[0-9]+$/;
var address = document.forms["Register"]["address"].value;
if (name == "") {
alert("username must be filled");
return false;
}
if (email == "") {
alert("email must be filled");
return false;
}
if (password == "" || cnfpassword == "") {
alert("password fields must be filled");
return false;
}
if (password != cnfpassword) {
alert("password must match");
return false;
}
if (address == "") {
alert("address must be filled");
return false;
}
if (openBalance == "") {
alert("openBalance must be filled");
return false;
}
if(!numbers.exec(openBalance)){
alert("openBalance must numbers");
return false;
}
}
|
JavaScript
|
UTF-8
| 247 | 3.40625 | 3 |
[] |
no_license
|
function reverseString(str) {
let letterArray = str.split('');
let reversedArray = [];
for (let i = 0; i < str.length; i++) {
reversedArray.push(letterArray.pop())
}
return reversedArray.join('');
}
module.exports = reverseString;
|
Java
|
UTF-8
| 2,128 | 2.59375 | 3 |
[] |
no_license
|
package ifnetpoo.Controllers;
import ifnetpoo.Models.PaginaWeb;
import ifnetpoo.Models.Livro;
import ifnetpoo.Models.Usuario;
import ifnetpoo.Models.Disciplina;
import ifnetpoo.Interfaces.IMaterial;
import ifnetpoo.DAO.MaterialDAO;
import ifnetpoo.Database.MySQLConnection;
import ifnetpoo.CustomExceptions.ExcessaoItemNaoEncontrado;
import ifnetpoo.Models.Apostila;
import java.util.ArrayList;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author gabriel
*/
public class MaterialController {
private final MaterialDAO materialDAO;
public MaterialController() {
var conn = new MySQLConnection();
this.materialDAO = new MaterialDAO(conn);
}
public ArrayList<IMaterial> index() {
return materialDAO.getMateriais();
}
public Livro store(String nome, String categoria, String autor, int edicao, int numeroDePaginas, Usuario criador, Disciplina disciplina) {
return this.materialDAO.adicionarMaterial(nome, categoria, autor, edicao, numeroDePaginas, criador, disciplina);
}
public Apostila store(String nome, String categoria, Usuario criador, String area, Disciplina disciplina) {
return this.materialDAO.adicionarMaterial(nome, categoria, criador, area, disciplina);
}
public PaginaWeb store (String nome, String categoria, String url, Usuario criador, Disciplina disciplina) {
return this.materialDAO.adicionarMaterial(nome, categoria, url, criador, disciplina);
}
public IMaterial destroy(int index) {
var materiais = this.materialDAO.getMateriais();
int size = materiais.size();
if (index < 0 || index > size - 1) {
throw new ExcessaoItemNaoEncontrado("Material não foi encontrado");
}
var materialDeletado = materiais.get(index);
this.materialDAO.removerMaterial(materialDeletado.getId());
return materialDeletado;
}
}
|
Java
|
UTF-8
| 1,110 | 3.265625 | 3 |
[] |
no_license
|
package com.company;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main (String[] args) throws IOException {
final int PORT = 8080;
final String ROOT_DIRECTORY_PATH = "root";
ServerSocket serverSocket = new ServerSocket(PORT);
int numberOfThreads = 0;
while (true) {
System.out.println("Waiting for connection...");
Socket socket = serverSocket.accept();
System.out.println("Connection established.");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter printWriter = new PrintWriter(socket.getOutputStream());
DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
// Open thread
Thread worker = new ServerWorker(socket, PORT, ROOT_DIRECTORY_PATH, bufferedReader, printWriter, dataInputStream, dataOutputStream);
worker.start();
numberOfThreads++;
System.out.println("Opened thread #" + numberOfThreads + "\n");
}
}
}
|
Java
|
UTF-8
| 591 | 2.671875 | 3 |
[] |
no_license
|
package com.montealegreluis.ticketbeast.concerts.address;
import static org.junit.jupiter.api.Assertions.*;
import com.montealegreluis.assertions.IllegalArgumentException;
import org.junit.jupiter.api.Test;
final class CityTest {
@Test
void it_cannot_be_blank() {
assertThrows(IllegalArgumentException.class, () -> new City(" "));
assertThrows(IllegalArgumentException.class, () -> new City(null));
}
@Test
void it_knows_its_current_value() {
var expectedCity = "Austin";
var city = new City(expectedCity);
assertEquals(expectedCity, city.value());
}
}
|
Swift
|
UTF-8
| 2,037 | 2.59375 | 3 |
[] |
no_license
|
//
// Created by Alx Krw on 08.10.2020
// Copyright © 2020 Ronas IT. All rights reserved.
//
import UIKit
import Framezilla
final class AppButton: UIButton {
var enabledSettings = (backgroundColor: UIColor.eveningSea, tintColor: UIColor.white)
var disabledSettings = (backgroundColor: UIColor.solitude, tintColor: UIColor.manatee)
var isLoading: Bool = false {
didSet {
guard isLoading != oldValue else {
return
}
if isLoading {
titleLabel?.alpha = 0
imageView?.transform = CGAffineTransform(scaleX: 0, y: 0)
activityIndicatorView.startAnimating()
isUserInteractionEnabled = false
} else {
titleLabel?.alpha = 1
imageView?.transform = .identity
activityIndicatorView.stopAnimating()
isUserInteractionEnabled = true
}
}
}
override var isEnabled: Bool {
didSet {
if isEnabled {
backgroundColor = enabledSettings.backgroundColor
tintColor = enabledSettings.tintColor
} else {
backgroundColor = disabledSettings.backgroundColor
tintColor = disabledSettings.tintColor
}
}
}
// MARK: - Subviews
private lazy var activityIndicatorView = UIActivityIndicatorView()
// MARK: - Lifecycle
override init(frame: CGRect = .zero) {
super.init(frame: frame)
addSubview(activityIndicatorView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
activityIndicatorView.configureFrame { maker in
maker.size(width: 24, height: 24).center()
}
}
// MARK: - Helpers
func setActivityIndicatorColor(_ color: UIColor) {
activityIndicatorView.color = color
}
}
|
C++
|
UTF-8
| 2,305 | 3.328125 | 3 |
[] |
no_license
|
#include <iostream>
#include <string>
#include "Fighter.h"
using namespace std;
int main(){
Fighter creature_one(50.0, 30.0, 10.0, 5.0,"Ratatat" );
Fighter creature_two(200.0, 60.0, 10.0, 30.0,"Lunala");
int optionNumber;
while(true){
cout << "USER 1 \n\n";
creature_one.display_statistics();
cout << "What would you like to do?\n";
cout << "1: Attack\n";
cout << "2: Boost Defense\n";
cout << "3: Heal\n";
cout << "Select Option:";
cin >> optionNumber;
if(optionNumber == 1){
creature_two.take_damage(creature_one.get_damage());
}
else if(optionNumber == 2){
creature_one.boost_defense();
}
else if(optionNumber == 3){
creature_one.heal_self();
}
else{
cout << "The creature doesn't knowwhat to do!\n";
cout << "It hit itself in confusion!\n";
creature_one.take_damage(creature_one.get_damage());
}
if(creature_one.is_alive() == false){
cout << "\n\nUSER 2 has won!\n\n";
break;
}
if(creature_two.is_alive() == false){
cout << "\n\nUSER 1 has won!\n\n";
break;
}
cout << "\nUSER 2 \n\n";
creature_two.display_statistics();
cout << "What would you like to do?\n";
cout << "1: Attack\n";
cout << "2: Boost Defense\n";
cout << "3: Heal\n";
cout << "Select Option:";
cin >> optionNumber;
if(optionNumber == 1){
creature_one.take_damage(creature_two.get_damage()*0.75);
}
else if(optionNumber == 2){
creature_two.boost_defense();
}
else if(optionNumber == 3){
creature_two.heal_self();
}
else{
cout << "The creature doesn't knowwhat to do!\n";
cout << "It hit itself in confusion!\n";
creature_two.take_damage(creature_two.get_damage()* 0.75);
}
if(creature_one.is_alive() == false){
cout << "\n\nUSER 2 has won!\n\n";
break;
}
if(creature_two.is_alive() == false){
cout << "\n\nUSER 1 has won!\n\n";
break;
}
}
}
|
C#
|
UTF-8
| 1,158 | 3.625 | 4 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Page07
{
class Program
{
public static void Main()
{
int n;
int other = 100;
// Console.WriteLine($"inside Main before: n= {n}, other = {other}"); // error n is unassigned
other = Add10(out n, true); // note out is allowed, and anotehr parameter is provided (a bool = true)
Console.WriteLine($"inside Main after: n= {n}, other = {other}");
}
public static int Add10(out int n, bool High) // note out, and additional parameter
{
//Console.WriteLine($"inside Add10 before: n= {n}"); // error n is unassigned
if (High)
{
n = 1000; // return 1000 to variable n (n is HIGH) (goes into n on line 14)
}
else
{
n = 10; // return 10 to variable n (n is not HIGH) (goes into n on line 14)
}
return 5; // return 5 as the actual return value (goes into other on line 17)
}
}
}
|
Markdown
|
UTF-8
| 1,526 | 2.828125 | 3 |
[] |
no_license
|
# Microservice
## Why Microservice?
Because of several drawbacks of previous architecture - Monolithic Architecture:
1. Unreliable:

if part of service is down, entire services are down. impact the availability of entire application
2. Unsalable: there is a need that we need to scale up, such as some services are cpu intensive and some are memory intensive. With microservice, we are able to only scale up the services that needs scale up independently.
3. Slow deployment: every time adds a new feature or change the service, Monolithic need to redeploy from scratch, microservice only needs to deploy partial, which is faster
4. Large & complex application: if the service is down, developers have to start from zero to look up the bugs
## What is Microservice?

Each component implement single business capability
They will communicate through APIs
### Example:


They are independent to each other, their libraries are different, database are different
API Gateway: forward the request from clients to the corresponding services
## Features of Microservice Architecture

1. for simplicity
2. independent
3. written in any languages
4. each microservice does not need to understand the implementation of other microservices
## Advantages

|
Python
|
UTF-8
| 684 | 3.890625 | 4 |
[
"Apache-2.0"
] |
permissive
|
import collections
class Path(object):
"""Path object represents a single node in a words path
It's used for finding path between two corresponding words.
Technically it is a reversed linked list where each node keeps a value set to a
certain word and a pointer to the previous node.
"""
def __init__(self, word, previous=None):
self.word = word
self.previous = previous
def get_path(self):
"""Generate path starting from this path."""
node = self
result = collections.deque()
while node is not None:
result.appendleft(node.word)
node = node.previous
return list(result)
|
PHP
|
UTF-8
| 1,077 | 2.515625 | 3 |
[] |
no_license
|
<?php
Require_once 'pdo.php';
function loai_insert($ten_loai){
$sql = "INSERT INTO loaihang(ten_loai) VALUES(?)";
pdo_execute($sql, $ten_loai);
}
function loai_update($ma_loai, $ten_loai){
$sql = "UPDATE loaihang SET ten_loai=? WHERE ma_loai=?";
pdo_execute($sql, $ten_loai, $ma_loai);
}
function loai_delete($ma_loai){
$sql = "DELETE FROM loaihang WHERE ma_loai=?";
if(is_array($ma_loai)){
foreach ($ma_loai as $ma) {
pdo_execute($sql, $ma);
}
}
else{
pdo_execute($sql, $ma_loai);
}
}
function loai_select_all(){
$sql = "SELECT * FROM loaihang";
return pdo_query($sql);
}
function loai_select_by_id($ma_loai){
$sql = "SELECT * FROM loaihang WHERE ma_loai=?";
return pdo_query_one($sql, $ma_loai);
}
function loai_exist($ma_loai){
$sql = "SELECT count(*) FROM loaihang WHERE ma_loai=?";
return pdo_query_value($sql, $ma_loai) > 0;
}
?>
|
C#
|
UTF-8
| 1,205 | 3.796875 | 4 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PracticalPart5._4
{
class Program
{
static void Main(string[] args)
{
//Сформировать одномерный массив из 20 случайных чисел в диапазоне [-50;50]. Определить количество нечетных положительных элементов, стоящих на четных местах.
const int n = 20;
int[] array = new int[n];
Random random = new Random();
for (int i = 0; i < n; i++)
{
array[i] = random.Next(-50, 50);
Console.Write("{0,4}", array[i]);
}
int a = 0;
for (int i = 1; i < n; i=i+2)
{
if (array[i]>0)
{
if (array[i]%2!=0)
{
a++;
}
}
}
Console.WriteLine();
Console.WriteLine("Ответ = {0}",a);
Console.ReadKey();
}
}
}
|
C++
|
UTF-8
| 877 | 3.109375 | 3 |
[] |
no_license
|
class Solution {
public:
int len(vector<int>& p){
return p[0]*p[0]+p[1]*p[1];
}
void quickSel(vector<vector<int>>& points,int left,int right,int K){
if(left==right) return;
int pvt=len(points[right]);
int index=left;
for(int i=left;i<right;++i){
if(len(points[i])<pvt){
swap(points[i],points[index]);
++index;
}
}
swap(points[right],points[index]);
if(index+1==K||index==K) return;
if(index>K) quickSel(points,left,index-1,K);
else quickSel(points,index+1,right,K);
}
vector<vector<int>> kClosest(vector<vector<int>>& points, int K) {
quickSel(points,0,points.size()-1,K);
vector<vector<int>> ans;
for(int i=0;i<K;++i){
ans.push_back(points[i]);
}
return ans;
}
};
|
C#
|
UTF-8
| 6,807 | 3.03125 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace WF_AsyncPinger
{
static class AsyncHelper
{
static public bool PingSync(string _ip)
{
using (Ping myPing = new Ping())
{
PingReply _replied = myPing.Send(_ip);
return (_replied.Status == IPStatus.Success) ? true : false;
}
}
static async public Task<bool> PingAsync(string _ip)
{
using (Ping myPing = new Ping())
{
var _replied = await myPing.SendPingAsync(_ip);
return (_replied.Status == IPStatus.Success) ? true : false;
}
}
static public bool TelnetSync(string _ip, int _port)
{
TcpClient tcpClient = null;
try
{
tcpClient = new TcpClient(_ip, _port);
return true;
}
catch (SocketException)
{
return false;
}
finally
{
if (tcpClient != null)
{
tcpClient.Close();
}
}
}
static async public Task<bool> TelnetAsync(string _ip, int _port)
{
TcpClient tcpClient = null;
try
{
tcpClient = new TcpClient();
await tcpClient.ConnectAsync(_ip, _port);
return true;
}
catch (SocketException)
{
return false;
}
finally
{
if (tcpClient != null)
{
tcpClient.Close();
}
}
}
public static IEnumerable<TracertEntry> Tracert(string ipAddress, int maxHops, int timeout)
{
IPAddress address;
// Ensure that the argument address is valid.
if (!IPAddress.TryParse(ipAddress, out address))
throw new ArgumentException(string.Format("{0} is not a valid IP address.", ipAddress));
// Max hops should be at least one or else there won't be any data to return.
if (maxHops < 1)
throw new ArgumentException("Max hops can't be lower than 1.");
// Ensure that the timeout is not set to 0 or a negative number.
if (timeout < 1)
throw new ArgumentException("Timeout value must be higher than 0.");
Ping ping = new Ping();
PingOptions pingOptions = new PingOptions(1, true);
Stopwatch pingReplyTime = new Stopwatch();
PingReply reply;
do
{
pingReplyTime.Start();
reply = ping.Send(address, timeout, new byte[] { 0 }, pingOptions);
pingReplyTime.Stop();
string hostname = string.Empty;
if (reply.Address != null)
{
try
{
hostname = Dns.GetHostByAddress(reply.Address).HostName; // Retrieve the hostname for the replied address.
}
catch (SocketException) { /* No host available for that address. */ }
}
// Return out TracertEntry object with all the information about the hop.
yield return new TracertEntry()
{
HopID = pingOptions.Ttl,
Address = reply.Address == null ? "N/A" : reply.Address.ToString(),
Hostname = hostname,
ReplyTime = pingReplyTime.ElapsedMilliseconds,
ReplyStatus = reply.Status
};
pingOptions.Ttl++;
pingReplyTime.Reset();
}
while (reply.Status != IPStatus.Success && pingOptions.Ttl <= maxHops);
}
public static async Task<dynamic[]> TracertAsync(string ipAddress, int maxHops, int timeout)
{
IPAddress address;
// Ensure that the argument address is valid.
if (!IPAddress.TryParse(ipAddress, out address))
throw new ArgumentException(string.Format("{0} is not a valid IP address.", ipAddress));
// Max hops should be at least one or else there won't be any data to return.
if (maxHops < 1)
throw new ArgumentException("Max hops can't be lower than 1.");
// Ensure that the timeout is not set to 0 or a negative number.
if (timeout < 1)
throw new ArgumentException("Timeout value must be higher than 0.");
Ping ping = new Ping();
PingOptions pingOptions = new PingOptions(1, true);
Stopwatch pingReplyTime = new Stopwatch();
PingReply reply;
//dynamic dynamicHolder = new dynamic[]
dynamic[] sa = new dynamic[5];
do
{
pingReplyTime.Start();
reply = await ping.SendPingAsync(address, timeout, new byte[] { 0 }, pingOptions);
pingReplyTime.Stop();
string hostname = string.Empty;
if (reply.Address != null)
{
try
{
hostname = Dns.GetHostByAddress(reply.Address).HostName; // Retrieve the hostname for the replied address.
}
catch (SocketException) { /* No host available for that address. */ }
}
// Return out TracertEntry object with all the information about the hop.
//yield return sa; //TracertEntry()
{
sa[0] = pingOptions.Ttl;
sa[1] = reply.Address == null ? "N/A" : reply.Address.ToString();
sa[2] = hostname;
sa[3] = pingReplyTime.ElapsedMilliseconds;
sa[4] = reply.Status;
//HopID = pingOptions.Ttl,
//Address = reply.Address == null ? "N/A" : reply.Address.ToString(),
//Hostname = hostname,
//ReplyTime = pingReplyTime.ElapsedMilliseconds,
//ReplyStatus = reply.Status
};
pingOptions.Ttl++;
pingReplyTime.Reset();
}
while (reply.Status != IPStatus.Success && pingOptions.Ttl <= maxHops);
return sa;
}
}
}
|
Swift
|
UTF-8
| 8,106 | 2.515625 | 3 |
[
"MIT"
] |
permissive
|
//
// MainViewController.swift
// Weibo
//
// Created by sw on 16/6/6.
// Copyright © 2016年 sw. All rights reserved.
//
import UIKit
class MainViewController: UITabBarController {
// MARK: 生命周期方法
override func viewDidLoad() {
super.viewDidLoad()
// 添加所有子控制器
addChildViewControllers()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
// 初始化加号按钮
setupComposeBtn()
}
// MARK: 初始化加号按钮
private func setupComposeBtn() {
// 把加号按钮添加到tabBar上
tabBar.addSubview(composeButton)
// 设置宽度
// let width = tabBar.itemWidth
let width = tabBar.bounds.width / CGFloat(childViewControllers.count)
// 设置高度
let height = tabBar.frame.size.height
// 修改frame
let rect = CGRect(origin:CGPointZero, size:CGSize(width:width, height:height))
composeButton.frame = CGRectOffset(rect, 2 * width, 0)
}
// MARK: 添加所有子控制器
private func addChildViewControllers() {
/*
// addChildViewController(HomeTableViewController(), image: "tabbar_home", highLightImage: "tabbar_home_highlighted", title: "首页")
// addChildViewController(MessageTableViewController(), image: "tabbar_message_center", highLightImage: "tabbar_message_center_highlighted", title: "消息")
// addChildViewController(DiscoverTableViewController(), image: "tabbar_discover", highLightImage: "tabbar_discover_highlighted", title: "发现")
// addChildViewController(ProfileTableViewController(), image: "tabbar_profile", highLightImage: "tabbar_profile_highlighted", title: "我")
*/
let path = NSBundle.mainBundle().pathForResource("MainVCSettings.json", ofType: nil)!
let data = NSData.init(contentsOfFile: path)!
do{
let dicArr = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers)
for dic in dicArr as! [[String:AnyObject]]
{
addChildViewController(dic["vcName"] as? String, image: dic["imageName"] as? String, highLightImage: (dic["imageName"] as? String)! + "_highlighted", title: dic["title"] as? String)
}
} catch{
addChildViewController("HomeTableViewController", image: "tabbar_home", highLightImage: "tabbar_home_highlighted", title: "首页")
addChildViewController("MessageTableViewController", image: "tabbar_message_center", highLightImage: "tabbar_message_center_highlighted", title: "消息")
addChildViewController("NullViewController", image: "", highLightImage: "", title: "")
addChildViewController("DiscoverTableViewController", image: "tabbar_discover", highLightImage: "tabbar_discover_highlighted", title: "发现")
addChildViewController("ProfileTableViewController", image: "tabbar_profile", highLightImage: "tabbar_profile_highlighted", title: "我")
}
}
// MARK: 创建子控制器
private func addChildViewController(childControllerName: String?, image: String?, highLightImage: String?, title:String?) {
let nameSpace = NSBundle.mainBundle().infoDictionary!["CFBundleExecutable"]
// 可选绑定
guard let ns = nameSpace as? String else {
WSLog("命名空间不存在")
return
}
//if let ns = nameSpace as? String {
guard let vcName = childControllerName else {
WSLog("控制器名称不能为nil")
return
}
let cls : AnyClass? = NSClassFromString(ns + "." + vcName)
// AnyClass本质是AnyObject.Type类型
// UIViewController本质是UIViewController.Type类型
// 将AnyClass转为UIViewController类型
// 类型绑定:如果是这个类型,那么就执行{}内部代码,否则不执行
// 不安全:let clsType = cls as! UIViewController.Type 直接将结果强转成UIViewController类型
guard let clsType = cls as? UIViewController.Type else {
WSLog("传入的字符串不能到最UIViewController来使用")
return
}
// if let clsType = cls as? UIViewController.Type {
let childController = clsType.init()
WSLog(childController)
// 如果是在iOS8以前,只有文字有效果,而图片没效果
tabBar.tintColor = UIColor.orangeColor()
// 控制器选项卡属性
guard let iName = image else {
return
}
childController.tabBarItem.image = UIImage(named: iName)
guard let highIName = highLightImage else {
return
}
childController.tabBarItem.selectedImage = UIImage(named: highIName)
guard let titleName = title else {
return
}
childController.title = titleName
// 包装导航控制器
let nav = UINavigationController(rootViewController: childController)
// 添加子控制器
addChildViewController(nav)
// }
// }
}
// MARK: 懒加载发布按钮
private lazy var composeButton: UIButton = {
var btn = UIButton(imageName: "tabbar_compose_icon_add", backImageName: "tabbar_compose_button")
btn.addTarget(self, action: Selector("composeBtnClick"), forControlEvents: UIControlEvents.TouchUpInside)
return btn
/*
var btn = UIButton.create("tabbar_compose_icon_add", backImageName: "tabbar_compose_button")
btn.addTarget(self, action: Selector("composeBtnClick"), forControlEvents: UIControlEvents.TouchUpInside)
return btn
*/
/*
var btn = UIButton()
// 1.设置背景图片
btn.setBackgroundImage(UIImage.init(named: "tabbar_compose_button"), forState: UIControlState.Normal)
btn.setBackgroundImage(UIImage.init(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
// 2.设置前景图片
btn.setImage(UIImage.init(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
btn.setImage(UIImage.init(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
// 3.监听按钮点击
btn.addTarget(self, action: Selector("composeBtnClick"), forControlEvents: UIControlEvents.TouchUpInside)
return btn
*/
}()
//MARK: 监听按钮点击
// 注意: 由于点击事件是由NSRunLoop发起的, 并不是当前类发起的, 所以如果在点击方法前面加上private, 那么NSRunLoop无法找到该方法
// OC是基于运行时动态派发事件的, 而Swift是编译时就已经确定了方法
// 如果想给监听点击的方法加上private, 并且又想让系统动态派发时能找到这个方法, 那么可以在前面加上@objc, @objc就能让这个方法支持动态派发
@objc private func composeBtnClick() {
WSLog("点击了写作按钮")
}
// // MARK: 内部控制方法
// func addChildViewController(childController:UIViewController, image: String, highLightImage: String, title:String) {
// // 如果是在iOS8以前,只有文字有效果,而图片没效果
// tabBar.tintColor = UIColor.orangeColor()
// // 控制器选项卡属性
// childController.tabBarItem.image = UIImage(named: image)
// childController.tabBarItem.selectedImage = UIImage(named: highLightImage)
// childController.title = title
// // childController.tabBarItem.title = title;
// // childController.navigationItem.title = title;
// // 包装导航控制器
// let nav = UINavigationController(rootViewController: childController)
// // 添加子控制器
// addChildViewController(nav)
// }
}
|
C
|
UTF-8
| 1,800 | 2.765625 | 3 |
[] |
no_license
|
/*
** parsing_args.c for PSU_2015_zappy
**
** Made by Matthew LEJEUNE
** Login lejeun_m
**
** Started on Fri Jun 10 15:46:01 2016 Matthew LEJEUNE
** Last update Mon Jun 13 15:31:13 2016 Matthew LEJEUNE
*/
#include "server.h"
int find_port(char **av)
{
int index;
index = 0;
while (av[index] != NULL)
{
if (strcmp(av[index], "-p") == 0)
return (atoi(av[index + 1]));
index++;
}
return (-1);
}
void parse_h_w(char **av, t_server **server)
{
int number;
if (!av[1] || (number = atoi(av[1])) == 0)
{
dprintf(1, "World size must be > 0 in each axes\n");
exit(EXIT_FAILURE);
}
if (av[0][1] == 'x')
(*server)->world_width = atoi(av[1]);
else if (av[0][1] == 'y')
(*server)->world_height = atoi(av[1]);
}
void parse_nb_client(char **av, t_server **server)
{
if (!av[1] || av[1][0] == '-')
{
dprintf(1, "Missing argument for '%c'\n", av[0][1]);
exit(EXIT_FAILURE);
}
(*server)->max_client_per_squad = atoi(av[1]);
}
void parse_frequency(char **av, t_server **server)
{
if (!av[1] || av[1][0] == '-' || atoi(av[1]) <= 0)
{
dprintf(1, "Invalid argument for '%c'\n", av[0][1]);
exit(EXIT_FAILURE);
}
(*server)->frequency = atoi(av[1]);
}
int parse_opt(char **av, t_server **server)
{
int index;
int port;
index = 0;
if ((port = find_port(av)) == -1)
{
dprintf(1, "Port not found");
return (-1);
}
*server = init_server(port);
(*server)->port = port;
while (av[index] != NULL)
{
if (av[index][1] == 'x' || av[index][1] == 'y')
parse_h_w(&av[index], server);
if (av[index][1] == 'c')
parse_nb_client(&av[index], server);
if (av[index][1] == 't')
parse_frequency(&av[index], server);
if (av[index][1] == 'n')
parse_squad(server, &av[index + 1]);
index++;
}
return (0);
}
|
Markdown
|
UTF-8
| 1,942 | 3 | 3 |
[
"MIT"
] |
permissive
|
# Docker Example with NiceGUI
This README provides a walkthrough on how to utilize the NiceGUI release docker image, [zauberzeug/nicegui, available on Docker Hub](https://hub.docker.com/r/zauberzeug/nicegui).
The image is configured using a `docker-compose.yml` file for ease of use.
You can achieve similar results using the `docker run` command along with its appropriate parameters.
## Testing the Setup
Modify the `docker-compose.yml` file to reflect your local host user's uid/gid and then execute the command:
```bash
docker compose up
```
## Special Docker Features
### Data Persistence
NiceGUI automatically generates a `.nicegui` directory in the application's root directory (`/app` within the docker container).
In this example, the local `app` folder is mounted to the `/app` location inside the container, ensuring that the `.nicegui` folder remains persistent across docker restarts.
You can validate this by accessing http://localhost:8080, inputting some data for storage, and then restarting the container.
### Non-Root User Execution
The application within the container operates as a non-root user (similar to the [configs from linuxserver.io](https://docs.linuxserver.io/general/understanding-puid-and-pgid)).
Consequently, all files generated by NiceGUI (such as the `.nicegui` persistence) will bear the configured uid/gid.
### Docker Signal Pass-Through
The docker image is designed to relay signals from Docker, such as SIGTERM, to initiate a graceful shutdown of NiceGUI.
For instance, when you stop the container (using Ctrl+C) and subsequently examine the logs using the `docker compose logs` command,
you should notice the initiation of the `ui.shutdown` method.
### Storage Secret
In the example `main.py` we read the [storage secret](https://nicegui.io/documentation/storage) from a environment variable.
This can then be defined in the `docker-compose.yml` (or even passed on from an `.env` file).
|
Java
|
UTF-8
| 1,150 | 2.453125 | 2 |
[] |
no_license
|
package com.wgycs.webview;
import android.util.Log;
import android.webkit.JavascriptInterface;
import org.json.JSONObject;
/**
* @ProjectName: FM_android
* @Package: com.wgycs.library_webview
* @ClassName: JavaScriptInterface
* @Description: webview js 接口处理类
* @Create: By wangy / 2020/4/7 19:49
* @Version: 1.0
*/
public final class JSInterface {
private JsFuncCallback callback;
public void setCallback(JsFuncCallback callback) {
this.callback = callback;
}
public interface JsFuncCallback {
void execute(String json);
}
/**
* 注册给 js 调用的方法
* */
@JavascriptInterface
public void nativeMessageHandle(final String json) {
if (callback != null) {
callback.execute(json);
}
}
/**
* js callback
* */
@JavascriptInterface
public void nativeMessageHandle(final JSONObject json) {
if (callback != null) {
callback.execute(json.toString());
Log.d("JSONObject", "nativeMessageHandle: " + json.toString());
}
}
}
|
Python
|
UTF-8
| 885 | 3.578125 | 4 |
[] |
no_license
|
class Animal():
def __init__(self, nome, idade, genero, peso):
self._nome = nome
self._idade = idade
self._genero = genero
self._peso = peso
self._energia = 60.0
self.som = ""
def obter_informacoes(self):
return "Nome: {} | Idade: {} | Gênero: {} \nPeso: {:.2f} KG | Energia: {:.1f} %".format(self._nome, self._idade, self._genero, self._peso, self._energia)
def comer(self):
self._peso += 0.7
if self._energia < 75:
self._energia += 25.0
else:
self._energia = 100.0
def mover(self):
self._peso -= 0.1
if self._energia > 20:
self._energia -= 10.0
def emitir_som(self):
if self._energia > 10:
self._energia -= 5.0
return "{} \n".format(self.som)
else:
return ""
|
Markdown
|
UTF-8
| 252 | 3.21875 | 3 |
[] |
no_license
|
# 次数
## 概念与性质
定义(次数):
- 设 m 是大于 1 的整数,a 是与 m 互素的整数,使 $$a^l \equiv 1 \pmod{m}$$ 成立的最小正整数 l 叫做 a 对模 m 的次数。记作 $$ord_m(a)$$ 或 $$\sigma(a)$$
|
Java
|
UTF-8
| 3,026 | 2.375 | 2 |
[
"BSD-3-Clause",
"LGPL-2.1-or-later",
"LicenseRef-scancode-mit-old-style",
"EPL-2.0",
"CDDL-1.0",
"MIT",
"LGPL-2.1-only",
"Apache-2.0",
"MPL-2.0",
"EPL-1.0"
] |
permissive
|
/*
* Copyright 2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.api.reporting;
import groovy.lang.Closure;
import groovy.lang.DelegatesTo;
import org.gradle.api.Action;
/**
* An object that provides reporting options.
* <p>
* Tasks that produce reports as part of their execution expose configuration options of those reports via these methods.
* The {@code Reporting} interface is parameterized, where the parameter denotes the specific type of reporting container
* that is exposed. The specific type of the reporting container denotes the different types of reports available.
* <p>
* For example, given a task such as:
* </p>
* <pre>
* class MyTask implements Reporting<MyReportContainer> {
* // implementation
* }
*
* interface MyReportContainer extends ReportContainer<Report> {
* Report getHtml();
* Report getCsv();
* }
* </pre>
* <p>
* The reporting aspects of such a task can be configured as such:
* </p>
* <pre>
* task my(type: MyTask) {
* reports {
* html.required = true
* csv.required = false
* }
* }
* </pre>
* <p>
* See the documentation for the specific {@code ReportContainer} type for the task for information on report types and options.
* </p>
*
* @param <T> The base type of the report container
*/
public interface Reporting<T extends ReportContainer> {
/**
* A {@link ReportContainer} instance.
* <p>
* Implementers specify a specific implementation of {@link ReportContainer} that describes the types of reports that
* are available.
*
* @return The report container
*/
T getReports();
/**
* Allow configuration of the report container by closure.
*
* <pre>
* reports {
* html {
* required false
* }
* xml.outputLocation = "build/reports/myReport.xml"
* }
* </pre>
*
* @param closure The configuration
* @return The report container
*/
T reports(@DelegatesTo(type="T", strategy = Closure.DELEGATE_FIRST) Closure closure);
/**
* Allow configuration of the report container by closure.
*
* <pre>
* reports {
* html {
* required false
* }
* xml.outputLocation = "build/reports/myReport.xml"
* }
* </pre>
* @param configureAction The configuration
* @return The report container
*/
T reports(Action<? super T> configureAction);
}
|
Java
|
UTF-8
| 5,058 | 2.046875 | 2 |
[] |
no_license
|
package com.restful.daily_click.repository;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.restful.daily_click.entity.ClassInfoEntity;
import com.restful.daily_click.entity.ClassRoomEntity;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import javax.transaction.Transactional;
import java.util.List;
public interface ClassRepository extends JpaRepository<ClassRoomEntity,Integer> {
//------------得到班级名字集合------------
@Query(value = "select class_id,class_name as name from class_info",nativeQuery = true)
List<JSONObject> getCLassNameList();
@Query(value = "select * from class_room",nativeQuery = true)
List<JSONObject> findRoomUidsByUserIdPageable(Pageable pageable);
@Query(value = "select count(*) from class_room",nativeQuery = true)
int getNumberfromClassRoom();
@Modifying
@Query(value = "DELETE FROM class_room WHERE id = ?1",nativeQuery = true)
@Transactional
int delClassRoom(int id);
@Modifying
@Query(value = "UPDATE class_room SET room_name = ?1, capacity = ?2 WHERE id = ?3 ",nativeQuery = true)
@Transactional
int changeClassData(Object room_name, Object capacity, Integer id);
@Modifying
@Query(value = "DELETE FROM class_room_seat WHERE room_id = ?1",nativeQuery = true)
@Transactional
int delectAllById(Integer id);
@Query(value = "select * from class_room_seat WHERE room_id = ?1",nativeQuery = true)
List<JSONObject> getSeatArr(int id);
@Modifying
//---------添加教室信息----------
@Query(value = "INSERT INTO class_room(room_name, capacity, length) values(?1,?2,?3)",nativeQuery = true)
@Transactional
int addNewClassRoom(String room_name, Integer capacity, int length);
@Query(value = "SELECT LAST_INSERT_ID()",nativeQuery = true)
int getLastInsert();
//----得到教室座位信息-------
@Query(value = "select * from class_room_seat WHERE room_id = ?1",nativeQuery = true)
JSONArray getSeatData(int classroomid);
//-----得到教室信息---------
@Query(value = "select * from class_room WHERE id = ?1",nativeQuery = true)
JSONObject getRoomData(int classroomid);
@Query(value = "select * from class_info where majority_id = ?1",nativeQuery = true)
List<JSONObject> getAllClassByMajorId(Pageable pageable, int majorid);
@Query(value = "select count(*) from class_info where majority_id = ?1",nativeQuery = true)
int getAllClassByMajorIdNum(int majorid);
@Transactional
@Modifying
@Query(value = "DELETE from class_info where id = ?1",nativeQuery = true)
int delClass(String id);
@Transactional
@Modifying
@Query(value = "UPDATE class_info set class_id=?1, class_name=?2, class_year=?3 where id = ?4",nativeQuery = true)
int editClass(String class_id, String class_name, String class_year, String id);
@Query(value = "select * FROM class_info WHERE class_name like %?1%",nativeQuery = true)
ClassInfoEntity findClassByClassName(String class_name);
@Transactional
@Modifying
@Query(value = "insert into class_info(class_id,class_name,class_year,majority_id) values(?1,?2,?3,?4)",nativeQuery = true)
int addClass(String class_id, String class_name, String class_year, String majority_id);
@Query(value = "select class_id,class_name as name from class_info",nativeQuery = true)
List<JSONObject> creatNewSignGetclassList();
@Query(value = "select id, room_name AS name from class_room",nativeQuery = true)
List<JSONObject> getAllClassRoom();
@Transactional
@Modifying
@Query(value = "UPDATE class_room set class_room.length = ?1 where id = ?2",nativeQuery = true)
int changeLength(int length, int id);
@Query(value = "select class_info.class_id,class_info.class_name as name " +
"from class_info,information " +
"WHERE information.tea_code = ?1 AND information.class_id = class_info.class_id " +
"GROUP BY class_info.class_id",nativeQuery = true)
List<JSONObject> miniPrograGetTeacherTeachClass(String account);
@Query(value = "select class_room.id, class_room.room_name AS name " +
"from class_room,information " +
"WHERE information.tea_code = ?1 AND information.room_id = class_room.room_name",nativeQuery = true)
List<JSONObject> miniproTeacherGetClassRoomList(String account);
@Query(value = "select class_room_seat.id,class_room_seat.room_id,class_room_seat.is_seat,class_room_seat.row,class_room_seat.col,class_room.length,class_room_seat.labstuname,class_room.room_name " +
"from class_room,class_room_seat,group_item " +
"WHERE group_item.id = ?1 and group_item.group_name = class_room.room_name and class_room.id = class_room_seat.room_id",nativeQuery = true)
JSONArray getLabSeatInfoById(int seatid);
}
|
C#
|
UTF-8
| 755 | 2.609375 | 3 |
[] |
no_license
|
using System;
using System.Windows.Input;
using WpfTest.Components;
namespace WpfTest.ViewModels
{
public class CameraViewModel : NotificationObject
{
private int _imageWidth;
public CameraViewModel()
{
ImageWidth = 1280;
SetImageWidthCommand = new DelegateCommand(p => ImageWidth = Convert.ToInt32(p), p => Convert.ToInt32(p) != ImageWidth);
}
public int ImageWidth
{
get { return _imageWidth; }
private set
{
if (value == _imageWidth) return;
_imageWidth = value;
OnPropertyChanged();
}
}
public ICommand SetImageWidthCommand { get; private set; }
}
}
|
C++
|
UTF-8
| 1,236 | 2.640625 | 3 |
[] |
no_license
|
#pragma once
#ifndef LEX_HPP
#define LEX_HPP_DEF
#include <iostream>
#include <string>
#include <fstream>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <float.h>
#define st_compare 0
#define st_reserved 1
#define st_variable 2
using namespace std;
bool isNumber(char a);
int isReservado(string a);
bool isLetter(char a);
int isSymbol(char a);
int int_max_v = 2147483647;
int max_string_size = 10;
int line_counter = 1;
string reservado[18] = {"while","void", "string", "return", "main", "integer",
"inicio", "if","for", "float", "fim" ,"else", "double", "do", "cout",
"cin", "char", "function"};
int index_res[18] = {1, 2, 3, 4, 11, 13, 15, 16, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27 };
char numbers[10] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
char letters[52] = { 'a', 'A', 'b', 'B', 'c', 'C', 'd', 'D', 'e', 'E', 'f', 'F', 'g', 'G', 'h', 'H', 'i', 'I',
'j', 'J', 'k', 'K', 'l', 'L', 'm', 'M', 'n', 'N', 'o', 'O', 'p', 'P', 'q', 'Q', 'r', 'R',
's', 'S', 't', 'T', 'u', 'U', 'v', 'V', 'w', 'W', 'x', 'X', 'y', 'Y', 'z', 'Z' };
char symbols[8] = {'}', '{', ';', ':', ',', ')', '(', '$' };
int index_sym[8] = {38, 39, 40, 41, 43, 45, 46, 47 };
#endif
|
Markdown
|
UTF-8
| 2,360 | 3 | 3 |
[] |
no_license
|
Python-Movie-Recommender
Author: Amir Ali
==============================================
Built using Python 2.7.13 |
with Python Anaconda 4.4.0 (64-bit) IDE
Required Python Modules = [pandas, numpy, scipy, sklearn, sqlite3, matplotlib ]
-------------------------------------------------------------------------------
The data used is provided by GroupLens Research Project at the University of Minnesota.
Downloaded data from
https://grouplens.org/datasets/movielens/
There are 3 data sets used:
* 100k - Consists of 100,000 ratings (1-5) from 943 users on 1682 movies
* 1m - Consists of 1,000,209 anonymous ratings of approximately 3,900 movies
made by 6,040 MovieLens users
* 20m - Consists of 20000263 ratings and 465564 tag applications across 27278 movies
**See the README.txt file in each data set folder for more details.
-------------------------------------------------------------------
There are 3 python recommenders:
* recommender.py - Uses the 100k data set. Baseline recommender using collaborative filtering.
Notes:
- There are a lot of design choices when making a recommendation system.
I have started the Coursera Specialization in Recommender Systems to get a better
understanding of the pros and cons each design choice.
-
Journal
Day1:
-import data into python. Started with the 100k dataset.
-learned pandas and numpy libraries. Read documentations.
-created a user item matrix using pandas and numpy libraries.
-implemented most popular movie recommender
Day 2:
-Implemented and tested pearson correlation measure method
-Implemented collabrotive filtering both user and item based
Day 3:
-Added metrics, evaluation and testing
-will add accuracy and error measures: MAE, RMSE and MSE
-Setting up the evaluation methods now is necessary for tuning and optimizing the recommender.
Day 4:
-Learned/Reviewed SQLite commands
-Created a database and read the data using python
-Added to test cases for the first recommender.
-Added proper python method comments.
-Tested item and user CF methods with a hand made small data set.
Day 5:
-Added SVD method. Normalized the matrix before factorization and calcualted the RMSE
-based on the test set.
-Transitioned to the 20 milllion ratings dataset.
-Will implement stochastic gradient descent to estimate the SVD for larger matrices.
|
Python
|
UTF-8
| 1,447 | 3.46875 | 3 |
[] |
no_license
|
#Multiple Columns
#-----------------------------
#%#Converting multiple columns to Categories
#multiple columns to categories
import pandas as pd
from pydataset import data
data =data('iris')
data.columns
data.describe()
data.dtypes
def rstr(df): return df.shape, df.apply(lambda x: [x.unique()])
print(rstr(data))
df.info(null_counts=True, verbose=True)
#which columns are categories
df=data.copy() #not link
df
df.describe()
df.dtypes
df['Species'] = df['Species'].astype('category')
df.dtypes
df.describe(include='category')
df.dtypes
df = df.astype({"Species":'category', "Sepal.Length":'int64'})
df.dtypes
df.describe()
df.describe(include=all)
include =['object', 'float', 'int', 'category']
# percentile list
perc =[.20, .40, .60, .80]
desc = df.describe(percentiles = perc, include = include)
desc
df.Species.value_counts() #numbers now
data.Species.value_counts()
df.Weight = df.Weight.astype('int64')
#run these together
for col_name in df.columns:
if(df[col_name].dtype == 'object'):
df[col_name]= df[col_name].astype('category')
df[col_name] = df[col_name].cat.codes
df.dtypes
help(df.describe())
df.describe(include='category')
help(df.describe)
#cols are categories
#run these together
for col_name in df.columns:
if(df[col_name].dtype == 'object'):
df[col_name]= df[col_name].astype('category')
df[col_name] = df[col_name].cat.codes
#plots
#https://realpython.com/python-matplotlib-guide/
|
Java
|
UTF-8
| 1,155 | 2.125 | 2 |
[] |
no_license
|
package com.artmark.avaxo.command;
import com.artmark.avaxo.command.model.CommandModel;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* @author Ushmodin N.
* @since 12.02.2016 10:18
*/
@Component
public class CommandService implements MessageListener {
private final static Logger log = LoggerFactory.getLogger(CommandService.class);
@Autowired
private StatusService statusService;
@Autowired
private ForwardService forwardService;
private ObjectMapper objectMapper = new ObjectMapper();
@Override
public void onMessage(Message message) {
try {
CommandModel command = objectMapper.readValue(message.getBody(), CommandModel.class);
if (command.getForward() != null) {
forwardService.forward(command.getForward());
}
if (command.getStatus() != null) {
statusService.sendStatus();
}
} catch (Exception e) {
log.error(null, e);
}
}
}
|
C
|
WINDOWS-1250
| 2,920 | 2.890625 | 3 |
[] |
no_license
|
#include "autreMenu.h"
// Globale variables
extern int midx, midy;
#define PI 3.14
void systemSolair()
{
int m=0,v=260,eh=300,mr=100,j=10,s=230,u=190,n=20;
float pi=3.1424,a,b,c,d,e,f,g,h,z;
while(1)
{
// Changer le diplacement dans l'orbit
a=(pi/180)*m++;
b=(pi/180)*v++;
c=(pi/180)*eh++;
d=(pi/180)*mr++;
e=(pi/180)*j++;
f=(pi/180)*s++;
g=(pi/180)*u++;
h=(pi/180)*n++;
n++;
cleardevice();
// Soleil
setcolor(YELLOW);
circle(midx,midy,20);
setcolor(RED);
//Mercure
circle(midx+60*sin(a),midy-35*cos(a),8); // plante
ellipse(midx,midy,0,360,60,35); // orbit
//Venus
circle(midx+100*sin(b),midy-60*cos(b),12);
ellipse(midx,midy,0,360,100,60);
//Terre
circle(midx+130*sin(c),midy-80*cos(c),10);
ellipse(midx,midy,0,360,130,80);
//Mars
circle(midx+170*sin(d),midy-100*cos(d),11);
ellipse(midx,midy,0,360,170,100);
//Jupiter
circle(midx+200*sin(e),midy-130*cos(e),14);
ellipse(midx,midy,0,360,200,130);
//Saturne
circle(midx+230*sin(f),midy-155*cos(f),12);
ellipse(midx,midy,0,360,230,155);
//Uranus
circle(midx+260*sin(g),midy-180*cos(g),9);
ellipse(midx,midy,0,360,260,180);
//Neptune
circle(midx+280*sin(h),midy-200*cos(h),9);
ellipse(midx,midy,0,360,280,200);
delay(50);
}
}
// https://fr.wikipedia.org/wiki/Flocon_de_Koch
void koch(int x1, int y1, int x2, int y2, int it)
{
//find angle
float angle = 60*PI/180;
//find p3 near p1
int x3 = (2*x1+x2)/3;
int y3 = (2*y1+y2)/3;
//find p4 near p2
int x4 = (x1+2*x2)/3;
int y4 = (y1+2*y2)/3;
//find joining pt
int dx=x4-x3;
int dy=y4-y3;
int x = x3 + dx*cos(angle)+dy*sin(angle);
int y = y3 - dx*sin(angle)+dy*cos(angle);
if(it > 0)
{
//recursion with it-1
koch(x1, y1, x3, y3, it-1); //13
koch(x3, y3, x, y, it-1); //30
koch(x, y, x4, y4, it-1); //04
koch(x4, y4, x2, y2, it-1); //42
}
else
{
line(x1, y1, x3, y3);
line(x3, y3, x, y);
line(x, y, x4, y4);
line(x4, y4, x2, y2);
}
}
void tracerFloconKoch()
{
int x1 = 100, y1 = 200, x2 = 400, y2 = 200, x3 = 250, y3 = 450, it;
cleardevice();
setcolor(RED);
it = 5;
koch(x1, y1, x2, y2, it); //12
koch(x2, y2, x3, y3, it); //23
koch(x3, y3, x1, y1, it); //31
return ;
}
int autre()
{
int choix;
do{
choix = autreMenu();
switch(choix)
{
case 1:
systemSolair();
break;
case 2 :
tracerFloconKoch();
break;
default :
printf("\n\t choix non reconu !!");
delay(1000);
break;
}
}while(choix != 3);
}
|
Rust
|
UTF-8
| 234 | 2.828125 | 3 |
[] |
no_license
|
pub fn is_prime(x: u64) -> bool{
if x > 2 && x % 2 == 0 {
return false
}
if x == 1 {
return false
}
for n in 2..x/2+1 {
if x % n == 0 {
return false
}
}
true
}
|
JavaScript
|
UTF-8
| 710 | 3.96875 | 4 |
[
"MIT"
] |
permissive
|
/**
* @param {string} a
* @param {string} b
* @return {number}
*/
const hammingDistance = (a, b) => {
const result = [];
if (a.length === b.length) {
let textA = " ";
let textB = " ";
for (let i = 0; i < a.length; i++) {
textA += a[i].charCodeAt(0).toString(2) + " ";
}
for (let i = 0; i < b.length; i++) {
textB += b[i].charCodeAt(0).toString(2) + " ";
}
for (let i = 0; i < a.length; i++) {
result.push(a.charAt(i) === b.charAt(i))
}
const diference = result.filter((item) => {
return item === false;
})
return diference.length;
} else {
throw "error"
}
}
hammingDistance('10', '10');
module.exports = hammingDistance;
|
Python
|
UTF-8
| 4,270 | 2.734375 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
"""A preprocessor that extracts all of the outputs from the
notebook file. The extracted outputs are returned in the 'resources' dictionary.
"""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
import re
from binascii import a2b_base64
import sys
import os
from mimetypes import guess_extension
from traitlets import Unicode, Set
from .base import Preprocessor
class AttachmentInlinerPreprocessor(Preprocessor):
"""
Replace all attachment references with inline base64 encoded data.
"""
def preprocess_cell(self, cell, resources, cell_index):
"""
Process only markdown cells, looking for image references to cell
attachments. Replace each with inline base64 image.
"""
if cell.cell_type != "markdown":
return cell, resources
regexp = re.compile(r'!\[[^\]]*\]\(attachment:([^)]*)\)')
for m in re.finditer(regexp, cell.source):
name = m.group(1)
attachment = cell.get('attachments')[name]
mimetype = list(attachment)[0]
cell.source = cell.source.replace(
m.group(0),
"<img src='data:%s;base64,%s' />" % (mimetype, attachment[mimetype])
)
return cell, resources
class ExtractAttachmentPreprocessor(Preprocessor):
"""
Extracts all of the attachments from the notebook file. The extracted
attachments are returned in the 'resources' dictionary. The markdown is
updated to refer to them.
"""
output_filename_template = Unicode(
"{unique_key}_{cell_index}_{index}{extension}"
).tag(config=True)
extract_output_types = Set(
{'image/png', 'image/jpeg', 'image/svg+xml', 'application/pdf'}
).tag(config=True)
def preprocess_cell(self, cell, resources, cell_index):
if cell.cell_type != "markdown":
return cell, resources
#Get the unique key from the resource dict if it exists. If it does not
#exist, use 'output' as the default. Also, get files directory if it
#has been specified
unique_key = resources.get('unique_key', 'attachment')
output_files_dir = resources.get('output_files_dir', None)
#Make sure outputs key exists
if not isinstance(resources['outputs'], dict):
resources['outputs'] = {}
#Loop through all of the outputs in the cell
for index, attachment in enumerate(cell.get('attachments', [])):
att = cell['attachments'][attachment]
#Get the output in data formats that the template needs extracted
for mime_type in self.extract_output_types:
if mime_type in att:
data = att[mime_type]
#Binary files are base64-encoded, SVG is already XML
if mime_type in {'image/png', 'image/jpeg', 'application/pdf'}:
# data is b64-encoded as text (str, unicode),
# we want the original bytes
data = a2b_base64(data)
elif sys.platform == 'win32':
data = data.replace('\n', '\r\n').encode("UTF-8")
else:
data = data.encode("UTF-8")
ext = guess_extension(mime_type)
if ext is None:
ext = '.' + mime_type.rsplit('/')[-1]
filename = self.output_filename_template.format(
unique_key=unique_key,
cell_index=cell_index,
index=index,
extension=ext)
if output_files_dir is not None:
filename = os.path.join(output_files_dir, filename)
resources['outputs'][filename] = data
original_ref = "".format(attachment, attachment)
new_ref = "".format(attachment, filename)
cell.source = cell.source.replace(original_ref, new_ref)
return cell, resources
|
Java
|
UTF-8
| 5,515 | 2.109375 | 2 |
[] |
no_license
|
package com.movision.controller.boss.robot;
import com.movision.common.Response;
import com.movision.facade.robot.RobotFacade;
import com.movision.mybatis.user.entity.User;
import com.movision.utils.pagination.model.Paging;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* 机器人自身的管理
*
* @Author zhuangyuhao
* @Date 2017/9/18 10:48
*/
@RestController
@RequestMapping("boss/robot/robot_self")
public class RobotSelfController {
@Autowired
private RobotFacade robotFacade;
@ApiOperation(value = "创建机器人", notes = "创建机器人", response = Response.class)
@RequestMapping(value = "/create_robot", method = RequestMethod.POST)
public Response createRobot(@ApiParam(value = "需要创建的机器人数量") @RequestParam Integer num) throws IOException {
Response response = new Response();
robotFacade.batchAddRobotUser(num);
response.setMessage("操作成功");
return response;
}
@ApiOperation(value = "用于查询机器人列表接口", notes = "用于查询机器人列表接口", response = Response.class)
@RequestMapping(value = "/query_robot_list", method = RequestMethod.POST)
public Response QueryRobotByList(@ApiParam(value = "机器人名称") @RequestParam(required = false) String name,
@ApiParam(value = "当前页") @RequestParam(defaultValue = "1") String pageNo,
@ApiParam(value = "每页几条") @RequestParam(defaultValue = "10") String pageSize) {
Response response = new Response();
List<User> userVoList = new ArrayList<User>();
Paging<User> pag = new Paging<User>(Integer.valueOf(pageNo), Integer.valueOf(pageSize));
//查询机器人列表,用于列表查询
userVoList = robotFacade.QueryRobotByList(name, pag);
pag.result(userVoList);
response.setData(pag);
response.setMessage("查询成功");
return response;
}
@ApiOperation(value = "用于查询机器人详情接口", notes = "用于查询机器人详情接口", response = Response.class)
@RequestMapping(value = "/query_robot_detail", method = RequestMethod.POST)
public Response queryRobotById(@ApiParam(value = "机器人id") @RequestParam String id) {
Response response = new Response();
User user = robotFacade.queryRobotById(id);
response.setMessage("查询成功");
response.setData(user);
return response;
}
@ApiOperation(value = "更新机器人", notes = "更新机器人", response = Response.class)
@RequestMapping(value = "/update_robot", method = RequestMethod.POST)
public Response updateRoboltById(@ApiParam(value = "id") @RequestParam(required = false) String id,
@ApiParam(value = "邮箱") @RequestParam(required = false) String email,
@ApiParam(value = "nickname") @RequestParam(required = false) String nickname,
@ApiParam(value = "手机号") @RequestParam(required = false) String phone,
@ApiParam(value = "头像") @RequestParam(required = false) String photo,
@ApiParam(value = "性别") @RequestParam(required = false) String sex) {
Response response = new Response();
robotFacade.updateRoboltById(id, email, nickname, phone, photo, sex);
response.setMessage("操作成功");
response.setData(1);
return response;
}
@ApiOperation(value = "批量替换机器人的头像", notes = "批量替换机器人的头像", response = Response.class)
@RequestMapping(value = "batch_change_robot_photo", method = RequestMethod.POST)
public Response batchChangeRobotPhoto(@ApiParam(value = "机器人id,逗号分隔") @RequestParam String userids) {
Response response = new Response();
robotFacade.batchChangeRobotPhoto(userids);
response.setMessage("操作成功");
return response;
}
@ApiOperation(value = "批量替换机器人的昵称", notes = "批量替换机器人的昵称", response = Response.class)
@RequestMapping(value = "batch_change_robot_nickname", method = RequestMethod.POST)
public Response batchChangeRobotNickname(@ApiParam(value = "机器人id,逗号分隔") @RequestParam String userids) {
Response response = new Response();
robotFacade.batchChangeRobotNickname(userids);
response.setMessage("操作成功");
return response;
}
@ApiOperation(value = "替换全部机器人的昵称、头像、签名", notes = "批量替换机器人的昵称、头像、签名", response = Response.class)
@RequestMapping(value = "all_change_robot_info", method = RequestMethod.POST)
public Response allChangeRobotNickname() {
Response response = new Response();
robotFacade.allChangeRobotInfo();
response.setMessage("操作成功");
return response;
}
}
|
C#
|
UTF-8
| 7,174 | 2.515625 | 3 |
[] |
no_license
|
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
namespace AnalogClockApplication
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private AnalogClockControl.AnalogClock analogClock1;
private AnalogClockControl.AnalogClock analogClock2;
private AnalogClockControl.AnalogClock analogClock3;
private System.Windows.Forms.Button cmdDecreaseSize;
private System.Windows.Forms.Button cmdIncreaseSize;
private System.Windows.Forms.Label label1;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
this.analogClock1 = new AnalogClockControl.AnalogClock();
this.analogClock2 = new AnalogClockControl.AnalogClock();
this.analogClock3 = new AnalogClockControl.AnalogClock();
this.cmdDecreaseSize = new System.Windows.Forms.Button();
this.cmdIncreaseSize = new System.Windows.Forms.Button();
this.label1 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// analogClock1
//
this.analogClock1.Draw1MinuteTicks = false;
this.analogClock1.Draw5MinuteTicks = false;
this.analogClock1.HourHandColor = System.Drawing.Color.MediumSlateBlue;
this.analogClock1.Location = new System.Drawing.Point(32, 32);
this.analogClock1.MinuteHandColor = System.Drawing.Color.MediumOrchid;
this.analogClock1.Name = "analogClock1";
this.analogClock1.SecondHandColor = System.Drawing.Color.White;
this.analogClock1.Size = new System.Drawing.Size(150, 150);
this.analogClock1.TabIndex = 0;
this.analogClock1.TicksColor = System.Drawing.Color.Black;
//
// analogClock2
//
this.analogClock2.Draw1MinuteTicks = false;
this.analogClock2.Draw5MinuteTicks = true;
this.analogClock2.HourHandColor = System.Drawing.Color.HotPink;
this.analogClock2.Location = new System.Drawing.Point(320, 24);
this.analogClock2.MinuteHandColor = System.Drawing.Color.MediumAquamarine;
this.analogClock2.Name = "analogClock2";
this.analogClock2.SecondHandColor = System.Drawing.Color.Yellow;
this.analogClock2.Size = new System.Drawing.Size(150, 150);
this.analogClock2.TabIndex = 1;
this.analogClock2.TicksColor = System.Drawing.Color.Blue;
//
// analogClock3
//
this.analogClock3.Draw1MinuteTicks = true;
this.analogClock3.Draw5MinuteTicks = true;
this.analogClock3.HourHandColor = System.Drawing.Color.DarkMagenta;
this.analogClock3.Location = new System.Drawing.Point(64, 168);
this.analogClock3.MinuteHandColor = System.Drawing.Color.Green;
this.analogClock3.Name = "analogClock3";
this.analogClock3.SecondHandColor = System.Drawing.Color.Red;
this.analogClock3.Size = new System.Drawing.Size(352, 352);
this.analogClock3.TabIndex = 2;
this.analogClock3.TicksColor = System.Drawing.Color.Black;
//
// cmdDecreaseSize
//
this.cmdDecreaseSize.Image = ((System.Drawing.Image)(resources.GetObject("cmdDecreaseSize.Image")));
this.cmdDecreaseSize.Location = new System.Drawing.Point(248, 80);
this.cmdDecreaseSize.Name = "cmdDecreaseSize";
this.cmdDecreaseSize.Size = new System.Drawing.Size(24, 32);
this.cmdDecreaseSize.TabIndex = 3;
this.cmdDecreaseSize.Click += new System.EventHandler(this.cmdDecreaseSize_Click);
//
// cmdIncreaseSize
//
this.cmdIncreaseSize.Image = ((System.Drawing.Image)(resources.GetObject("cmdIncreaseSize.Image")));
this.cmdIncreaseSize.Location = new System.Drawing.Point(216, 80);
this.cmdIncreaseSize.Name = "cmdIncreaseSize";
this.cmdIncreaseSize.Size = new System.Drawing.Size(24, 32);
this.cmdIncreaseSize.TabIndex = 4;
this.cmdIncreaseSize.Click += new System.EventHandler(this.cmdIncreaseSize_Click);
//
// label1
//
this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label1.Location = new System.Drawing.Point(224, 56);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(32, 16);
this.label1.TabIndex = 5;
this.label1.Text = "Size";
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(520, 517);
this.Controls.Add(this.label1);
this.Controls.Add(this.cmdIncreaseSize);
this.Controls.Add(this.cmdDecreaseSize);
this.Controls.Add(this.analogClock1);
this.Controls.Add(this.analogClock2);
this.Controls.Add(this.analogClock3);
this.Name = "Form1";
this.Text = "Analog Clock Control Test Application";
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
private void button1_Click(object sender, System.EventArgs e)
{
this.analogClock1.Stop();
}
private void button2_Click(object sender, System.EventArgs e)
{
this.analogClock1.Start();
}
private void cmdDecreaseSize_Click(object sender, System.EventArgs e)
{
this.analogClock1.Height-=20;
this.analogClock2.Height-=20;
}
private void cmdIncreaseSize_Click(object sender, System.EventArgs e)
{
this.analogClock1.Height+=20;
this.analogClock2.Height+=20;
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
|
Java
|
UTF-8
| 607 | 3.296875 | 3 |
[] |
no_license
|
package com.trylabs;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.println("Введите количество минут разговора и день недели(1-7)");
Scanner scanner = new Scanner(System.in);
int n=scanner.nextInt();
int day=scanner.nextInt();
if (day>5){
System.out.println("сумма за "+n + " минут разговора :"+((n*1.2)/100)*80);
}
else System.out.println("Cумма за "+ n +"минут разговора:"+ (n*1.2));
}
}
|
Markdown
|
UTF-8
| 4,791 | 2.9375 | 3 |
[] |
no_license
|
---
author: whidy
comments: true
date: 2013-10-17 15:12:00+00:00
layout: post
link: http://www.whidy.net/chrome-codecademy-font-size-10px.html
slug: chrome-codecademy-font-size-10px
title: Chrome无法正确显示小于12px的问题思考解决
wordpress_id: 1784
categories:
- CSS
- HTML
- IT技术
- 技术分享
tags:
- 技术
- 网站
---
很多东西都是有时效性的啦...正巧我又遇到一个设计做的10px汉字,来翻以前写的东西,实际上发现这个还是有作用的,给需要设置10px的标签加上这个就ok啦,至少chrome 39是OK的啦~
```css
-webkit-text-size-adjust:none;font-size:10px;
```
ps: 2015年1月23日
* * *
想必很多计算机自学者都在CodeCademy学习过,作为入门学习的免费网站,的确做得不错,这几天闲来无事本来是想在上面学点别的,看到有HTML教程顺便也想快速通过,却发现在控制字体大小卡壳了.一般来说我使用chrome浏览器,其中有一个小的CodeCademy的练习,要求设定字体大小10px,chrome始终无法通过,不过似乎之前遇到过这个问题,所以思考了片刻解决了.首先看图,通过不同浏览器运行此练习效果:
[caption id="attachment_1785" align="aligncenter" width="400"][](http://www.whidy.net/wp-content/uploads/2013/10/CodeCademy.jpg) chrome和ie下的区别,点击查看大图[/caption]
<!-- more -->
那么为什么chrome不通过,而IE是可以通过呢,当然还有其他浏览器我没有进行测试,因为作为这个问题,不必对多个浏览器进行检测.
如果没有经验的人,肯定绞尽脑汁都想不出来,或许能想到沾点边的原因,比如说是不是chrome的默认字体跟IE是不一样的呢,chrome默认字体恰好不支持10px大小的字体导致呢?那么我们可以尝试做个测试,在p标签的样式内添加一句**font-family:Arial;**我想这样应该没问题了吧,提交发现仍然无法通过.
其实,告诉大家,这是由于chrome浏览器本身问题导致.那么如何解决这个问题呢?相信大家一定会搜百度,其实我也是这样做的,但是似乎搜出来的结果都是说这样一个方法.添加一条样式,只有chrome才能识别的:
html,body {-webkit-text-size-adjust:none;}
似乎我用了这个不管用,也不知道是几年前的方法了.那怎么办还是找google靠谱些吧.于是找到这篇文章[Font-size <12px doesn't have effect in Google Chrome](http://stackoverflow.com/questions/2295095/font-size-12px-doesnt-have-effect-in-google-chrome)有个人的回复大家可以自己看看,我尝试了一下,还是有一些问题.具体是修改一个选项文件内容如下:
```javascripton
"webkit": {
"webprefs": {
"default_fixed_font_size": 11,
"default_font_size": 12,
"fixed_font_family": "Bitstream Vera Sans Mono",
"minimum_font_size": 12,
"minimum_logical_font_size": 12,
"sansserif_font_family": "Times New Roman",
"serif_font_family": "Arial",
"standard_font_is_serif": false,
"text_areas_are_resizable": true
}
}
```
但是似乎这个是适应国外英文网站的,我经过无数次的调试测验,终于可以正常使用了,在不影响中文文字大小的情况下,最小的设置为8px,我想应该没有什么网站会设置更小的字体了吧.那么我是这样改得:
```javascripton
"webkit": {
"webprefs": {
"uses_universal_detector": true,
"minimum_font_size": 8,
"standard_font_is_serif": false,
"text_areas_are_resizable": true
}
}
```
大家可以试试,目前来说是可以在chrome 30的版本下正常使用的, 好像说了半天没有说是修改那个文件,其实就是chrome安装目录里,以我的电脑(WIN 8.1)举例:
**C:\Users\Whidy\AppData\Local\Google\Chrome\User Data\Default\Preferences**
修改**Preferences**文件,末尾处即可.(其他系统自行查找此文件咯~)
虽然这个问题解决了,但是实际上还有个IE下却有些不同,如图
[caption id="attachment_1793" align="aligncenter" width="400"][](http://www.whidy.net/wp-content/uploads/2013/10/fontsize.jpg) 不同浏览器字体显示效果[/caption]
IE的确还是很奇怪...那么这个问题下次来研究下,不早了,要睡觉了...(哈哈,逗大家玩的,其实我缩放了百分比的...)
相关阅读: **[默认css字体大小单位及样式研究](http://www.whidy.net/wp-admin/post.php?post=748&action=edit)**
|
C++
|
UTF-8
| 1,196 | 3.296875 | 3 |
[] |
no_license
|
#include <iostream>
#include <vector>
#include <string>
using namespace std;
bool isValid(string s)
{
if(s.empty() || s.size() > 3 || (s.size() > 1 && s[0] == '0'))
return false;
int res = atoi(s.c_str());
return (res >= 0 && res <= 255);
}
void restore(string s,int k,string out,vector<string> &res)
{
if(k == 0)
{
if(s.empty())
res.push_back(out);
}
else
{
for(int i = 1; i <= 3; i++)
{
if(s.size() >= i && isValid(s.substr(0,i)))
{
if(k == 1)
restore(s.substr(i),k-1,out+s.substr(0,i),res);
else
restore(s.substr(i),k-1,out+s.substr(0,i)+".",res);
}
}
}
}
vector<string> restoreIpAddresses(string s)
{
vector<string> res;
restore(s,4,"",res);
return res;
}
int main()
{
string s;
cin >> s;
vector<string> result = restoreIpAddresses(s);
for(int i = 0; i < result.size(); i++)
{
for(int j = 0; j < result[i].size(); j++)
{
cout << result[i][j];
}
if(i < result.size()-1)
cout << ", ";
}
return 0;
}
|
Java
|
UTF-8
| 3,615 | 2.203125 | 2 |
[] |
no_license
|
package Controller;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.persistence.EntityManager;
import Comparator.Comparador;
import Entity.CondicionOrdenamiento;
import Entity.Empresa;
import Entity.Metodologia;
import Entity.Periodo;
import Modelo.DAOGlobalMYSQL;
import Modelo.DAOjson;
import Modelo.DAOmetodologiaJson;
import Modelo.RepositorioDeMetodologia;
import db.EntityManagerHelper;
import spark.ModelAndView;
import spark.Request;
import spark.Response;
public class MetodologiaListaEmpresaController {
private Map<String, Object> model=new HashMap<>();
public ModelAndView inicioMetodologiaListaEmpresas(Request req, Response res){
String nombre_usuario = req.session().attribute("usuario");
DAOGlobalMYSQL<Periodo> modelPeriodo = new DAOGlobalMYSQL<Periodo>(Periodo.class);
DAOGlobalMYSQL<Empresa> modelEmpresa = new DAOGlobalMYSQL<Empresa>(Empresa.class);
DAOGlobalMYSQL<Metodologia> modelMetodologia = new DAOGlobalMYSQL<Metodologia>(Metodologia.class);
RepositorioDeMetodologia repo = new RepositorioDeMetodologia(modelMetodologia);
List<Metodologia> metodologiaUsuario = repo.getLista().stream().filter(m -> m.getUsuario().getNombre().equals(nombre_usuario)).collect(Collectors.toList());
model.put("empresas", modelEmpresa.getAllEmp());
model.put("periodosDesde", modelPeriodo.getAllPeriodos());
model.put("periodosHasta", modelPeriodo.getAllPeriodos());
model.put("metodologia", metodologiaUsuario);
return new ModelAndView(model, "metodologiaListaEmpresas.hbs");
}
public ModelAndView consultaMetodologiaListaEmpresas(Request req, Response res){
String nombre_usuario = req.session().attribute("usuario");
String periodoDesde = req.queryParams("periodoDesde");
String periodoHasta = req.queryParams("periodoHasta");
String condicionOrdenamiento = req.queryParams("metodologia");
//aca va arrays de strings
String[] empresasPrueba = req.queryParamsValues("empresas");
List<String> empresasSeleccionadas= new ArrayList<>();
//empresasSeleccionadas.add("Cloud");empresasSeleccionadas.add("Ford");empresasSeleccionadas.add("Google");
for(int i = 0;i<empresasPrueba.length;i++){
empresasSeleccionadas.add(empresasPrueba[i]);
}
DAOGlobalMYSQL<Empresa> dao = new DAOGlobalMYSQL<Empresa>(Empresa.class);
List<Empresa> lista = dao.getAllEmp();
//**Agregar empresas mediante stringsss****
List<Empresa> empresas = new ArrayList<>();
for(Empresa e : lista){
if(empresasSeleccionadas.stream().anyMatch((String nombre)-> nombre.equals(e.getNombre()))){
empresas.add(e);
}
}
CondicionOrdenamiento condicion = this.findCondicion(nombre_usuario, condicionOrdenamiento);
condicion.setListaEmpresas(empresas);
condicion.darValorAEmpresas(periodoDesde,periodoHasta);
condicion.ordenar();
model.put("empresas", empresas);
return new ModelAndView(model, "consultaMetodologiasListaEmpresas.hbs");
}
public CondicionOrdenamiento findCondicion(String usuario, String condicion)
{
EntityManager em = EntityManagerHelper.entityManager();
return (CondicionOrdenamiento) em.createNativeQuery("SELECT c.id, c.comparador, c.indicadorCuenta,c.metodologia_id FROM inversiones.condicionordenamiento c "
+ "join inversiones.metodologia m on (m.id=c.metodologia_id) "
+ "join inversiones.usuario u "
+ "where m.nombre = '"+condicion+"' and u.nombre ='"+usuario+"'"
,CondicionOrdenamiento.class).getSingleResult();
}
}
|
C++
|
UTF-8
| 1,276 | 3.640625 | 4 |
[] |
no_license
|
#include <iostream>
#include <chrono>
#include <vector>
#include <memory>
using namespace std;
using namespace chrono;
// 7. Radix Sort
// Time Complexity: theta(n)
template <typename T>
void RadixSort(T* A, int n, int k)
{
vector<T> vec_tmp[10];
for (int i = 0, mod = 10, div = 1, tmp_idx = 0; i <= k - 1; ++i, mod *= 10, div *= 10, tmp_idx = 0) {
for (int j = 0; j <= n - 1; ++j)
vec_tmp[A[j] % mod / div].push_back(A[j]);
for (int m = 0; m <= 9; ++m) {
for (auto e : vec_tmp[m]) {
A[tmp_idx++] = e;
}
vec_tmp[m].clear();
}
}
}
const size_t ARRAY_SIZE = 100'000'000;
const size_t RADIX_SIZE = 5;
int main()
{
shared_ptr<int> sp_intArray(new int[ARRAY_SIZE], [](int* ptr) { delete[] ptr; });
for (int i = 0; i <= ARRAY_SIZE - 1; ++i)
sp_intArray.get()[i] = rand() % RAND_MAX;
cout << "7. Radix Sort" << endl;
cout << "Start!" << endl;
auto start = high_resolution_clock::now();
RadixSort(sp_intArray.get(), ARRAY_SIZE, RADIX_SIZE);
cout << "Finish!" << endl;
auto finish = high_resolution_clock::now();
auto duration = finish - start;
cout << "Elapsed Time: " << duration_cast<milliseconds>(duration).count() << "(ms)" << endl;
for (int i = 0; i <= ARRAY_SIZE - 1; ++i)
cout << sp_intArray.get()[i] << ", ";
return 0;
}
|
Go
|
UTF-8
| 605 | 2.921875 | 3 |
[] |
no_license
|
package question_671_680
import (
"testing"
)
func Test_validPalindrome(t *testing.T) {
tests := []struct {
s string
want bool
}{
{"ab", true},
{"a", true},
{"aba", true},
{"abca", true},
{"bddb", true},
{"abbca", true},
{"abbdca", false},
{"aguokepatgbnvfqmgmlcupuufxoohdfpgjdmysgvhmvffcnqxjjxqncffvmhvgsymdjgpfdhooxfuupuculmgmqfvnbgtapekouga", true},
{"acxcybycxcxa", true},
}
for _, tt := range tests {
t.Run("test", func(t *testing.T) {
if got := validPalindrome(tt.s); got != tt.want {
t.Errorf("validPalindrome() = %v, want %v", got, tt.want)
}
})
}
}
|
Java
|
UTF-8
| 12,796 | 2.046875 | 2 |
[] |
no_license
|
// Code generated by Wire protocol buffer compiler, do not edit.
// Source file: AppInterface.proto at 227:1
package com.yijianyi.protocol;
import com.squareup.wire.FieldEncoding;
import com.squareup.wire.Message;
import com.squareup.wire.ProtoAdapter;
import com.squareup.wire.ProtoReader;
import com.squareup.wire.ProtoWriter;
import com.squareup.wire.WireField;
import com.squareup.wire.internal.Internal;
import java.io.IOException;
import java.lang.Long;
import java.lang.Object;
import java.lang.Override;
import java.lang.String;
import java.lang.StringBuilder;
import java.util.List;
import okio.ByteString;
public final class GetPriceRsp extends Message<GetPriceRsp, GetPriceRsp.Builder> {
public static final ProtoAdapter<GetPriceRsp> ADAPTER = new ProtoAdapter_GetPriceRsp();
private static final long serialVersionUID = 0L;
public static final String DEFAULT_PHONE = "";
public static final String DEFAULT_PREPAYAMOUNT = "";
public static final Long DEFAULT_ENTRANCECARDPRICE = 0L;
public static final String DEFAULT_ENTRANCECARDPRICESTR = "";
public static final String DEFAULT_TOTALPRICE = "";
/**
* 一对多套餐列表
*/
@WireField(
tag = 1,
adapter = "com.yijianyi.protocol.Price#ADAPTER",
label = WireField.Label.REPEATED
)
public final List<Price> pList12N;
/**
* 一对一套餐列表
*/
@WireField(
tag = 2,
adapter = "com.yijianyi.protocol.Price#ADAPTER",
label = WireField.Label.REPEATED
)
public final List<Price> pList121;
/**
* 用户的手机号码
*/
@WireField(
tag = 3,
adapter = "com.squareup.wire.ProtoAdapter#STRING"
)
public final String phone;
/**
* 下面两个字段加起来的数值 就是app端页面展示的预付款
* 预付金
*/
@WireField(
tag = 4,
adapter = "com.squareup.wire.ProtoAdapter#STRING"
)
public final String prepayAmount;
/**
* 门禁卡押金
*/
@WireField(
tag = 5,
adapter = "com.squareup.wire.ProtoAdapter#UINT64"
)
public final Long entranceCardPrice;
/**
* 居家套餐列表 每个套餐都有不同的预付金 在CompanyPriceVO中
*/
@WireField(
tag = 6,
adapter = "com.yijianyi.protocol.CompanyPriceVO#ADAPTER",
label = WireField.Label.REPEATED
)
public final List<CompanyPriceVO> familyPriceVOList;
/**
* 门禁卡押金(转化后)
*/
@WireField(
tag = 7,
adapter = "com.squareup.wire.ProtoAdapter#STRING"
)
public final String entranceCardPriceStr;
/**
* 机构预付金和门禁卡押金的和
*/
@WireField(
tag = 8,
adapter = "com.squareup.wire.ProtoAdapter#STRING"
)
public final String totalPrice;
public GetPriceRsp(List<Price> pList12N, List<Price> pList121, String phone, String prepayAmount, Long entranceCardPrice, List<CompanyPriceVO> familyPriceVOList, String entranceCardPriceStr, String totalPrice) {
this(pList12N, pList121, phone, prepayAmount, entranceCardPrice, familyPriceVOList, entranceCardPriceStr, totalPrice, ByteString.EMPTY);
}
public GetPriceRsp(List<Price> pList12N, List<Price> pList121, String phone, String prepayAmount, Long entranceCardPrice, List<CompanyPriceVO> familyPriceVOList, String entranceCardPriceStr, String totalPrice, ByteString unknownFields) {
super(ADAPTER, unknownFields);
this.pList12N = Internal.immutableCopyOf("pList12N", pList12N);
this.pList121 = Internal.immutableCopyOf("pList121", pList121);
this.phone = phone;
this.prepayAmount = prepayAmount;
this.entranceCardPrice = entranceCardPrice;
this.familyPriceVOList = Internal.immutableCopyOf("familyPriceVOList", familyPriceVOList);
this.entranceCardPriceStr = entranceCardPriceStr;
this.totalPrice = totalPrice;
}
@Override
public Builder newBuilder() {
Builder builder = new Builder();
builder.pList12N = Internal.copyOf("pList12N", pList12N);
builder.pList121 = Internal.copyOf("pList121", pList121);
builder.phone = phone;
builder.prepayAmount = prepayAmount;
builder.entranceCardPrice = entranceCardPrice;
builder.familyPriceVOList = Internal.copyOf("familyPriceVOList", familyPriceVOList);
builder.entranceCardPriceStr = entranceCardPriceStr;
builder.totalPrice = totalPrice;
builder.addUnknownFields(unknownFields());
return builder;
}
@Override
public boolean equals(Object other) {
if (other == this) return true;
if (!(other instanceof GetPriceRsp)) return false;
GetPriceRsp o = (GetPriceRsp) other;
return unknownFields().equals(o.unknownFields())
&& pList12N.equals(o.pList12N)
&& pList121.equals(o.pList121)
&& Internal.equals(phone, o.phone)
&& Internal.equals(prepayAmount, o.prepayAmount)
&& Internal.equals(entranceCardPrice, o.entranceCardPrice)
&& familyPriceVOList.equals(o.familyPriceVOList)
&& Internal.equals(entranceCardPriceStr, o.entranceCardPriceStr)
&& Internal.equals(totalPrice, o.totalPrice);
}
@Override
public int hashCode() {
int result = super.hashCode;
if (result == 0) {
result = unknownFields().hashCode();
result = result * 37 + pList12N.hashCode();
result = result * 37 + pList121.hashCode();
result = result * 37 + (phone != null ? phone.hashCode() : 0);
result = result * 37 + (prepayAmount != null ? prepayAmount.hashCode() : 0);
result = result * 37 + (entranceCardPrice != null ? entranceCardPrice.hashCode() : 0);
result = result * 37 + familyPriceVOList.hashCode();
result = result * 37 + (entranceCardPriceStr != null ? entranceCardPriceStr.hashCode() : 0);
result = result * 37 + (totalPrice != null ? totalPrice.hashCode() : 0);
super.hashCode = result;
}
return result;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
if (!pList12N.isEmpty()) builder.append(", pList12N=").append(pList12N);
if (!pList121.isEmpty()) builder.append(", pList121=").append(pList121);
if (phone != null) builder.append(", phone=").append(phone);
if (prepayAmount != null) builder.append(", prepayAmount=").append(prepayAmount);
if (entranceCardPrice != null) builder.append(", entranceCardPrice=").append(entranceCardPrice);
if (!familyPriceVOList.isEmpty()) builder.append(", familyPriceVOList=").append(familyPriceVOList);
if (entranceCardPriceStr != null) builder.append(", entranceCardPriceStr=").append(entranceCardPriceStr);
if (totalPrice != null) builder.append(", totalPrice=").append(totalPrice);
return builder.replace(0, 2, "GetPriceRsp{").append('}').toString();
}
public static final class Builder extends Message.Builder<GetPriceRsp, Builder> {
public List<Price> pList12N;
public List<Price> pList121;
public String phone;
public String prepayAmount;
public Long entranceCardPrice;
public List<CompanyPriceVO> familyPriceVOList;
public String entranceCardPriceStr;
public String totalPrice;
public Builder() {
pList12N = Internal.newMutableList();
pList121 = Internal.newMutableList();
familyPriceVOList = Internal.newMutableList();
}
/**
* 一对多套餐列表
*/
public Builder pList12N(List<Price> pList12N) {
Internal.checkElementsNotNull(pList12N);
this.pList12N = pList12N;
return this;
}
/**
* 一对一套餐列表
*/
public Builder pList121(List<Price> pList121) {
Internal.checkElementsNotNull(pList121);
this.pList121 = pList121;
return this;
}
/**
* 用户的手机号码
*/
public Builder phone(String phone) {
this.phone = phone;
return this;
}
/**
* 下面两个字段加起来的数值 就是app端页面展示的预付款
* 预付金
*/
public Builder prepayAmount(String prepayAmount) {
this.prepayAmount = prepayAmount;
return this;
}
/**
* 门禁卡押金
*/
public Builder entranceCardPrice(Long entranceCardPrice) {
this.entranceCardPrice = entranceCardPrice;
return this;
}
/**
* 居家套餐列表 每个套餐都有不同的预付金 在CompanyPriceVO中
*/
public Builder familyPriceVOList(List<CompanyPriceVO> familyPriceVOList) {
Internal.checkElementsNotNull(familyPriceVOList);
this.familyPriceVOList = familyPriceVOList;
return this;
}
/**
* 门禁卡押金(转化后)
*/
public Builder entranceCardPriceStr(String entranceCardPriceStr) {
this.entranceCardPriceStr = entranceCardPriceStr;
return this;
}
/**
* 机构预付金和门禁卡押金的和
*/
public Builder totalPrice(String totalPrice) {
this.totalPrice = totalPrice;
return this;
}
@Override
public GetPriceRsp build() {
return new GetPriceRsp(pList12N, pList121, phone, prepayAmount, entranceCardPrice, familyPriceVOList, entranceCardPriceStr, totalPrice, super.buildUnknownFields());
}
}
private static final class ProtoAdapter_GetPriceRsp extends ProtoAdapter<GetPriceRsp> {
ProtoAdapter_GetPriceRsp() {
super(FieldEncoding.LENGTH_DELIMITED, GetPriceRsp.class);
}
@Override
public int encodedSize(GetPriceRsp value) {
return Price.ADAPTER.asRepeated().encodedSizeWithTag(1, value.pList12N)
+ Price.ADAPTER.asRepeated().encodedSizeWithTag(2, value.pList121)
+ (value.phone != null ? ProtoAdapter.STRING.encodedSizeWithTag(3, value.phone) : 0)
+ (value.prepayAmount != null ? ProtoAdapter.STRING.encodedSizeWithTag(4, value.prepayAmount) : 0)
+ (value.entranceCardPrice != null ? ProtoAdapter.UINT64.encodedSizeWithTag(5, value.entranceCardPrice) : 0)
+ CompanyPriceVO.ADAPTER.asRepeated().encodedSizeWithTag(6, value.familyPriceVOList)
+ (value.entranceCardPriceStr != null ? ProtoAdapter.STRING.encodedSizeWithTag(7, value.entranceCardPriceStr) : 0)
+ (value.totalPrice != null ? ProtoAdapter.STRING.encodedSizeWithTag(8, value.totalPrice) : 0)
+ value.unknownFields().size();
}
@Override
public void encode(ProtoWriter writer, GetPriceRsp value) throws IOException {
Price.ADAPTER.asRepeated().encodeWithTag(writer, 1, value.pList12N);
Price.ADAPTER.asRepeated().encodeWithTag(writer, 2, value.pList121);
if (value.phone != null) ProtoAdapter.STRING.encodeWithTag(writer, 3, value.phone);
if (value.prepayAmount != null) ProtoAdapter.STRING.encodeWithTag(writer, 4, value.prepayAmount);
if (value.entranceCardPrice != null) ProtoAdapter.UINT64.encodeWithTag(writer, 5, value.entranceCardPrice);
CompanyPriceVO.ADAPTER.asRepeated().encodeWithTag(writer, 6, value.familyPriceVOList);
if (value.entranceCardPriceStr != null) ProtoAdapter.STRING.encodeWithTag(writer, 7, value.entranceCardPriceStr);
if (value.totalPrice != null) ProtoAdapter.STRING.encodeWithTag(writer, 8, value.totalPrice);
writer.writeBytes(value.unknownFields());
}
@Override
public GetPriceRsp decode(ProtoReader reader) throws IOException {
Builder builder = new Builder();
long token = reader.beginMessage();
for (int tag; (tag = reader.nextTag()) != -1;) {
switch (tag) {
case 1: builder.pList12N.add(Price.ADAPTER.decode(reader)); break;
case 2: builder.pList121.add(Price.ADAPTER.decode(reader)); break;
case 3: builder.phone(ProtoAdapter.STRING.decode(reader)); break;
case 4: builder.prepayAmount(ProtoAdapter.STRING.decode(reader)); break;
case 5: builder.entranceCardPrice(ProtoAdapter.UINT64.decode(reader)); break;
case 6: builder.familyPriceVOList.add(CompanyPriceVO.ADAPTER.decode(reader)); break;
case 7: builder.entranceCardPriceStr(ProtoAdapter.STRING.decode(reader)); break;
case 8: builder.totalPrice(ProtoAdapter.STRING.decode(reader)); break;
default: {
FieldEncoding fieldEncoding = reader.peekFieldEncoding();
Object value = fieldEncoding.rawProtoAdapter().decode(reader);
builder.addUnknownField(tag, fieldEncoding, value);
}
}
}
reader.endMessage(token);
return builder.build();
}
@Override
public GetPriceRsp redact(GetPriceRsp value) {
Builder builder = value.newBuilder();
Internal.redactElements(builder.pList12N, Price.ADAPTER);
Internal.redactElements(builder.pList121, Price.ADAPTER);
Internal.redactElements(builder.familyPriceVOList, CompanyPriceVO.ADAPTER);
builder.clearUnknownFields();
return builder.build();
}
}
}
|
Java
|
UTF-8
| 1,208 | 2.984375 | 3 |
[] |
no_license
|
package exercício_too_agosto;
public class Exercício_TOO_Agosto {
public static void main(String[] args) {
System.out.println("***** DAGOS DO PACIENTE ***** \n");
Paciente p = new Paciente();
p.setNome("Helen");
p.setSobrenome("Ikeda");
p.setCPF("055.475.999-66");
p.setRG("12.741.200-4");
p.setCodPaciente(1);
Informações.mostrarDadosPaciente(p);
System.out.println("\n");
System.out.println("***** DADOS DO MÉDICO ***** \n");
Médico m = new Médico();
m.setNome("Juliana");
m.setSobrenome("Marques");
m.setCPF("042.149.666-69");
m.setRG("07.510.497-X");
m.setEspecialidade("Ortopedista");
m.setSalario(10000);
Informações.mostrarDadosMedico(m);
System.out.println("\n");
System.out.println("***** DADOS DO ENFERMEIRO ***** \n");
Enfermeiro e = new Enfermeiro();
e.setNome("Murilo");
e.setSobrenome("Sérgio");
e.setCPF("318.417.910-01");
e.setRG("87.977.450-3");
e.setCoren("8925");
Informações.mostrarDadosEnfermeiros(e);
}
}
|
Java
|
UTF-8
| 6,336 | 1.867188 | 2 |
[
"Apache-2.0"
] |
permissive
|
package com.xinfan.wxshop.business.admin;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.xinfan.wxshop.business.entity.Customer;
import com.xinfan.wxshop.business.entity.Order;
import com.xinfan.wxshop.business.entity.OrderDetail;
import com.xinfan.wxshop.business.formater.DataGridFormater;
import com.xinfan.wxshop.business.formater.OrderStateDataGridFormater;
import com.xinfan.wxshop.business.model.DataTableDataGrid;
import com.xinfan.wxshop.business.model.JSONResult;
import com.xinfan.wxshop.business.service.CustomerService;
import com.xinfan.wxshop.business.service.OrderService;
import com.xinfan.wxshop.business.util.RequestUtils;
import com.xinfan.wxshop.common.base.DataMap;
import com.xinfan.wxshop.common.page.Pagination;
import com.xinfan.wxshop.common.sms.SmsService;
@Controller
@RequestMapping("/admin")
public class OrderAction {
private static final Logger logger = LoggerFactory.getLogger(OrderAction.class);
@Autowired
private OrderService OrderService;
@Autowired
private CustomerService CustomerService;
@Autowired
private SmsService SmsService;
@RequestMapping("/order-list.jspx")
public ModelAndView listOrder(HttpServletRequest request) {
ModelAndView mv = new ModelAndView("/admin/order/list");
return mv;
}
@RequestMapping("/confirm-msg.jspx")
public ModelAndView confirmMsg(HttpServletRequest request) {
ModelAndView mv = new ModelAndView("/admin/order/confirm_msg");
String id = request.getParameter("id");
mv.addObject("id", id);
return mv;
}
@RequestMapping("/save-confirm-msg.jspx")
public @ResponseBody
JSONResult savConfirmMsg(HttpServletRequest request) {
JSONResult result = null;
String id = request.getParameter("id");
String msg = request.getParameter("msg");
try {
Order order = this.OrderService.getPayOrderInfo(0, Integer.parseInt(id));
if (order != null) {
SmsService.sendOrderConfirmMsg(order.getReceiverPhone(), msg);
OrderService.updateOrderIsConfirmed(Integer.parseInt(id));
}
result = JSONResult.success();
} catch (Exception e) {
logger.error(e.getMessage(), e);
result = JSONResult.error(e.getMessage());
}
return result;
}
@RequestMapping("/order-list-page.jspx")
public @ResponseBody
DataTableDataGrid listOrderPage(HttpServletRequest request) {
Pagination page = RequestUtils.getDataTablePagination(request);
String draw = request.getParameter("draw");
if (draw == null || draw.trim().length() == 0) {
draw = "1";
}
DataMap paramter = new DataMap();
String state = request.getParameter("state");
if (StringUtils.isNotEmpty(state)) {
paramter.put("status", state);
}
String account = request.getParameter("account");
String startdate = request.getParameter("startdate");
String enddate = request.getParameter("enddate");
String orderId = request.getParameter("orderId");
if (StringUtils.isNotEmpty(account)) {
paramter.put("account", account);
}
if (StringUtils.isNotEmpty(startdate)) {
paramter.put("startdate", startdate);
}
if (StringUtils.isNotEmpty(enddate)) {
paramter.put("enddate", enddate);
}
if (StringUtils.isNotEmpty(orderId)) {
paramter.put("orderId", orderId);
}
page = OrderService.pageSelectOrderList(paramter, page);
DataGridFormater stateFormater = new OrderStateDataGridFormater("status");
DataTableDataGrid grid = new DataTableDataGrid(Integer.parseInt(draw), page, new Object[] { "order_id", "receiver_name", "account", "order_date",
"total_amount", "status","shared" });
return grid;
}
@RequestMapping("/order-info.jspx")
public ModelAndView orderDetail(HttpServletRequest request) {
ModelAndView mv = new ModelAndView("/admin/order/info");
String orderId = request.getParameter("oid");
int oid = Integer.parseInt(orderId);
List<OrderDetail> orderDetailList = OrderService.getOrderDetail(0, oid);
Order order = OrderService.getPayOrderInfo(0, oid);
Customer customer = CustomerService.getById(order.getCustomerId());
mv.addObject("orderDetailList", orderDetailList);
mv.addObject("order", order);
mv.addObject("customer", customer);
return mv;
}
@RequestMapping("/order-process.jspx")
public ModelAndView order_process(HttpServletRequest request) {
ModelAndView mv = new ModelAndView("/admin/m_order_process");
String orderId = request.getParameter("oid");
int oid = Integer.parseInt(orderId);
List<OrderDetail> orderDetailList = OrderService.getOrderDetail(0, oid);
Order order = OrderService.getPayOrderInfo(0, oid);
Customer customer = CustomerService.getById(order.getCustomerId());
mv.addObject("orderDetailList", orderDetailList);
mv.addObject("order", order);
mv.addObject("customer", customer);
return mv;
}
@RequestMapping("/process-order-{id}.jspx")
public @ResponseBody
JSONResult processOrder(@PathVariable int id, HttpServletRequest request) {
JSONResult result = null;
try {
OrderService.processOrder(id);
result = JSONResult.success();
} catch (Exception e) {
logger.error(e.getMessage(), e);
result = JSONResult.error();
}
return result;
}
@RequestMapping("/wait-order-page.jspx")
public @ResponseBody
DataTableDataGrid waitOrderPage(HttpServletRequest request) {
Pagination page = RequestUtils.getDataTablePagination(request);
String draw = request.getParameter("draw");
if (draw == null || draw.trim().length() == 0) {
draw = "1";
}
// page = OrderService.pageSelectOrderList(1, page);
DataTableDataGrid grid = new DataTableDataGrid(Integer.parseInt(draw), page, new String[] { "order_id", "displayname", "order_date", "total_amount",
"status" });
return grid;
}
}
|
Shell
|
UTF-8
| 246 | 2.640625 | 3 |
[] |
no_license
|
#!/bin/bash
IMAGENAME=${2:-"debian:jessie"}
sed "s/{{IMAGENAME}}/${IMAGENAME}/" Dockerfile.templ > Dockerfile
docker build -t py2deb .
rm Dockerfile
mkdir -p pkg
docker run -v `pwd`/pkg:/tmp --rm=true -it --name py2deb py2deb py2deb $3 -- $1
|
Python
|
UTF-8
| 1,483 | 2.515625 | 3 |
[] |
no_license
|
# -*- coding: utf-8 -*-
"""
Created on Thu May 2 11:15:26 2019
@author: Chris
"""
from bokeh.models import Panel, Tabs
from bokeh.io import output_file, show
from bokeh.plotting import figure
import gridwatchLinePlot
import tidalvwind
import twinRidgePlot
import govtDataPlot
import loadFollowingHex
import paras
from bokeh.io import curdoc
from bokeh.layouts import column,row
output_folder="C:/Users/Chris/Documents/Documents/Python2018/DataVisCW/Plots"
## Define the layout of the overall bokeh output #########################
tab0 = Panel(child= paras.introP,
title = 'Info')
tab1 = Panel(child=column(paras.squiggleP,
gridwatchLinePlot.layout),
title='Explore the data')
tab2 = Panel(child=column(paras.ridgeP,
twinRidgePlot.layout),
title='Nuclear vs Wind')
tab3 = Panel(child = column(paras.govtP,
govtDataPlot.layout,
row(paras.govtPb,
paras.gap,
paras.govtPc)),
title = 'Trends')
tab4 = Panel(child = column(paras.tidalvwindP,
tidalvwind.layout),
title = 'Tidal vs wind')
tab5 = Panel(child = loadFollowingHex.layout,
title = 'Load Following')
tabs = Tabs(tabs=[tab0,tab1,tab2,tab3,tab4, tab5])
curdoc().add_root(tabs)
#show(tabs)
|
Markdown
|
UTF-8
| 366 | 2.65625 | 3 |
[] |
no_license
|
# Overview
This is a tic-tac-toe program
This simple game demonstrates how to use files to save game progress and resume the game by reading the game board from the file if it exists.
I created this game to review working with JSON files in python.
[Software Demo Video](http://youtube.link.goes.here)
# Development Environment
Visual Studio Code 3.9.7
Python
|
C#
|
UTF-8
| 1,163 | 3.390625 | 3 |
[] |
no_license
|
using System;
namespace Ejercicio02
{
class Program
{
static void Main(string[] args)
{
int valorMax = 0;
int times = 0;
int[,] matriz = new int[4, 4];
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
Console.WriteLine("ingrese" + "[" + i + "," + j + "]");
matriz[i, j] = Convert.ToInt16(Console.ReadLine());
if (matriz[i, j] > valorMax)
{
valorMax = matriz[i, j];
}
}
}
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
if (matriz[i, j] == valorMax)
{
times++;
}
}
}
Console.WriteLine($"El valor maximo {valorMax} se repite {times} veces");
Console.ReadKey();
}
}
}
|
TypeScript
|
UTF-8
| 2,002 | 2.5625 | 3 |
[
"MIT"
] |
permissive
|
import * as firebase from "firebase";
import stateEngine from "./state-engine";
import App from "./app";
interface GridConfig {
x: number,
y: number,
autoPosition: boolean,
id: string
}
export class AppGridService {
public saveInstalledGrid() {
const apps = stateEngine.get("installed-apps") as Array<App>;
const userGrid = {
apps: new Array<GridConfig>()
}
apps.forEach(app => {
const gso = app.getGridStackOptions();
userGrid.apps.push({ x: gso.x, y: gso.y, autoPosition: gso.autoPosition, id: gso.id });
});
firebase.database().ref('grid/' + firebase.auth().currentUser.uid).set(userGrid);
}
public loadGrid(): void {
firebase.database().ref('/grid/' + firebase.auth().currentUser.uid).once('value').then(function (snapshot) {
if (snapshot.val() != null) {
const appsConfig = snapshot.val().apps as Array<GridConfig>;
const newInstalledApps = new Array<App>();
const availableApps = stateEngine.get("available-apps") as Array<App>;
if (availableApps != null && availableApps.length != 0) {
appsConfig.forEach(cfg => {
const filtered = availableApps.filter(app => app.getId() == cfg.id);
if (filtered.length != 0) {
const app = filtered[0];
app.setX(cfg.x);
app.setY(cfg.y);
app.setAutoPosition(cfg.autoPosition);
newInstalledApps.push(app);
}
});
stateEngine.set("installed-apps", newInstalledApps);
return;
}
}
stateEngine.set("installed-apps", null);
});
}
}
const appGridService: AppGridService = new AppGridService();
export default appGridService;
|
Python
|
UTF-8
| 273 | 3.21875 | 3 |
[] |
no_license
|
num = int(input())
arr = []
newarr = []
arr = list(map(int, input().split()))
maxnum = max(arr)
for i in arr:
newarr.append(i / maxnum * 100)
print(round(sum(newarr) / num, 6))
# round는 소수 n번째 자리까지 보여주는 것 n번째 전에서 반올림한다.
|
Java
|
UTF-8
| 17,227 | 1.78125 | 2 |
[] |
no_license
|
package com.example.designofsteelstructures;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.Gson;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
public class SingleAngle extends AppCompatActivity {
private EditText et_Factored_Load, et_length_of_tension_member, et_allowable_slenderness_ratio, et_ultimate_tensile_stress, et_steel_yield_stress, et_gamma_m0, et_gamma_m1, et_bolt_ultimate_tensile_stress, et_bolt_diameter, et_pitch, et_end_distance, et_gamma_mb;
private CheckBox cb_use_Fe_410_steel, cb_take_partial_safety_factors_wrt_table5, cb_use_min_value_acc_to_IS800, cb_take_gamma_mb_from_IS800, cb_connected_length_larger;
private RadioButton rb_bolt_grade_4x6, rb_bolt_grade_8x8, rb_equal_section, rb_unequal_section;
private Double factoredLoad, lengthOfTensionMember, allowableSlendernessRatio, ultimateTensileStress, steelYieldStress, gamma_m0, gamma_m1, boltUltimateTensileStress, boltDiameter, holeDiameter, Pitch, endDistance, gamma_mb;
private ArrayList<Design> ISA_Angles = new ArrayList<>();
public static final String TAG = "SingleAngle";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.single_angle_bolt);
et_Factored_Load = findViewById(R.id.et_Factored_Load);
et_length_of_tension_member = findViewById(R.id.et_len_of_tension_member);
et_allowable_slenderness_ratio = findViewById(R.id.et_allowable_slenderness_ratio);
et_ultimate_tensile_stress = findViewById(R.id.et_Ultimate_Tensile_Stress);
et_steel_yield_stress = findViewById(R.id.et_Yield_Stress);
et_gamma_m0 = findViewById(R.id.et_gamma_0);
et_gamma_m1 = findViewById(R.id.et_gamma_1);
et_bolt_ultimate_tensile_stress = findViewById(R.id.et_Ultimate_Tensile_Stress_bolt);
et_bolt_diameter = findViewById(R.id.et_diameter_bolt);
et_pitch = findViewById(R.id.et_pitch);
et_end_distance = findViewById(R.id.et_end_dist);
et_gamma_mb = findViewById(R.id.et_custom_safety_factor);
cb_use_Fe_410_steel = findViewById(R.id.checkbox_Use_fe410);
cb_take_partial_safety_factors_wrt_table5 = findViewById(R.id.checkbox_Use_IS800_table5_values);
cb_use_min_value_acc_to_IS800 = findViewById(R.id.take_min_val_from_IS800);
cb_take_gamma_mb_from_IS800 = findViewById(R.id.checkbox_Use_IS800_table5_values2);
cb_connected_length_larger = findViewById(R.id.checkbox_connected_length_larger);
rb_bolt_grade_4x6 = findViewById(R.id.radio_grade4_6);
rb_bolt_grade_8x8 = findViewById(R.id.radio_grade8_8);
rb_equal_section = findViewById(R.id.radio_equal_angle);
rb_unequal_section = findViewById(R.id.radio_unequal_angle);
cb_use_Fe_410_steel.setOnCheckedChangeListener((buttonView, isChecked) -> {
if (isChecked) {
et_steel_yield_stress.setText(R.string.FE410_steel_yield_stress);
et_steel_yield_stress.setTextColor(getResources().getColor((R.color.faded)));
et_ultimate_tensile_stress.setText(R.string.FE410_ultimate_tensile_stress);
et_ultimate_tensile_stress.setTextColor(getResources().getColor((R.color.faded)));
} else {
et_steel_yield_stress.setTextColor(Color.BLACK);
et_ultimate_tensile_stress.setTextColor(Color.BLACK);
}
});
cb_take_partial_safety_factors_wrt_table5.setOnCheckedChangeListener((buttonView, isChecked) -> {
if (isChecked) {
et_gamma_m1.setText(R.string.gamma_m1);
et_gamma_m0.setText(R.string.gamma_m0);
et_gamma_m1.setTextColor(getResources().getColor((R.color.faded)));
et_gamma_m0.setTextColor(getResources().getColor((R.color.faded)));
} else {
et_gamma_m1.setTextColor(Color.BLACK);
et_gamma_m0.setTextColor(Color.BLACK);
}
});
rb_bolt_grade_4x6.setOnCheckedChangeListener((buttonView, isChecked) -> {
if (isChecked) {
et_bolt_ultimate_tensile_stress.setText(R.string.bolt_46);
et_bolt_ultimate_tensile_stress.setTextColor(getResources().getColor((R.color.faded)));
} else if (rb_bolt_grade_8x8.isChecked()) {
et_bolt_ultimate_tensile_stress.setText(R.string.bolt_88);
et_bolt_ultimate_tensile_stress.setTextColor(getResources().getColor((R.color.faded)));
} else {
et_bolt_ultimate_tensile_stress.setTextColor(Color.BLACK);
}
});
rb_bolt_grade_8x8.setOnCheckedChangeListener((buttonView, isChecked) -> {
if (isChecked) {
et_bolt_ultimate_tensile_stress.setText(R.string.bolt_88);
et_bolt_ultimate_tensile_stress.setTextColor(getResources().getColor((R.color.faded)));
} else if (rb_bolt_grade_4x6.isChecked()) {
et_bolt_ultimate_tensile_stress.setText(R.string.bolt_46);
et_bolt_ultimate_tensile_stress.setTextColor(getResources().getColor((R.color.faded)));
} else {
et_bolt_ultimate_tensile_stress.setTextColor(Color.BLACK);
}
});
cb_use_min_value_acc_to_IS800.setOnCheckedChangeListener((buttonView, isChecked) -> {
if (isChecked) {
String value = et_bolt_diameter.getText().toString();
if (value.equals("")) return;
double ans = 2.5 * (Double.parseDouble(value) + 2);
value = ans + "";
et_pitch.setText(value);
et_pitch.setTextColor(getResources().getColor((R.color.faded)));
double holeDia = 1.5 * (Double.parseDouble(et_bolt_diameter.getText().toString()) + 2);
value = holeDia + "";
et_end_distance.setText(value);
et_end_distance.setTextColor(getResources().getColor((R.color.faded)));
} else {
et_pitch.setTextColor(Color.BLACK);
et_end_distance.setTextColor(Color.BLACK);
}
});
cb_take_gamma_mb_from_IS800.setOnCheckedChangeListener((buttonView, isChecked) -> {
if (isChecked) {
et_gamma_mb.setText(R.string.gamma_mb);
et_gamma_mb.setTextColor(getResources().getColor((R.color.faded)));
} else {
et_gamma_mb.setTextColor(Color.BLACK);
}
});
// rb_equal_section.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
// @Override
// public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// if (isChecked) {
//
// } else if(rb_bolt_grade_8x8.isChecked()) {
//
// } else {
//
// }
// }
// });
// rb_bolt_grade_8x8.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
// @Override
// public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// if (isChecked) {
//
// } else if(rb_bolt_grade_4x6.isChecked()) {
//
// } else {
//
// }
// }
// });
TextView next = findViewById(R.id.btn_submit);
next.setOnClickListener(v -> {
readISAValues();
make_design();
});
}
private boolean updateValues() {
if (cb_use_Fe_410_steel.isChecked()) {
et_ultimate_tensile_stress.setText(R.string.FE410_ultimate_tensile_stress);
et_steel_yield_stress.setText(R.string.FE410_steel_yield_stress);
et_ultimate_tensile_stress.setTextColor(getResources().getColor((R.color.faded)));
et_steel_yield_stress.setTextColor(getResources().getColor((R.color.faded)));
}
if (cb_take_partial_safety_factors_wrt_table5.isChecked()) {
et_gamma_m1.setText(R.string.gamma_m1);
et_gamma_m0.setText(R.string.gamma_m0);
et_gamma_m1.setTextColor(getResources().getColor((R.color.faded)));
et_gamma_m0.setTextColor(getResources().getColor((R.color.faded)));
}
if (rb_bolt_grade_4x6.isChecked()) {
et_bolt_ultimate_tensile_stress.setText(R.string.bolt_46);
et_bolt_ultimate_tensile_stress.setTextColor(getResources().getColor((R.color.faded)));
} else if (rb_bolt_grade_8x8.isChecked()) {
et_bolt_ultimate_tensile_stress.setText(R.string.bolt_88);
et_bolt_ultimate_tensile_stress.setTextColor(getResources().getColor((R.color.faded)));
}
if (cb_use_min_value_acc_to_IS800.isChecked()) {
et_pitch.setTextColor(getResources().getColor((R.color.faded)));
et_end_distance.setTextColor(getResources().getColor((R.color.faded)));
}
if (cb_take_gamma_mb_from_IS800.isChecked()) {
et_gamma_mb.setText(R.string.gamma_mb);
et_gamma_mb.setTextColor(getResources().getColor((R.color.faded)));
}
String value = et_Factored_Load.getText().toString();
if (value.equals("")) return false;
factoredLoad = 1000 * Double.parseDouble(value);
value = et_length_of_tension_member.getText().toString();
if (value.equals("")) return false;
lengthOfTensionMember = Double.parseDouble(value);
value = et_allowable_slenderness_ratio.getText().toString();
if (value.equals("")) return false;
allowableSlendernessRatio = Double.parseDouble(value);
value = et_ultimate_tensile_stress.getText().toString();
if (value.equals("")) return false;
ultimateTensileStress = Double.parseDouble(value);
value = et_steel_yield_stress.getText().toString();
if (value.equals("")) return false;
steelYieldStress = Double.parseDouble(value);
value = et_gamma_m0.getText().toString();
if (value.equals("")) return false;
gamma_m0 = Double.parseDouble(value);
value = et_gamma_m1.getText().toString();
if (value.equals("")) return false;
gamma_m1 = Double.parseDouble(value);
value = et_bolt_ultimate_tensile_stress.getText().toString();
if (value.equals("")) return false;
boltUltimateTensileStress = Double.parseDouble(value);
value = et_bolt_diameter.getText().toString();
if (value.equals("")) return false;
boltDiameter = Double.parseDouble(value);
holeDiameter = boltDiameter + 2;
value = et_pitch.getText().toString();
if (value.equals("")) return false;
Pitch = Double.parseDouble(value);
value = et_end_distance.getText().toString();
if (value.equals("")) return false;
endDistance = Double.parseDouble(value);
value = et_gamma_mb.getText().toString();
if (value.equals("")) return false;
gamma_mb = Double.parseDouble(value);
return true;
}
void readISAValues() {
ISA_Angles.clear();
if (rb_equal_section.isChecked()) {
readJsonFromFile("equal_angles.json");
} else {
readJsonFromFile("unequal_angles.json");
}
}
private void readJsonFromFile(String fileName) {
try {
InputStream inputStream = getAssets().open(fileName);
int size = inputStream.available();
byte[] buffer = new byte[size];
inputStream.read(buffer);
inputStream.close();
String json = new String(buffer, StandardCharsets.UTF_8);
JSONArray jsonArray = new JSONArray(json);
for(int i = 0; i < jsonArray.length(); ++i) {
Gson gson = new Gson();
JSONObject jsonObject = jsonArray.getJSONObject(i);
Design design = gson.fromJson(jsonObject.toString(), Design.class);
ISA_Angles.add(design);
}
} catch (Exception e) {
Log.e(TAG, "readJsonFromFile: " + e.getMessage());
}
}
void make_design() {
if (!updateValues()) {
Toast.makeText(this, "Insert All Values.", Toast.LENGTH_SHORT).show();
return;
}
double minAreaRequired = (factoredLoad * gamma_m0) / steelYieldStress;
// We put a counter variable to traverse all the json objects belonging to the equal / unequal section
for (int counter = 0; counter < ISA_Angles.size(); ++counter) {
double currentArea = ISA_Angles.get(counter).getSectionalArea() * 100d;
if (currentArea >= minAreaRequired) {
// Checking for Shear Strength
double crossSectionalArea = 0.78 * 0.25 * 3.14 * (boltDiameter * boltDiameter);
double boltShearStrength = boltUltimateTensileStress * crossSectionalArea / (1.73 * gamma_mb);
// Bearing Strength
double Kb = Math.min(Math.min(endDistance / (3 * holeDiameter), (Pitch / (3 * holeDiameter)) - 0.25), Math.min(boltUltimateTensileStress / ultimateTensileStress, 1d));
double bearingStrengthOfBolt = (2.5d * Kb * boltDiameter * boltUltimateTensileStress * ISA_Angles.get(counter).getThickness()) / gamma_mb;
int numberOfBolts = (int) Math.ceil(factoredLoad / Math.min(boltShearStrength, bearingStrengthOfBolt));
double alpha = (numberOfBolts <= 2) ? 0.6 : (numberOfBolts == 3) ? 0.7 : 0.8;
// Yielding Strength
double Tdg = steelYieldStress * ISA_Angles.get(counter).getSectionalArea() * 100 / gamma_m0;
// Rupture Strength
double Anc = (ISA_Angles.get(counter).getLength() - (ISA_Angles.get(counter).getThickness() >> 1) - holeDiameter) * ISA_Angles.get(counter).getThickness();
double Ago = (ISA_Angles.get(counter).getWidth() - (ISA_Angles.get(counter).getThickness() >> 1)) * ISA_Angles.get(counter).getThickness();
double An = Anc + Ago;
double Tdn = ultimateTensileStress * An * alpha / gamma_m1;
// Block Shear
double g = Math.ceil((ISA_Angles.get(counter).getLength() - ISA_Angles.get(counter).getThickness()) >> 1);
double p = ISA_Angles.get(counter).getLength() - g;
double Avg = (((numberOfBolts - 1) * Pitch) + endDistance) * ISA_Angles.get(counter).getThickness();
double Avn = (((numberOfBolts - 1) * Pitch) + endDistance - (numberOfBolts - 0.5d) * holeDiameter) * ISA_Angles.get(counter).getThickness();
double Atg = p * ISA_Angles.get(counter).getThickness();
double Atn = (p - (0.5 * holeDiameter)) * ISA_Angles.get(counter).getThickness();
double Tdb1 = ((0.9d * Avn * ultimateTensileStress) / (1.73d * gamma_m1)) + (Atg * steelYieldStress / gamma_m0);
double Tdb2 = ((Avg * steelYieldStress) / (1.73d * gamma_m0)) + ((0.9d * Atn * ultimateTensileStress) / gamma_m1);
double Tdb = Math.min(Tdb1, Tdb2);
// Taking Minimum Magnitude of possible failure scenarios
double designStrengthOfAngle = Math.min(Math.min(Tdg, Tdb), Tdn);
if (designStrengthOfAngle >= factoredLoad) {
String ansStatement = "ISA section " + ISA_Angles.get(counter).getLength() + " x " + ISA_Angles.get(counter).getWidth() + " x " + ISA_Angles.get(counter).getThickness() + " is termed suitable for the given load conditions.";
Intent intent = new Intent(this, ResultShowcase.class);
intent.putExtra("results", ansStatement);
intent.putExtra("isBolt", true);
intent.putExtra("factored_load", "" + factoredLoad / 1000);
intent.putExtra("len_of_ten_member", "" + lengthOfTensionMember);
intent.putExtra("slenderness_ratio", "" + allowableSlendernessRatio);
intent.putExtra("gamma_m1", "" + gamma_m1);
intent.putExtra("gamma_m0", "" + gamma_m0);
intent.putExtra("gamma_mb", "" + gamma_mb);
intent.putExtra("diameter_of_bolt", "" + boltDiameter);
intent.putExtra("num_of_bolts", "" + numberOfBolts);
this.startActivity(intent);
return;
}
}
}
String ansStatement = "No available ISA section can be termed suitable for the given load conditions.";
Toast.makeText(this, ansStatement, Toast.LENGTH_SHORT).show();
}
}
|
TypeScript
|
UTF-8
| 4,606 | 2.71875 | 3 |
[] |
no_license
|
import crypto from 'crypto';
import { EntityPlainProtectedColumn } from '@column/entities';
describe('Plain entity column protection FROM', () => {
test(`String data should be deserialized in the same format it's stored`, () => {
const entityPlain = new EntityPlainProtectedColumn({
binaryTextFormat: 'hex',
});
const serializedData = {
_type: 'plain',
data: 'hello',
};
const result = entityPlain.protectFrom(serializedData);
expect(result).toEqual(serializedData.data);
});
test(`Hash digest should be validated`, () => {
const data = 'hello';
const hashAlgorithm = 'sha256';
const binaryTextFormat = 'hex';
const entityPlain = new EntityPlainProtectedColumn({
binaryTextFormat,
hash: {
algorithm: hashAlgorithm,
},
});
const serializedData = {
_type: 'plain',
data: data,
hashAlgorithm: hashAlgorithm,
hash: crypto.createHash(hashAlgorithm).update(data).digest().toString(binaryTextFormat),
};
const result = entityPlain.protectFrom(serializedData);
expect(result).toEqual(serializedData.data);
});
test(`Hash digest should be validated with via custom provided function`, () => {
const hashAlgorithm = 'sha256';
const binaryTextFormat = 'hex';
const hashValue = Buffer.from('nice');
const hashPayloadFn = jest.fn(() => hashValue);
const entityPlain = new EntityPlainProtectedColumn({
binaryTextFormat,
hash: {
makeHash: hashPayloadFn,
hashOptions: {
algorithm: hashAlgorithm,
},
},
});
const serializedData = {
_type: 'plain',
data: 'data',
hashAlgorithm: hashAlgorithm,
hash: hashValue.toString(binaryTextFormat),
};
entityPlain.protectFrom(serializedData);
expect(hashPayloadFn).toBeCalled();
});
test(`Exception should be thrown, when hash digest mismatches`, () => {
const data = 'hello';
const hashAlgorithm = 'sha256';
const binaryTextFormat = 'hex';
const entityPlain = new EntityPlainProtectedColumn({
binaryTextFormat,
hash: {
algorithm: hashAlgorithm,
},
});
const serializedData = {
_type: 'plain',
data: data,
hashAlgorithm: hashAlgorithm,
hash: crypto.createHash(hashAlgorithm).update('someother').digest().toString(binaryTextFormat),
};
expect(entityPlain.protectFrom.bind(entityPlain, serializedData)).toThrowError();
});
test(`Exception should be thrown, when hash digest is mismatched via custom function`, () => {
const hashAlgorithm = 'sha256';
const binaryTextFormat = 'hex';
const hashValue = Buffer.from('some_data');
const hashPayloadFn = jest.fn(() => hashValue);
const entityPlain = new EntityPlainProtectedColumn({
binaryTextFormat,
hash: {
makeHash: hashPayloadFn,
hashOptions: {
algorithm: hashAlgorithm,
},
},
});
const serializedData = {
_type: 'plain',
data: 'data',
hashAlgorithm: hashAlgorithm,
hash: Buffer.from('some_other_data').toString(binaryTextFormat),
};
expect(entityPlain.protectFrom.bind(entityPlain, serializedData)).toThrowError();
});
test(`Exception should be thrown, when binary text format is mismatched`, () => {
const data = 'hello';
const hashAlgorithm = 'sha256';
const binaryTextFormatV1 = 'base64';
const binaryTextFormatV2 = 'hex';
const entityPlain = new EntityPlainProtectedColumn({
binaryTextFormat: binaryTextFormatV1,
hash: {
algorithm: hashAlgorithm,
},
});
const serializedData = {
_type: 'plain',
data: data,
hashAlgorithm: hashAlgorithm,
hash: crypto.createHash(hashAlgorithm).update(data).digest().toString(binaryTextFormatV2),
};
expect(entityPlain.protectFrom.bind(entityPlain, serializedData)).toThrowError();
});
test(`Exception should be thrown, when unknown column type shows up`, () => {
const data = 'hello';
const hashAlgorithm = 'sha256';
const binaryTextFormat = 'hex';
const entityPlain = new EntityPlainProtectedColumn({
binaryTextFormat,
hash: {
algorithm: hashAlgorithm,
},
});
const serializedData = {
_type: 'some_unknown_type',
data: data,
hashAlgorithm: hashAlgorithm,
hash: crypto.createHash(hashAlgorithm).update(data).digest().toString(binaryTextFormat),
};
expect(entityPlain.protectFrom.bind(entityPlain, serializedData)).toThrowError();
});
});
|
Java
|
UTF-8
| 382 | 1.992188 | 2 |
[] |
no_license
|
package ru.nchernetsov.test.sbertech.common.message;
import lombok.Data;
import java.io.Serializable;
/**
* Адрес для указания отправителя и получателя сообщений
*/
@Data
public class Address implements Serializable {
private final String address;
public Address(String address) {
this.address = address;
}
}
|
C#
|
UTF-8
| 1,250 | 2.78125 | 3 |
[] |
no_license
|
class Path
{
public string Id { get; set; }
public File File { get; set; }
}
class File
{
public Guid Id { get; set; }
public ICollection<Version> Versions { get; set; }
}
class Version
{
public string Id { get; set; }
}
class Program
{
static void Main(string[] args)
{
var builder = new ODataConventionModelBuilder();
builder.Namespace = "api";
builder.EntityType<File>();
var function = builder.EntityType<Path>().Function("getFileByName");
function.Parameter<string>("name");
//function.ReturnsFromEntitySet<File>("Files");
function.ReturnsEntityViaEntitySetPath<File>("bindingParameter/File");
function.IsComposable = true;
builder.EntitySet<Path>("Paths");
builder.EntitySet<Version>("Versions");
var model = builder.GetEdmModel();
string path = "Paths('1')/api.getFileByName(name='sd')/Versions('s')";
var parser = new ODataUriParser(model, new Uri(path, UriKind.Relative));
var pa = parser.ParsePath();
Console.WriteLine(pa);
}
}
|
Ruby
|
UTF-8
| 2,171 | 2.8125 | 3 |
[
"MIT"
] |
permissive
|
require "fmparser/error"
require "fmparser/node"
require "fmparser/parser/deep_hash_parser"
module FMParser
class Parser
# @param [<String>] paths
# @param [Class] root Google::Protobuf message class
def parse(paths:, root:)
deep_hash = DeepHashParser.parse(paths)
scalars, enums, messages = build_nodes(
descriptor: root.descriptor,
deep_hash: deep_hash,
)
MessageNode.new(
name: nil,
type: root,
label: nil,
scalars: scalars,
enums: enums,
messages: messages,
)
end
private
# @param [Google::Protobuf::Descriptor] descriptor
# @param [FMParser::Parser::DeepHashNode] deep_hash
# @return [<<ScalarNode>, <EnumNode>, <MessageNode>>]
def build_nodes(descriptor:, deep_hash:)
scalars = []
enums = []
messages = []
deep_hash.children.each do |name, dh|
entry = descriptor.entries.find { |e| e.name == name }
if entry.nil?
raise InvalidPathError.new("\"#{name}\" does not exist in the fields of #{descriptor.msgclass}!")
end
case entry.type
when :message
d = entry.subtype # Google::Protobuf::Descriptor
s, e, m = build_nodes(
descriptor: d,
deep_hash: dh,
)
n = MessageNode.new(
name: name,
type: d.msgclass,
label: entry.label,
scalars: s,
enums: e,
messages: m,
)
messages << n
when :enum
# NOTE: If dh.is_leaf is false, it is invalid. But ignore it now.
d = entry.subtype # Google::Protobuf::EnumDescriptor
n = EnumNode.new(name: name, type: d.enummodule, label: entry.label)
enums << n
else # We treat this case as scalar
# NOTE: If dh.is_leaf is false, it is invalid. But ignore it now.
n = ScalarNode.new(name: name, type: entry.type, label: entry.label)
scalars << n
end
end
[
scalars,
enums,
messages,
]
end
end
end
|
C++
|
UTF-8
| 389 | 3.109375 | 3 |
[] |
no_license
|
#include <math.h>
#include <stdio.h>
#include <iostream>
using namespace std;
int main( void )
{
//Entrada
float raio = 0;
float area = 0;
const float pi = 3.14159;
cout << "ATIVIDADES (5)";
cout << "\n\nInforme o raio do circulo: ";
cin >> raio;
//Processamento
area = pi*pow(raio, 2);
//Saida
cout << "Area do circulo: " << area;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.