language stringclasses 15
values | src_encoding stringclasses 34
values | length_bytes int64 6 7.85M | score float64 1.5 5.69 | int_score int64 2 5 | detected_licenses listlengths 0 160 | license_type stringclasses 2
values | text stringlengths 9 7.85M |
|---|---|---|---|---|---|---|---|
Java | UTF-8 | 264 | 1.757813 | 2 | [] | no_license | package com.dist.message.server.conf;
public interface WSConstants {
/**
* session中用户id
*/
String SESSION_USERNAME = "userId";
/**
* 设备类型
*/
String DEVICE_TYPE = "device";
/**
* token标识符
*/
String TOKEN = "access_token";
}
|
Java | UTF-8 | 297 | 2.859375 | 3 | [] | no_license | public class Solution {
public int lengthOfLastWord(String s) {
if(s.length()==0)
{
return 0;
}
String[] sArr = s.split(" ");
if(sArr.length == 0)
{
return 0;
}
return sArr[sArr.length-1].length();
}
} |
Shell | UTF-8 | 427 | 3.015625 | 3 | [
"BSD-3-Clause",
"MIT"
] | permissive | #!/bin/bash
./auto-init
name="STUB"
run_ionic="npm run ionic:serve"
run_horizon="./dev"
hash "tmux" 2>/dev/null
if [ $? == 0 ]; then
## has tmux installed
tmux start
tmux new -dP -s ionic "$run_ionic"
cd "../$name-horizon"
tmux new -dP -s hz "$run_horizon"
cd "../$name-ionic"
tmux attach -t ionic
else
## do not has tmux installed
cd "../$name-horizon"
$run_horizon &
cd "../$name-ionic"
$run_ionic
fi
|
Python | UTF-8 | 984 | 3.0625 | 3 | [
"MIT"
] | permissive | # Import the helper gateway class
from .AfricasTalkingGateway import AfricasTalkingGateway, AfricasTalkingGatewayException
#django specific imports
from django.conf import settings
#application specific imports
def send_message(phone_number, message, short_code):
'''A function to send messages using Pythons AficasTalkingGateway'''
username = settings.AFRICAS_TALKING['USERNAME']
apikey = settings.AFRICAS_TALKING['API_KEY']
# Create a new instance of our awesome gateway class
gateway = AfricasTalkingGateway(username, apikey)
# Any gateway errors will be captured by our custom Exception class below,
# so wrap the call in a try-catch block
try:
# Thats it, hit send and we'll take care of the rest.
while True:
recipient = gateway.sendMessage(phone_number, message, short_code)[0]
if recipient['status'] == 'Success':
return recipient
except AfricasTalkingGatewayException as e:
print('Encountered an error while sending: {0}'.format(str(e)))
|
Markdown | UTF-8 | 1,874 | 2.65625 | 3 | [] | no_license | # # ListingMarketHistory
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**id** | **int** | The listing market history ID. | [optional]
**listing_market_id** | **int** | The listing market ID of the current listing market history. | [optional]
**referrer_id** | **int** | The referrer ID. | [optional]
**external_id** | **string** | The external ID of the listing market history. | [optional]
**status_id** | **int** | The status ID of the current listing market history. The following properties are available: <ul> <li>1 = Active</li> <li>2 = Ended</li> <li>3 = Relisted</li> <li>4 = Hidden</li> </ul> | [optional]
**quantity** | **int** | The quantity available for sale on the marketplace. | [optional]
**quantity_sold** | **int** | The quantity sold currently on the marketplace. | [optional]
**quantity_sold_delta** | **int** | The difference between the sold quantity and orders imported for this listing market history. | [optional]
**quantity_remain** | **int** | The quantity remaining on the marketplace. | [optional]
**price** | **float** | The price offered for this listing market. @see ListingMarketHistoryVariation if the listing market history contains variations. | [optional]
**currency** | **string** | The currency for the price of this listing market. | [optional]
**sku** | **string** | The stock keeping unit of this listing market history. | [optional]
**created_at** | **string** | The date that the entry was created. | [optional]
**updated_at** | **string** | The date that the entry was updated last. | [optional]
[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md)
|
PHP | WINDOWS-1252 | 9,095 | 2.546875 | 3 | [] | no_license | <?PHP
/*
Autore: Francesco Chiriaco
parametri funzione:
$myquery: query di autenticazione
$area_autenticare: area a cui si deve avere accesso
$necessario_amministratore: 0/1 indica se per l'accesso necessario essere amministratore
$querystr: la query string da accodare al link di ritorno
$valoreidut: identificativo dell'utente che deve avere accesso
$nomecampouser: nome del campo username nella tabella di autenticazione
$nomecampopassword: nome del campo password nella tabella di autenticazione
$nomecampoid: nome del campo contenente l'ID dell'utente
$paginaindice: pagina a cui tornare
per utilizzare questa funzione necessario utilizzare 3 tabelle
1) tabella contenente gli utenti
2) aree_aut tabella che collega gli utenti con le aree a cui possono avere accesso
3) sezioni_aut tabella delle aree di accesso esistenti
esempio di chiamata:
if(!isset($_SESSION["aut"]) || ($_SESSION["aut"] != 1) || !isset($_SESSION["area"]) || (strpos($_SESSION["area"],"docenti") === false) || ($_SESSION["idut"] != $_REQUEST["idutente"]))
{
if (!autentica_ut3("select * from utenti,aree_aut where utenti.id = aree_aut.idutente","docenti",0,"?id={$_REQUEST["id"]}&idutente={$_REQUEST["idutente"]}",$_REQUEST["idutente"]))
exit;
}
if(!isset($_SESSION["aut"]) || ($_SESSION["aut"] != 1) || !isset($_SESSION["area"]) || (strpos($_SESSION["area"],"admin") === false) || !isset($_SESSION["amministratore"]["admin"]) || ($_SESSION["amministratore"]["admin"] != 1))
{
if (!autentica_ut3("select * from utenti,aree_aut where utenti.id = aree_aut.idutente","admin",1))
exit;
}
if(!isset($_SESSION["aut"]) || ($_SESSION["aut"] != 1) || !isset($_SESSION["area"]) || (strpos($_SESSION["area"],"cistituto") === false))
{
if (!autentica_ut3("select * from utenti,aree_aut where utenti.id = aree_aut.idutente","cistituto",0))
exit;
}
*/
function autentica_ut3($myquery = "",$area_autenticare = "news",$necessario_amministratore = 0,$paginaindice = "../index.php",$querystr = "",$valoreidut = 0,$nomecampouser="username",$nomecampopassword="password",$nomecampoid = "")
{
if (isset($_POST["pwd"]) && isset($_POST["uname"]))
{
if((strpos($_POST["pwd"],"'") !== false) || (strpos($_POST["uname"],"'") !== false))
{
echo "<p style=\"text-align:center;fontweight:bold;\">Utente non autorizzato<br /><br /><a href=\"{$paginaindice}{$querystr}\">Torna Indietro</a>\n";
echo "</body>\n";
echo "</html>";
return false;
}
if((strpos($_POST["pwd"],"\"") !== false) || (strpos($_POST["uname"],"\"") !== false))
{
echo "<p style=\"text-align:center;fontweight:bold;\">Utente non autorizzato<br /><br /><a href=\"{$paginaindice}{$querystr}\">Torna Indietro</a>\n";
echo "</body>\n";
echo "</html>";
return false;
}
$uname = filter_var($_POST["uname"],FILTER_SANITIZE_STRING);
$pwd = filter_var($_POST["pwd"],FILTER_SANITIZE_STRING);
if(empty($valoreidut))
$qrytxt = $myquery . " and $nomecampouser = '{$uname}' and $nomecampopassword = password('" . $pwd . "')";
else
$qrytxt = $myquery . " and $nomecampouser = '{$uname}' and $nomecampopassword = password('" . $pwd . "') and id = {$valoreidut}";
$qry = esegui_query($qrytxt);
if (numrec($qry) <= 0)
{
echo "<p style=\"text-align:center;fontweight:bold;\">Utente non autorizzato<br /><br /><a href=\"{$paginaindice}{$querystr}\">Torna Indietro</a>\n";
echo "</body>\n";
echo "</html>";
return false;
}
$firstloop = true;
$aree = "";
$autenticato = false;
while ($rec = getrecord($qry))
{
if($firstloop)
{
$aree .= $rec["idarea"];
$firstloop = false;
}
else
$aree .= "," . $rec["idarea"];
if(($rec["idarea"] == $area_autenticare) && (($rec["amministratore"] == $necessario_amministratore) || ($rec["amministratore"] == 1)))
{
$_SESSION["aut"] = 1;
$_SESSION["amministratore"][$rec["idarea"]] = $rec["amministratore"];
if($nomecampoid == "")
$_SESSION["idut"] = $rec["id"];
else
$_SESSION["idut"] = $rec[$nomecampoid];
$autenticato = true;
}
}
if($autenticato)
{
$_SESSION["area"] = $aree;
return true;
}
else
{
echo "<p style=\"text-align:center;fontweight:bold;\">Utente non autorizzato<br /><br /><a href=\"{$paginaindice}{$querystr}\">Torna Indietro</a>";
echo "</body>";
echo "</html>";
return false;
}
}
elseif(( isset($_SESSION["aut"]) && ($_SESSION["aut"] == 1)) && (isset($_SESSION["area"]) && (strpos($_SESSION["area"],$area_autenticare) !== false)) && (isset($_SESSION["amministratore"]) && (($_SESSION["amministratore"][$area_autenticare] == $necessario_amministratore) || (isset($rec["amministratore"]) && ($rec["amministratore"][$area_autenticare] == 1)))) && (empty($valoreidut) || (isset($_SESSION["idut"]) && ($_SESSION["idut"] == $valoreidut))))
return true;
else
{
?>
<form id="aut" method="post" action=<?PHP echo "\"" . $_SERVER["PHP_SELF"] . $querystr . "\""; ?>>
<table class="mytable31new">
<tr><td colspan="2" class="centrato"><b>Autenticazione utente</b></td></tr>
<tr>
<td style="text-align:right;">Utente:</td><td><input type="text" name="uname" /></td>
</tr>
<tr>
<td style="text-align:right;">Password:</td> <td><input type="password" name="pwd" /></td>
</tr>
<tr>
<td colspan="2" class="centrato"><input type="submit" name="invia" value="ACCEDI" /></td>
</tr>
</table>
</form>
</body>
</html>
<?PHP
}
}
/* funzione con ldap
function autentica_ut3($myquery = "",$area_autenticare = "news",$necessario_amministratore = 0,$paginaindice = "../index.php",$querystr = "",$valoreidut = 0,$nomecampouser="username",$nomecampopassword="password",$nomecampoid = "")
{
if (isset($_POST["pwd"]) && isset($_POST["uname"]))
{
if((strpos($_POST["pwd"],"'") !== false) || (strpos($_POST["uname"],"'") !== false))
{
echo "<p style=\"text-align:center;fontweight:bold;\">Utente non autorizzato<br /><br /><a href=\"{$paginaindice}{$querystr}\">Torna Indietro</a>\n";
echo "</body>\n";
echo "</html>";
return false;
}
if((strpos($_POST["pwd"],"\"") !== false) || (strpos($_POST["uname"],"\"") !== false))
{
echo "<p style=\"text-align:center;fontweight:bold;\">Utente non autorizzato<br /><br /><a href=\"{$paginaindice}{$querystr}\">Torna Indietro</a>\n";
echo "</body>\n";
echo "</html>";
return false;
}
if(empty($valoreidut))
$qrytxt = $myquery . " and $nomecampouser = '{$_POST["uname"]}'";
else
$qrytxt = $myquery . " and $nomecampouser = '{$_POST["uname"]}' and id = {$valoreidut}";
$qry = esegui_query($qrytxt);
if (numrec($qry) <= 0)
{
echo "<p style=\"text-align:center;fontweight:bold;\">Utente non autorizzato<br /><br /><a href=\"{$paginaindice}{$querystr}\">Torna Indietro</a>\n";
echo "</body>\n";
echo "</html>";
return false;
}
if (!check_auth_ldap($_POST["uname"],$_POST["pwd"]))
{
echo "<p style=\"text-align:center;fontweight:bold;\">Utente non autorizzato<br /><br /><a href=\"{$paginaindice}{$querystr}\">Torna Indietro</a>\n";
echo "</body>\n";
echo "</html>";
return false;
}
$firstloop = true;
$aree = "";
$autenticato = false;
while ($rec = getrecord($qry))
{
if($firstloop)
{
$aree .= $rec["idarea"];
$firstloop = false;
}
else
$aree .= "," . $rec["idarea"];
if(($rec["idarea"] == $area_autenticare) && (($rec["amministratore"] == $necessario_amministratore) || ($rec["amministratore"] == 1)))
{
$_SESSION["aut"] = 1;
$_SESSION["amministratore"][$rec["idarea"]] = $rec["amministratore"];
if($nomecampoid == "")
$_SESSION["idut"] = $rec["id"];
else
$_SESSION["idut"] = $rec[$nomecampoid];
$autenticato = true;
}
}
if($autenticato)
{
$_SESSION["area"] = $aree;
return true;
}
else
{
echo "<p style=\"text-align:center;fontweight:bold;\">Utente non autorizzato<br /><br /><a href=\"{$paginaindice}{$querystr}\">Torna Indietro</a>";
echo "</body>";
echo "</html>";
return false;
}
}
elseif(( isset($_SESSION["aut"]) && ($_SESSION["aut"] == 1)) && (isset($_SESSION["area"]) && (strpos($_SESSION["area"],$area_autenticare) !== false)) && (isset($_SESSION["amministratore"]) && (($_SESSION["amministratore"][$area_autenticare] == $necessario_amministratore) || (isset($rec["amministratore"]) && ($rec["amministratore"][$area_autenticare] == 1)))) && (empty($valoreidut) || (isset($_SESSION["idut"]) && ($_SESSION["idut"] == $valoreidut))))
return true;
else
{
?>
<form id="aut" method="post" action=<?PHP echo "\"" . $_SERVER["PHP_SELF"] . $querystr . "\""; ?>>
<table class="mytable31new">
<tr><td colspan="2" class="centrato"><b>Autenticazione utente</b></td></tr>
<tr>
<td style="text-align:right;">Utente:</td><td><input type="text" name="uname" /></td>
</tr>
<tr>
<td style="text-align:right;">Password:</td> <td><input type="password" name="pwd" /></td>
</tr>
<tr>
<td colspan="2" class="centrato"><input type="submit" name="invia" value="ACCEDI" /></td>
</tr>
</table>
</form>
</body>
</html>
<?PHP
}
}
*/
?>
|
Swift | UTF-8 | 4,671 | 2.625 | 3 | [
"MIT"
] | permissive | //
// ProjectName : SmartNews-Like-Menu
// File Name : TabMenu.swift
// Created Date : 2020/11/24
//
// Copyright © 2019-2020 KC Apps. All rights reserved.
//
import UIKit
protocol TabMenuViewDelete: class {
func tabMenuView(_ tabMenuView: TabMenuView, didChangePage id: Int)
}
final class TabMenuView: UIView {
fileprivate var viewBorder: UIView!
fileprivate var scrollView: UIScrollView!
fileprivate var stackView: UIStackView!
fileprivate var currentMenuButton: TabMenuButton! {
didSet {
//現在のメニューボタン画面内に表示される様にスクロール
let offsetX = -scrollView.frame.width / 2 + currentMenuButton.frame.origin.x + currentMenuButton.frame.width / 2
if offsetX > 0 && offsetX < scrollView.contentSize.width - scrollView.frame.width {
let offset = CGPoint(x: offsetX, y: 0)
scrollView.setContentOffset(offset, animated: true)
} else if offsetX < 0 {
let offset = CGPoint(x: 0, y: 0)
scrollView.setContentOffset(offset, animated: true)
} else if offsetX > scrollView.contentSize.width - scrollView.frame.width {
let offset = CGPoint(x: scrollView.contentSize.width - scrollView.frame.width, y: 0)
scrollView.setContentOffset(offset, animated: true)
}
//仕切り線の色を現在のメニューボタンの色に変更
viewBorder.backgroundColor = currentMenuButton.backgroundColor
}
}
weak var delegate: TabMenuViewDelete?
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setup()
}
func setItems(_ items: [HomePageItem]) {
if items.isEmpty {
fatalError()
}
var count = 0
for item in items {
let button = TabMenuButton(item)
button.tag = item.id
button.addTarget(self, action: #selector(self.onTouchMenu(_:)), for: .touchUpInside)
stackView.addArrangedSubview(button)
button.translatesAutoresizingMaskIntoConstraints = false
button.heightConstraint = button.heightAnchor.constraint(equalTo: self.heightAnchor, multiplier: 0.8)
button.heightConstraint.isActive = true
count += 1
}
changePage(items.first!.id)
}
func changePage(_ id: Int) {
for view in stackView.arrangedSubviews {
if let button = view as? TabMenuButton {
if button.tag == id {
button.heightConstraint.isActive = false
button.heightConstraint = button.heightAnchor.constraint(equalTo: self.heightAnchor, multiplier: 0.9)
button.heightConstraint.isActive = true
currentMenuButton = button
} else {
button.heightConstraint.isActive = false
button.heightConstraint = button.heightAnchor.constraint(equalTo: self.heightAnchor, multiplier: 0.8)
button.heightConstraint.isActive = true
}
}
}
}
fileprivate func setup() {
viewBorder = UIView(frame: .zero)
viewBorder.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(viewBorder)
viewBorder.heightAnchor.constraint(equalToConstant: 2).isActive = true
viewBorder.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
viewBorder.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true
viewBorder.trailingAnchor.constraint(equalTo: self.trailingAnchor).isActive = true
scrollView = UIScrollView(frame: .zero)
scrollView.showsHorizontalScrollIndicator = false
scrollView.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(scrollView)
scrollView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
scrollView.bottomAnchor.constraint(equalTo: viewBorder.topAnchor).isActive = true
scrollView.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true
scrollView.trailingAnchor.constraint(equalTo: self.trailingAnchor).isActive = true
stackView = UIStackView(frame: .zero)
stackView.axis = .horizontal
stackView.alignment = .bottom
stackView.distribution = .fill
stackView.spacing = 0
stackView.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(stackView)
stackView.heightAnchor.constraint(equalTo: scrollView.heightAnchor, multiplier: 1).isActive = true
stackView.topAnchor.constraint(equalTo: scrollView.topAnchor).isActive = true
stackView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor).isActive = true
stackView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor).isActive = true
stackView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor).isActive = true
}
@objc fileprivate func onTouchMenu(_ sender: TabMenuButton) {
changePage(sender.tag)
delegate?.tabMenuView(self, didChangePage: sender.tag)
}
}
|
C# | UTF-8 | 693 | 2.90625 | 3 | [] | no_license | void Main()
{
var list = new List<DateTime>
{
new DateTime(2005, 10, 11),
new DateTime(2009, 3, 4),
new DateTime(2010, 5, 8),
new DateTime(2010, 8, 10),
DateTime.Now,
new DateTime(2010, 4, 8)
};
var result= Enumerable.Range(list.Min (l => l.Year), list.Max (l => l.Year) - list.Min (l => l.Year)).
SelectMany (e => Enumerable.Range(1, 12).Select (en => new DateTime(e, en, 1))).
Except(list.Select(o => new DateTime(o.Year, o.Month, 1))).
Where (o => o.Date > list.Min (l => l.Date) && o.Date < list.Max (l => new DateTime(l.Year, l.Month, 1)));
}
|
C++ | UTF-8 | 6,068 | 3.1875 | 3 | [] | no_license | // ---------------------------------------------------------------------------------------------------------
//
// Spline
//
// ---------------------------------------------------------------------------------------------------------
#pragma once
#include "Standard/api.h"
#include "Math.h"
#include "Dirty.h"
#include <vector>
// HermiteSpline
class HermiteSpline
{
public:
HermiteSpline() {};
HermiteSpline(const Point3& start, const Point3& end, const Point3& startTangent, const Point3& endTangent) :
m_start(start),
m_end(end),
m_startTangent(startTangent),
m_endTangent(endTangent)
{
}
const Point3& start() const { return m_start; }
const Point3& end() const { return m_end; }
const Point3& startTangent() const { return m_startTangent; }
const Point3& endTangent() const { return m_endTangent; }
Point3 operator()(float t) const
{
float t2 = t * t;
float t3 = t2 * t;
float h1 = (2.0f * t3) - (3.0f * t2) + 1;
float h2 = (-2.0f * t3) + (3.0f * t2);
float h3 = t3 - (2.0f * t2) + t;
float h4 = t3 - t2;
return h1 * m_start + h2 * m_end + h3 * m_startTangent + h4 * m_endTangent;
}
Point3 derivative(float t) const
{
float t2 = t * t;
float h1 = (6.0f * t2) - (6.0f * t);
float h2 = (6.0f * t) - (6.0f * t2);
float h3 = (3.0f * t2) - (4.0f * t) + 1;
float h4 = (3.0f * t2) - (2.0f * t);
return h1 * m_start + h2 * m_end + h3 * m_startTangent + h4 * m_endTangent;
}
float inverse(float s) const
{
int steps = 100;
float epsilon = 0.001f;
float t = s / arcLength();
float lastT = 0.5f;
// newton root finder
do
{
float f = arcLength(0, t) - s;
float df = derivative(t).length();
t = t - (f / df);
if (fabs(t - lastT) < epsilon)
break;
lastT = t;
steps--;
}
while (1 && steps);
return t;
}
float arcLength() const
{
if (m_arcLength.dirty())
{
m_arcLength = arcLength(0, 1);
}
return *m_arcLength;
}
float arcLength(float t0, float t1) const
{
float length = 0;
// simple euler integration
int steps = 100;
float delta = (t1 - t0) / steps;
float t = t0;
for (int i = 0; i < steps; i++)
{
length += (derivative(t) * delta).length();
t += delta;
}
return length;
}
protected:
Point3 m_start;
Point3 m_end;
Point3 m_startTangent;
Point3 m_endTangent;
mutable Dirty<float> m_arcLength;
};
// CatmullRomSpline
class CatmullRomSpline : public HermiteSpline
{
public:
CatmullRomSpline() {};
CatmullRomSpline(const Point3& start, const Point3& end, const Point3& beforeStart, const Point3& afterEnd) :
HermiteSpline(start, end, 0.5f * (end - beforeStart), 0.5f * (afterEnd - end))
{
}
};
// SplinePath
class SplinePath
{
public:
SplinePath() :
m_totalLength(0)
{
}
void add(const Point3& p)
{
m_points.push_back(p);
updateSplines();
}
const Point3& at(int idx) const
{
return m_points[idx];
}
int pointSize() const
{
return m_points.size();
}
int splineSize() const
{
return m_points.size() - 1;
}
Point3 eval(float t) const
{
if (!m_totalLength)
return Point3(0,0,0);
// get the spline that the point is on at time t
clamp(t);
float curDistance = m_totalLength * t;
float distance = curDistance;
int idx = 0;
for (uint i = 0; i < m_lengths.size(); i++)
{
distance -= m_lengths[i];
if (distance < 0)
{
idx = i;
distance += m_lengths[idx]; // distance is now the remaining distance in this spline
break;
}
}
return evalSpline(idx, distance / (m_lengths[idx]));
}
Point3 evalArc(float t) const
{
if (!m_totalLength)
return Point3(0,0,0);
// get the spline that the point is on at time t
clamp(t);
float curDistance = m_totalLength * t;
float distance = curDistance;
int idx = 0;
for (uint i = 0; i < m_lengths.size(); i++)
{
distance -= m_lengths[i];
if (distance < 0)
{
idx = i;
distance += m_lengths[idx]; // distance is now the remaining distance in this spline
break;
}
}
return evalSplineArc(idx, distance);
}
float arcLength() const
{
return m_totalLength;
}
protected:
// get a spline index from a time
int getIdx(float& t)
{
return 0;
}
// gets the time for the current spline
float getSplineTime(float t, int idx)
{
return (t * (m_points.size() - 1)) - (t * idx);
}
// generate splines when a point is added
void updateSplines()
{
if (m_points.size() > 1)
{
int newIdx = m_points.size() - 2;
createSpline(newIdx);
float length = evalArcLength(newIdx);
m_lengths.push_back(length);
m_totalLength += length;
}
}
// overloadable functions
virtual void clearSplines()
{
// overload
}
// create a spline starting a the point with index 'idx'
virtual void createSpline(int idx)
{
// overload
}
virtual Point3 evalSpline(int idx, float t) const
{
// overload
return Point3(0,0,0);
}
virtual Point3 evalSplineArc(int idx, float d) const
{
// overload
return Point3(0,0,0);
}
virtual float evalArcLength(int idx)
{
// overload
return 0;
}
float m_totalLength;
std::vector<float> m_lengths;
std::vector<Point3> m_points;
};
// CatmullRomPath
class CatmullRomPath : public SplinePath
{
protected:
virtual void clearSplines()
{
m_splines.clear();
}
virtual void createSpline(int idx)
{
if ((int)m_splines.size() - 1 < idx)
m_splines.resize(idx + 1);
int preIdx = idx - 1;
int endIdx = idx + 1;
int postIdx = idx + 2;
clamp(preIdx, 0, (int)m_points.size() - 1);
clamp(endIdx, 0, (int)m_points.size() - 1);
clamp(postIdx, 0, (int)m_points.size() - 1);
m_splines[idx] = CatmullRomSpline(m_points[idx], m_points[endIdx], m_points[preIdx], m_points[postIdx]);
}
virtual Point3 evalSpline(int idx, float t) const
{
const CatmullRomSpline& s = m_splines[idx];
return s(t);
}
virtual Point3 evalSplineArc(int idx, float d) const
{
const CatmullRomSpline& s = m_splines[idx];
return s(s.inverse(d));
}
virtual float evalArcLength(int idx)
{
return m_splines[idx].arcLength();
}
std::vector<CatmullRomSpline> m_splines;
};
|
Python | UTF-8 | 1,010 | 2.546875 | 3 | [] | no_license | from django.db import models
class VisibleManager(models.Manager):
def get_query_set(self):
kwargs = {"visible": True}
return super(VisibleManager, self).get_query_set().filter(**kwargs)
class Location(models.Model):
class Meta:
abstract = True
ordering = ('name',)
name = models.CharField(u'Регион', max_length=255)
visible = models.BooleanField(u'Показывать?', default=True)
allobjects = models.Manager()
objects = VisibleManager()
def __unicode__(self):
return self.name
class Region(Location):
"""Регионы и области"""
class Meta:
verbose_name = u'Регион'
verbose_name_plural = u'Регионы'
class City(Location):
"""Города"""
region = models.ForeignKey(Region,
verbose_name=u"Регион", on_delete=models.CASCADE)
class Meta:
verbose_name = u'Город'
verbose_name_plural = u'Города'
|
Java | UTF-8 | 547 | 1.796875 | 2 | [] | no_license | package com.example.demo.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Data;
import javax.persistence.*;
import java.sql.Timestamp;
@Data
@Entity
public class AppLike {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne
private AppUser user;
@ManyToOne
@JsonIgnoreProperties("likes")
// @JsonIgnore
private Post post;
private String notification;
private Timestamp createAt;
}
|
C | UTF-8 | 1,837 | 4.125 | 4 | [] | no_license | /*Alex Kastanek
Count Digits
This program counts how many of each digit are in a user-made multidimensional array.*/
#include <stdio.h>
int read_row(int rowCounter, int colCounter) {
int val;
if (colCounter == 0) {
printf("Enter row %d of array: ", rowCounter);
}
scanf("%d", &val);
return val;
}
int check_input(int input) {
if (input > 9 || input < 0) {
return 0;
} else return 1;
}
int compute_row_count(int val, int count[val]) {
count[val] = count[val] + 1;
return count[val];
}
int print_total_count (int val, int count[val]) {
if (count[val] == 1) {
printf("Digit %d occurs %d time\n", val, count[val]);
} else {
printf("Digit %d occurs %d times\n", val, count[val]);
}
return 0;
}
int main(void) {
int n = 0, m = 0, rowCounter = 0, colCounter = 0, a[n][m], i = 0, j = 0, currentValue;
int digitCount[9] = {0};
printf("Enter the size of your array: ");
scanf("%d %d", &n, &m);
for (rowCounter = 0; rowCounter < n; rowCounter++) {
for (colCounter = 0; colCounter < m; colCounter++) {
a[rowCounter][colCounter] = read_row(rowCounter, colCounter);
currentValue = a[rowCounter][colCounter];
if (check_input(currentValue) == 0) {
for (colCounter; colCounter < m; colCounter++) {
a[rowCounter][colCounter] = 0;
}
printf("Values outside of range.\n");
rowCounter--;
} else {
digitCount[currentValue] = compute_row_count(currentValue, digitCount);
}
//printf("%3d", a[rowCounter][colCounter]); debugging
}
}
/*debugging:
printf("%d,%d\n", n, m);
printf("%d,%d\n", rowCounter, colCounter);*/
rowCounter = 0;
colCounter = 0;
printf("\n");
printf("Total count for each digit:\n");
printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");
for (i = 0; i < 10; i++) {
print_total_count(i, digitCount);
}
printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");
return 0;
}
|
Java | UTF-8 | 1,215 | 1.898438 | 2 | [] | no_license |
package gov.va.oit.vistaevolution.mailman.ws.xmxapig.endpoints.interfaces.jaxws;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import gov.va.oit.vistaevolution.mailman.ws.xmxapig.model.XMXAPIGAddMbrsRequest;
@XmlRootElement(name = "XMXAPIGAddMbrs", namespace = "http://vistaevolution.va.gov")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "XMXAPIGAddMbrs", namespace = "http://vistaevolution.va.gov")
public class AddMbrs {
@XmlElement(name = "XMXAPIGAddMbrsRequest", namespace = "")
private XMXAPIGAddMbrsRequest xmxapigAddMbrsRequest;
/**
*
* @return
* returns XMXAPIGAddMbrsRequest
*/
public XMXAPIGAddMbrsRequest getXmxapigAddMbrsRequest() {
return this.xmxapigAddMbrsRequest;
}
/**
*
* @param xmxapigAddMbrsRequest
* the value for the xmxapigAddMbrsRequest property
*/
public void setXmxapigAddMbrsRequest(XMXAPIGAddMbrsRequest xmxapigAddMbrsRequest) {
this.xmxapigAddMbrsRequest = xmxapigAddMbrsRequest;
}
}
|
Python | UTF-8 | 3,913 | 2.671875 | 3 | [
"Apache-2.0"
] | permissive | # coding: utf-8
# プロセス分散
# pip install futures
import time
from concurrent import futures
import os
from multiprocessing import Manager
import logging
logging.basicConfig(level=logging.DEBUG,
format='[%(levelname)s] time:%(created).8f pid:%(process)d pn:%(processName)-10s tid:%(thread)d tn:%(threadName)-10s fn:%(funcName)-10s %(message)s',
)
'''
ここはプロセスで実行される
SHARED_VARIABLE['SOMETHING1_READY']=True であるうちは実行を続ける
'''
def do_something1():
logging.debug("enter")
SHARED_VARIABLE['SOMETHING1_READY']=True
####################
# ループ実行
####################
execute_time=0.0
execute_clock_time=0.0
count = 0
while SHARED_VARIABLE['SOMETHING1_READY']:
start_time,clock_time=time.time(),time.clock()
SHARED_VARIABLE['SOMETHING1_VALUE'] += 1
execute_time += time.time() - start_time
execute_clock_time += time.clock() - clock_time
count+=1
logging.debug("value:%s" % (str(SHARED_VARIABLE['SOMETHING1_VALUE'])))
time.sleep(0.1)
logging.debug("ave time:%.8f ave clock:%.8f" % (execute_time/count,execute_clock_time/count))
return
'''
ここはプロセスで実行される
SHARED_VARIABLE['SOMETHING2_READY']=True であるうちは実行を続ける
'''
def do_something2():
logging.debug("enter")
SHARED_VARIABLE['SOMETHING2_READY']=True
####################
# ループ実行
####################
execute_time=0.0
execute_clock_time=0.0
count = 0
while SHARED_VARIABLE['SOMETHING2_READY']:
start_time,clock_time=time.time(),time.clock()
SHARED_VARIABLE['SOMETHING2_VALUE'] = SHARED_VARIABLE['SOMETHING1_VALUE'] << 1 # SHARED_VARIABLE['SOMETHING1_VALUE'] * 2
execute_time += time.time() - start_time
execute_clock_time += time.clock() - clock_time
count+=1
logging.debug("value:%s" % (str(SHARED_VARIABLE['SOMETHING2_VALUE'])))
time.sleep(0.1)
logging.debug("ave time:%.8f ave clock:%.8f" % (execute_time/count,execute_clock_time/count))
return
'''
ここはプロセスで実行される
RUNNING_SEC後に各プロセスが停止するようにBOOL型変数を書き換える
'''
def do_stop():
logging.debug("enter")
####################
# ループ実行
####################
start_time = time.time()
RUNNING_SEC = 10
time.sleep(RUNNING_SEC)
SHARED_VARIABLE['SOMETHING1_READY']=False
SHARED_VARIABLE['SOMETHING2_READY']=False
return
'''
process pattern
'''
SHARED_VARIABLE=Manager().dict()
SHARED_VARIABLE['SOMETHING1_READY']=False
SHARED_VARIABLE['SOMETHING2_READY']=False
SHARED_VARIABLE['SOMETHING1_VALUE']=0
SHARED_VARIABLE['SOMETHING2_VALUE']=0
'''
プロセスによる実行関数の振り分け定義
'''
PROCESS_LIST=['do_something1','do_something2','do_stop']
def do_process(target):
if target == 'do_something1':
do_something1()
return "end do_something1"
if target == 'do_something2':
do_something2()
return "end do_something2"
if target == 'do_stop':
do_stop()
return "end do_stop"
'''
メイン処理を行う部分
・メインスレッド(ここ)
・スレッド1(concurrent.futures)
・スレッド2(concurrent.futures)
・制御スレッド(concurrent.futures)
'''
def do_main():
try:
with futures.ProcessPoolExecutor(max_workers=len(PROCESS_LIST)) as executer:
mappings = {executer.submit(do_process, pname): pname for pname in PROCESS_LIST}
for i in futures.as_completed(mappings):
target = mappings[i]
result = i.result()
print(result)
except Exception as e:
print('error! executer failed.')
print(str(e))
finally:
print("executer end")
return
do_main()
|
Java | UTF-8 | 2,484 | 3.265625 | 3 | [] | no_license | import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
/*https://www.hackerrank.com/challenges/ctci-bfs-shortest-reach/problem*/
public class ShortestPath_BFS {
public static class Graph {
ArrayList<HashSet<Integer>> edges;
int n;
public Graph(int size) {
this.n=size;
this.edges = new ArrayList<HashSet<Integer>>();
for(int i = 0; i < this.n; i++)
this.edges.add(new HashSet<Integer>());
}
public void addEdge(int first, int second) {
this.edges.get(first).add(second);
this.edges.get(second).add(first);
}
public int[] shortestReach(int s) {
// 0 indexed
int[] paths=new int[this.n];
Arrays.fill(paths,-1);
paths[s]=0;
Queue<Integer> q= new LinkedList<Integer>();
q.add(s);
while(!q.isEmpty())
{
int u=q.poll();
for(int v:this.edges.get(u))
{
if(paths[v]==-1)
{
paths[v]=paths[u]+6;
q.add(v);
}
}
}
return paths;
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int queries = scanner.nextInt();
for (int t = 0; t < queries; t++) {
// Create a graph of size n where each edge weight is 6:
Graph graph = new Graph(scanner.nextInt());
int m = scanner.nextInt();
// read and set edges
for (int i = 0; i < m; i++) {
int u = scanner.nextInt() - 1;
int v = scanner.nextInt() - 1;
// add each edge to the graph
graph.addEdge(u, v);
}
// Find shortest reach from node s
int startId = scanner.nextInt() - 1;
int[] distances = graph.shortestReach(startId);
for (int i = 0; i < distances.length; i++) {
if (i != startId) {
System.out.print(distances[i]);
System.out.print(" ");
}
}
System.out.println();
}
scanner.close();
}
}
|
Python | UTF-8 | 1,919 | 2.578125 | 3 | [] | no_license | from collections import defaultdict
from datetime import datetime
from django.db import models
from django.http import QueryDict
class Form:
def __init__(self, model=None):
self._model = model
self._converter = defaultdict(lambda: lambda value: value, {
models.CharField: lambda value: str(value),
models.BooleanField: lambda value: value in ['true', 'True', 'y', 'Y', 1, True],
models.IntegerField: lambda value: int(value),
models.DateTimeField: lambda value: value if isinstance(value, datetime) else datetime.fromisoformat(value)
})
@classmethod
def for_model(cls, model):
instance = cls(model)
return instance
def with_request(self, request):
if request.method == 'POST':
self.__dict__.update({
key: value[0]
for key, value
in request.POST.lists()
})
else:
self.__dict__.update({
key: value
for key, value
in QueryDict(request.body)
})
if self._model:
self._convert_types()
return self
def _convert_types(self):
definitions = {
definition.name: definition.__class__
for definition
in self._model._meta.fields
}
for key, value in self.__dict__.items():
if not key.startswith('_'):
if key in definitions:
try:
#print(f"Converting {key}")
self.__dict__[key] = self._converter[definitions[key]](value)
except Exception as e:
print(f"Failed to convert value {self.__dict__[key]} from type {type(self.__dict__[key])} to {definitions[key]} in form construction")
def __getattr__(self, key):
return None
|
Java | UTF-8 | 1,274 | 2.015625 | 2 | [] | no_license | package com.hosiang.dev.controller;
import com.hosiang.dev.bean.Order;
import com.hosiang.dev.bean.UserBean;
import com.hosiang.dev.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;
/**
* Blog:http://www.hosiang.cn
*
* @author Howe Hsiang
*
*/
@Controller
/*@RequestMapping("/libra/user")*/
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/userlist")
public String userList() {
return "user/userList";
}
@GetMapping("/usercollect")
public String userCollect() {
return "user/userCollect";
}
/**
* 获取全部
*
* @return
*/
@PostMapping("/findAll")
public @ResponseBody Object findAll() {
return userService.findAll();
}
/**
* 持久化
*
* @param userBean
* @return
*/
@PostMapping("/save")
public @ResponseBody Map<String, Object> save(@RequestBody UserBean userBean) {
Map<String, Object> result = new HashMap<>();
try {
userService.save(userBean);
result.put("success", true);
} catch (Exception e) {
result.put("success", false);
}
return result;
}
}
|
C++ | UTF-8 | 1,724 | 2.640625 | 3 | [] | no_license | #include "pch.h"
#include "nvsg/DAL.h"
namespace nvsg {
DALServer::DALServer ()
{
m_hDALNext = 0;
}
DALServer::~DALServer ()
{
}
HDAL
DALServer::storeDALData (HDAL hDAL, unsigned int dataID, DALData* data)
{
m_lock.lockExclusive ();
if (hDAL == HDAL_INVALID)
{
std::multimap<unsigned int, DALData *> map;
std::pair<unsigned int, DALData *> pair (dataID,data);
map.insert (pair);
std::pair<HDAL,std::multimap<unsigned int,DALData *>> np (m_hDALNext,map);
m_DALMap.insert (np);
nvsg::HDAL ret = m_hDALNext;
m_hDALNext ++;
return ret;
}
std::map<HDAL, std::multimap<unsigned int , DALData *>>::iterator it = m_DALMap.find (hDAL);
if (it == m_DALMap.end())
{
// assert here
}
std::multimap<unsigned int,DALData*> mulmap =(*it).second;
mulmap.insert (std::pair<unsigned int, DALData*>(dataID,data));
m_lock.unlockExclusive ();
return hDAL;
}
bool
DALServer::getDALData (HDAL hDAL, unsigned int dataID,std::vector<DALData*>& data) const
{
m_lock.lockShared ();
if (hDAL == HDAL_INVALID)
{
return false;
}
std::map<HDAL, std::multimap<unsigned int , DALData *>>::const_iterator it= m_DALMap.find(hDAL); // = m_DALMap.find (hDAL);
if (it == m_DALMap.end())
{
return false;
}
std::multimap<unsigned int,DALData*> mulmap =(*it).second;
std::multimap<unsigned int,DALData*>::const_iterator ittt = mulmap.find (dataID);
if (ittt == mulmap.end())
{
return false;
}
data.push_back (ittt->second);
m_lock.unlockShared ();
return true;
}
void DALServer::releaseDALData(HDAL hDAL, DALDataCreator * creator, unsigned int dataID) {}
void DALServer::deleteDALData(DALData * data) {}
const HDAL HDAL_INVALID = 0xfffffff;
} |
C# | UTF-8 | 879 | 2.6875 | 3 | [
"MIT"
] | permissive | namespace UniversityStudentSystem.Data.Models
{
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Common;
using CommonModels;
public class Category : BaseModel<int>
{
private ICollection<ForumPost> forumPosts;
public Category()
{
this.forumPosts = new HashSet<ForumPost>();
}
[Required]
[Index(IsUnique = true)]
[MinLength(ModelConstants.NameMinLength)]
[MaxLength(ModelConstants.NameMaxLength)]
public string Name { get; set; }
public virtual ICollection<ForumPost> ForumPosts
{
get
{
return forumPosts;
}
set
{
forumPosts = value;
}
}
}
} |
Java | UTF-8 | 1,291 | 3.578125 | 4 | [] | no_license | package easy;
import java.util.HashMap;
/**
* @author 喻浩
* @create 2020-03-13-9:51
*/
public class majority_element_169 {
/**
* question url:https://leetcode-cn.com/problems/majority-element/
* question context :
* 给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。
*
* 你可以假设数组是非空的,并且给定的数组总是存在多数元素。
*/
class Solution {
public int majorityElement(int[] nums) {
int num = nums.length/2;
HashMap<Integer,Integer> map = new HashMap<>();
for (int i : nums) {
if (!map.containsKey(i)){
map.put(i, num);
}else {
map.put(i, map.get(i)-1);
}
if (map.get(i) <= 0){
return i;
}
}
return -1;
}
}
public static void main(String[] args) {
int[] nums = {2,2,1,1,1,2,2};
// int[] nums = {3,2,3};
majority_element_169 majority_element_169 = new majority_element_169();
System.out.println(majority_element_169.new Solution().majorityElement(nums));
}
}
|
C | UTF-8 | 585 | 4.09375 | 4 | [] | no_license | /*4.Write a program which accept two strings from user and concat
alternate characters from second string at the end of first string.
Input : “Marvellous”
“Infosystems”
Output : MarvellousIfsses
*/
#include<stdio.h>
void StrConcat(char *str1,char *str2)
{
while(*str1!='\0')
{
str1++;
}
str1--;
while(*str2!='\0')
{
*str1=*str2;
str2=str2+2;
str1++;
}
}
int main()
{
char Arr[40];
char Brr[40];
printf("Enter the string:");
scanf("%s",Arr);
printf("Enter the 2nd string:");
scanf("%s",Brr);
StrConcat(Arr,Brr);
printf("%s",Arr);
return 0;
}
|
C++ | UTF-8 | 575 | 3.015625 | 3 | [] | no_license | #include <stdio.h>
#include <locale.h>
#include <math.h>
int main()
{
setlocale(LC_ALL, "Rus");
int A, B;
printf("Введите двузначное число: ");
scanf_s("%d", &A);
if (((A >= 10) && (A < 100)) || ((A <= -10) && (A > -100))) {
B = A / 10;
A = A - B * 10;
A = A * 10 + B;
printf("При переставлении цифр местами получено число %d", A);
}
else {
printf("Необходимо ввести двузначное число");
}
return 0;
} |
Python | UTF-8 | 4,803 | 2.546875 | 3 | [] | no_license | # Todo check timers of isValid()
import sys
import logging as log
from PyQt5 import QtWidgets, QtCore
from .raspberry_pi import MockPi
from .gui import Ui_MainWindow
def setup_logging():
log.basicConfig(
format="[%(asctime)s] [%(levelname)-8s] :: %(message)s",
level=log.DEBUG,
datefmt="%Y-%m-%d %H:%M:%S",
stream=sys.stdout
)
class Timer(QtCore.QElapsedTimer):
def __init__(self):
super().__init__()
self.restart()
def secs_elapsed(self):
return int(self.elapsed()/1000)
class Game:
def __init__(self, pi):
log.info('Game Start')
self.pi = pi
self.controlling_team = None
self.team_change_in = Timer()
self.game_end_in = Timer()
self.red_held = False
self.blue_held = False
self.both_held = False
self.red_score = 0
self.blue_score = 0
self.red_display = 0
self.blue_display = 0
self.red_current = Timer()
self.red_current.invalidate()
self.blue_current = Timer()
self.blue_current.invalidate()
def tick(self):
self.button_check()
self.update_score()
return [self.red_display, self.blue_display]
def change_team(self, team):
log.info('Change team to {}'.format(team))
if team == 'red':
if self.blue_current.isValid() and self.blue_current.secs_elapsed() > 0:
self.blue_score += self.blue_current.secs_elapsed()
self.controlling_team = team
self.red_current.restart()
elif team == 'blue':
if self.red_current.isValid() and self.red_current.secs_elapsed() > 0:
self.red_score += self.red_current.secs_elapsed()
self.controlling_team = team
self.blue_current.restart()
def end(self):
log.info('Game End')
self.pi.cleanup()
sys.exit()
def update_score(self):
if self.controlling_team == 'red':
self.red_display = self.red_score + self.red_current.secs_elapsed()
self.blue_display = self.blue_score
elif self.controlling_team == 'blue':
self.blue_display = self.blue_score + self.blue_current.secs_elapsed()
self.red_display = self.red_score
else:
self.red_display, self.blue_display = self.red_score, self.blue_score
def button_check(self):
if self.pi.red_pressed() and self.pi.blue_pressed():
self.both_buttons_pressed()
elif self.pi.red_pressed():
self.red_pressed()
elif self.pi.blue_pressed():
self.blue_pressed()
else:
self.none_pressed()
# ---- Button Pressed States ---- #
def both_buttons_pressed(self):
if self.both_held:
timer_value = self.game_end_in.secs_elapsed()
if timer_value > 4:
self.end()
else:
self.both_held = True
self.game_end_in.start()
def red_pressed(self):
if self.controlling_team == 'red':
log.info('Red team already has control.')
else:
if self.red_held:
timer_value = self.team_change_in.secs_elapsed()
if timer_value >= 4:
self.change_team('red')
else:
self.red_held = True
self.team_change_in.start()
def blue_pressed(self):
if self.controlling_team == 'blue':
log.info('Blue team already has control.')
else:
if self.blue_held:
timer_value = self.team_change_in.secs_elapsed()
if timer_value >= 4:
self.change_team('blue')
else:
self.blue_held = True
self.team_change_in.start()
def none_pressed(self):
self.red_held = False
self.blue_held = False
self.both_held = False
self.game_end_in.invalidate()
self.team_change_in.invalidate()
class GUI(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self):
super().__init__()
self.pi = MockPi(self)
self.game = Game(self.pi)
self.tick_rate = QtCore.QTimer(self)
self.tick_rate.setInterval(250)
self.tick_rate.timeout.connect(self.tick)
self.tick_rate.start()
self.setupUi(self)
self.show()
def tick(self):
info = self.game.tick()
self.display(*info)
def display(self, red_score, blue_score):
self.red_team_score_lcd.display(red_score)
self.blue_team_score_lcd.display(blue_score)
def main():
setup_logging()
app = QtWidgets.QApplication(sys.argv)
gui = GUI()
sys.exit(app.exec_())
|
Markdown | UTF-8 | 445 | 2.53125 | 3 | [] | no_license | # sms
Command line tool written in Go that sends an SMS of the given data.
Download:
* [Mac](https://github.com/codeitloadit/sms/blob/master/bin/sms?raw=true)
Environment Variables:
* SMS_DEFAULT_MESSAGE
* SMS_DEFAULT_NUMBER
Usages:
* $ sms "This is a message" 5551234567
* $ sms "This is a message" <- Uses SMS_DEFAULT_NUMBER
* $ sms <- Uses SMS_DEFAULT_MESSAGE and SMS_DEFAULT_NUMBER
* $ pwd | sms
* $ ls | grep test | sms
|
C# | UTF-8 | 2,818 | 2.640625 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using GarmentsERP.Model;
namespace GarmentsERP.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class TrimsGroupsController : ControllerBase
{
private readonly GarmentERPContext _context;
public TrimsGroupsController(GarmentERPContext context)
{
_context = context;
}
// GET: api/TrimsGroups
[HttpGet]
public async Task<ActionResult<IEnumerable<TrimsGroup>>> GetTrimsGroup()
{
return await _context.TrimsGroup.ToListAsync();
}
// GET: api/TrimsGroups/5
[HttpGet("{id}")]
public async Task<ActionResult<TrimsGroup>> GetTrimsGroup(int id)
{
var trimsGroup = await _context.TrimsGroup.FindAsync(id);
if (trimsGroup == null)
{
return NotFound();
}
return trimsGroup;
}
// PUT: api/TrimsGroups/5
[HttpPut("{id}")]
public async Task<IActionResult> PutTrimsGroup(int id, TrimsGroup trimsGroup)
{
if (id != trimsGroup.Id)
{
return BadRequest();
}
_context.Entry(trimsGroup).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!TrimsGroupExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return NoContent();
}
// POST: api/TrimsGroups
[HttpPost]
public async Task<ActionResult<TrimsGroup>> PostTrimsGroup(TrimsGroup trimsGroup)
{
_context.TrimsGroup.Add(trimsGroup);
await _context.SaveChangesAsync();
return CreatedAtAction("GetTrimsGroup", new { id = trimsGroup.Id }, trimsGroup);
}
// DELETE: api/TrimsGroups/5
[HttpDelete("{id}")]
public async Task<ActionResult<TrimsGroup>> DeleteTrimsGroup(int id)
{
var trimsGroup = await _context.TrimsGroup.FindAsync(id);
if (trimsGroup == null)
{
return NotFound();
}
_context.TrimsGroup.Remove(trimsGroup);
await _context.SaveChangesAsync();
return trimsGroup;
}
private bool TrimsGroupExists(int id)
{
return _context.TrimsGroup.Any(e => e.Id == id);
}
}
}
|
Markdown | UTF-8 | 2,135 | 3.265625 | 3 | [] | no_license | # DigitPixels
Applying OpenCV Neural Network to an image to recognize digits.
### Dependencies
To easily compile and run project install following list of dependencies:
- **pkg-config**
- **GNU/Make**
- **OpenCV**
## How does it work?
### Preparing input images
From input image
- Rectangle of Interest is taken
- Gaussian blur filter is applied
- resize to 10x10 is done
- conversion to 32 bit float depth, single channel (**CV_32FC1**) is done on the obtained matrix
Process is visualized by the image below:

### Training data
Each matrix representing learnt digit/character is reshaped to 1x100 size, pushed to the **training data** matrix as single row - number of columns corresponds with the count of input neurons (100). At the same time, on the same row number of training outputs matrix a row containing expected output (for the training data representing the digit) is pushed - matrix 1x10 with zeros on all positions except position representig digit for which data are being inserted. For this position value 1 is set.
Visualization of training input data:

Visualization of training expected outputs:

## Compile and run
### Compile
Clone repository in the command line, change directory to the one containing the repository content and run **make** command.
```shell
git clone https://github.com/adamgic/DigitPixels.git
cd DigitPixels
make
```
### Run
Run passing path to directory containing training set as first argument and name of input image as second argument.
```shell
./DigitRecognizer digits/ inputImage.png
```
You will see output visualization containing excitation diagram for each output neuron depending on the shift of Rectangle of Interest along the input image. It is easy to see that when the rectanlge of interests is containing a digit the neuron representing it is the one excited the most:

The program will print out recognized sequence of digits:
```shell
Digits on image: 98792364539
```
|
Markdown | UTF-8 | 3,588 | 2.578125 | 3 | [] | no_license | # End to End Tests
End to end tests push a number of bags through the system and then verify expected
outcomes in Pharos, S3, and Redis. The tests include ingest, re-ingest, fixity
checking and restoration. (Deletions are not currently included because they require
email confirmations. Integration and manual tests cover deletions.)
## Ingest
Ingest tests should prove that we can ingest at least one BTR bag, plus APTrust
bags with the following storage options:
* Standard
* Glacier-OH
* Glacier-OR
* Glacier-VA
* Glacier-Deep-OH
* Glacier-Deep-OR
* Glacier-Deep-VA
* Wasabi-OR
* Wasabi-VA
After each ingest, we should ensure the following in Pharos:
* Object record was created
* Generic file records were created
* Checksums were created
* PREMIS events were created
* Work item was marked complete
We should ensure the following in Redis:
* All interim processing data from each ingest was deleted
We should ensure the following in S3:
* All generic files exist in the correct preservation buckets
* All generic files have expected metadata
* No interim files remain in the staging bucket
* Original bags have been deleted from the receiving bucket
## Reingest
Tests should re-ingest two bags and test everything listed under the Ingest
section above, ensuring only new and changed files were re-ingested.
## Fixity Check
The fixity tests should test one file from each storage option. The post test
should ensure that the expected PREMIS events were recorded in Pharos.
Fixity tests don't need to check S3, since fixity checks don't change anything
in S3. They don't need to check Redis, since fixity checks don't use Redis.
## Restoration Tests
Restoration tests should restore:
* One BTR bag
* One file from each storage option
* One complete bag from each storage option
Tests should ensure the following in Pharos:
* Each work item is marked complete and successful
Tests should ensure the following in S3:
* Restored files are in the proper restoration bucket and match the URL in the
completed WorkItem
* Restored bag are in the proper restoration bucket and match the URL in the
completed WorkItem
* Restored bags are valid
Restoration tests don't need to check Redis, since restoration workers don't
use Redis.
## Test Files
All files in the e2e directory should have the build tag `// +build e2e`
### e2e_test.go
* Upload all ingest test bags to receiving bucket.
* Start the following workers:
* ingest_posttest.go
* reingest_posttest.go
* fixity_posttest.go
* restoration_posttest.go
* When ingest topic reaches expected finished count, e2e should upload
bags for re-ingest.
* When reingest topic reaches expected finished count, e2e should:
* queue one file from each bag for fixity check
* queue one file from each bag for restoration
* After files have been restored, e2e shoud queue eac of the test bags
for restoration.
* e2e will wait for workers to signal they are done (via NSQ)
* e2e will print test results
### Workers
Worker tests should not use require, since a failure there can shut down the
worker and prevent it from performing further tests.
Each of these workers:
* ingest_posttest.go
* reingest_posttest.go
* fixity_posttest.go
* restoration_posttest.go
Should do the following:
* Test expected outcomes for each object and file
* Tell e2e it's done by sending a message to an NSQ topic
### Test Structures
For each object and file, there should be one test struct containing expected
info about the object and its files. These structs should be available to all
of the test workers.
|
Java | UTF-8 | 11,196 | 1.984375 | 2 | [] | no_license | package org.greatfree.server.container;
import java.io.IOException;
import org.greatfree.client.FreeClientPool;
import org.greatfree.cluster.message.ClusterSizeRequest;
import org.greatfree.cluster.message.ClusterSizeResponse;
import org.greatfree.cluster.message.PartitionSizeRequest;
import org.greatfree.cluster.message.PartitionSizeResponse;
import org.greatfree.concurrency.ThreadPool;
import org.greatfree.data.ServerConfig;
import org.greatfree.exceptions.RemoteReadException;
import org.greatfree.framework.container.p2p.message.PeerAddressRequest;
import org.greatfree.framework.multicast.message.PeerAddressResponse;
import org.greatfree.framework.p2p.RegistryConfig;
import org.greatfree.message.ServerMessage;
import org.greatfree.util.IPAddress;
import org.greatfree.util.Tools;
// Created: 12/31/2018, Bing Li
public class PeerContainer
{
private Peer<CSDispatcher> peer;
public PeerContainer(String peerName, int port, String registryServerIP, int registryServerPort, ServerTask task, boolean isRegistryNeeded) throws IOException
{
CSDispatcher csd = new CSDispatcher(ServerConfig.SHARED_THREAD_POOL_SIZE, ServerConfig.SHARED_THREAD_POOL_KEEP_ALIVE_TIME, RegistryConfig.SCHEDULER_THREAD_POOL_SIZE, RegistryConfig.SCHEDULER_THREAD_POOL_KEEP_ALIVE_TIME);
this.peer = new Peer.PeerBuilder<CSDispatcher>()
.peerPort(port)
.peerName(peerName)
.registryServerIP(registryServerIP)
.registryServerPort(registryServerPort)
.isRegistryNeeded(isRegistryNeeded)
.listenerCount(ServerConfig.LISTENING_THREAD_COUNT)
.dispatcher(csd)
.freeClientPoolSize(RegistryConfig.CLIENT_POOL_SIZE)
.readerClientSize(RegistryConfig.READER_CLIENT_SIZE)
.syncEventerIdleCheckDelay(RegistryConfig.SYNC_EVENTER_IDLE_CHECK_DELAY)
.syncEventerIdleCheckPeriod(RegistryConfig.SYNC_EVENTER_IDLE_CHECK_PERIOD)
.syncEventerMaxIdleTime(RegistryConfig.SYNC_EVENTER_MAX_IDLE_TIME)
.asyncEventQueueSize(RegistryConfig.ASYNC_EVENT_QUEUE_SIZE)
.asyncEventerSize(RegistryConfig.ASYNC_EVENTER_SIZE)
.asyncEventingWaitTime(RegistryConfig.ASYNC_EVENTING_WAIT_TIME)
.asyncEventerWaitTime(RegistryConfig.ASYNC_EVENTER_WAIT_TIME)
.asyncEventerWaitRound(RegistryConfig.ASYNC_EVENTER_WAIT_ROUND)
.asyncEventIdleCheckDelay(RegistryConfig.ASYNC_EVENT_IDLE_CHECK_DELAY)
.asyncEventIdleCheckPeriod(RegistryConfig.ASYNC_EVENT_IDLE_CHECK_PERIOD)
.schedulerPoolSize(RegistryConfig.SCHEDULER_THREAD_POOL_SIZE)
.scheulerKeepAliveTime(RegistryConfig.SCHEDULER_THREAD_POOL_KEEP_ALIVE_TIME)
.build();
// Assign the server key to the message dispatchers in the server dispatcher. 03/30/2020, Bing Li
csd.init();
ServiceProvider.CS().init(csd.getServerKey(), task);
}
public PeerContainer(String peerName, int port, ServerTask task, boolean isRegistryNeeded) throws IOException
{
CSDispatcher csd = new CSDispatcher(ServerConfig.SHARED_THREAD_POOL_SIZE, ServerConfig.SHARED_THREAD_POOL_KEEP_ALIVE_TIME, RegistryConfig.SCHEDULER_THREAD_POOL_SIZE, RegistryConfig.SCHEDULER_THREAD_POOL_KEEP_ALIVE_TIME);
this.peer = new Peer.PeerBuilder<CSDispatcher>()
.peerPort(port)
.peerName(peerName)
.registryServerIP(RegistryConfig.PEER_REGISTRY_ADDRESS)
.registryServerPort(RegistryConfig.PEER_REGISTRY_PORT)
.isRegistryNeeded(isRegistryNeeded)
.listenerCount(ServerConfig.LISTENING_THREAD_COUNT)
// .serverThreadPoolSize(ServerConfig.SHARED_THREAD_POOL_SIZE)
// .serverThreadKeepAliveTime(ServerConfig.SHARED_THREAD_POOL_KEEP_ALIVE_TIME)
// .dispatcher(new CSDispatcher(RegistryConfig.DISPATCHER_THREAD_POOL_SIZE, RegistryConfig.DISPATCHER_THREAD_POOL_KEEP_ALIVE_TIME, RegistryConfig.SCHEDULER_THREAD_POOL_SIZE, RegistryConfig.SCHEDULER_THREAD_POOL_KEEP_ALIVE_TIME))
.dispatcher(csd)
.freeClientPoolSize(RegistryConfig.CLIENT_POOL_SIZE)
.readerClientSize(RegistryConfig.READER_CLIENT_SIZE)
.syncEventerIdleCheckDelay(RegistryConfig.SYNC_EVENTER_IDLE_CHECK_DELAY)
.syncEventerIdleCheckPeriod(RegistryConfig.SYNC_EVENTER_IDLE_CHECK_PERIOD)
.syncEventerMaxIdleTime(RegistryConfig.SYNC_EVENTER_MAX_IDLE_TIME)
.asyncEventQueueSize(RegistryConfig.ASYNC_EVENT_QUEUE_SIZE)
.asyncEventerSize(RegistryConfig.ASYNC_EVENTER_SIZE)
.asyncEventingWaitTime(RegistryConfig.ASYNC_EVENTING_WAIT_TIME)
.asyncEventerWaitTime(RegistryConfig.ASYNC_EVENTER_WAIT_TIME)
.asyncEventerWaitRound(RegistryConfig.ASYNC_EVENTER_WAIT_ROUND)
.asyncEventIdleCheckDelay(RegistryConfig.ASYNC_EVENT_IDLE_CHECK_DELAY)
.asyncEventIdleCheckPeriod(RegistryConfig.ASYNC_EVENT_IDLE_CHECK_PERIOD)
.schedulerPoolSize(RegistryConfig.SCHEDULER_THREAD_POOL_SIZE)
.scheulerKeepAliveTime(RegistryConfig.SCHEDULER_THREAD_POOL_KEEP_ALIVE_TIME)
// .clientThreadPoolSize(RegistryConfig.CLIENT_THREAD_POOL_SIZE)
// .clientThreadKeepAliveTime(RegistryConfig.CLIENT_THREAD_KEEP_ALIVE_TIME)
// .schedulerPoolSize(RegistryConfig.SCHEDULER_THREAD_POOL_SIZE)
// .schedulerKeepAliveTime(RegistryConfig.SCHEDULER_THREAD_POOL_KEEP_ALIVE_TIME)
// .asyncEventerShutdownTimeout(ClientConfig.ASYNC_SCHEDULER_SHUTDOWN_TIMEOUT)
.build();
// Assign the server key to the message dispatchers in the server dispatcher. 03/30/2020, Bing Li
csd.init();
// ServiceProvider.CS().init(this.peer.getPeerID(), task);
ServiceProvider.CS().init(csd.getServerKey(), task);
}
public PeerContainer(ServerTask task, String configXML) throws IOException
{
PeerProfile.P2P().init(configXML);
CSDispatcher csd = new CSDispatcher(ServerConfig.SHARED_THREAD_POOL_SIZE, ServerConfig.SHARED_THREAD_POOL_KEEP_ALIVE_TIME, RegistryConfig.SCHEDULER_THREAD_POOL_SIZE, RegistryConfig.SCHEDULER_THREAD_POOL_KEEP_ALIVE_TIME);
this.peer = new Peer.PeerBuilder<CSDispatcher>()
.peerPort(ServerProfile.CS().getPort())
.peerName(PeerProfile.P2P().getPeerName())
.registryServerIP(PeerProfile.P2P().getRegistryServerIP())
.registryServerPort(PeerProfile.P2P().getRegistryServerPort())
.isRegistryNeeded(PeerProfile.P2P().isRegistryNeeded())
.listenerCount(ServerProfile.CS().getListeningThreadCount())
// .serverThreadPoolSize(ServerProfile.CS().getServerThreadPoolSize())
// .serverThreadKeepAliveTime(ServerProfile.CS().getServerThreadKeepAliveTime())
.dispatcher(csd)
.freeClientPoolSize(PeerProfile.P2P().getFreeClientPoolSize())
.readerClientSize(PeerProfile.P2P().getReaderClientSize())
.syncEventerIdleCheckDelay(PeerProfile.P2P().getSyncEventerIdleCheckDelay())
.syncEventerIdleCheckPeriod(PeerProfile.P2P().getSyncEventerIdleCheckPeriod())
.syncEventerMaxIdleTime(PeerProfile.P2P().getSyncEventerMaxIdleTime())
.asyncEventQueueSize(PeerProfile.P2P().getAsyncEventQueueSize())
.asyncEventerSize(PeerProfile.P2P().getAsyncEventerSize())
.asyncEventingWaitTime(PeerProfile.P2P().getAsyncEventingWaitTime())
.asyncEventerWaitTime(PeerProfile.P2P().getAsyncEventerWaitTime())
.asyncEventerWaitRound(PeerProfile.P2P().getAsyncEventerWaitRound())
.asyncEventIdleCheckDelay(PeerProfile.P2P().getAsyncEventIdleCheckDelay())
.asyncEventIdleCheckPeriod(PeerProfile.P2P().getAsyncEventIdleCheckPeriod())
.schedulerPoolSize(PeerProfile.P2P().getSchedulerPoolSize())
.scheulerKeepAliveTime(PeerProfile.P2P().getSchedulerKeepAliveTime())
.build();
// Assign the server key to the message dispatchers in the server dispatcher. 03/30/2020, Bing Li
csd.init();
// ServiceProvider.CS().init(this.peer.getPeerID(), task);
ServiceProvider.CS().init(csd.getServerKey(), task);
}
public void stop(long timeout) throws ClassNotFoundException, IOException, InterruptedException, RemoteReadException
{
this.peer.stop(timeout);
}
public void start() throws ClassNotFoundException, RemoteReadException, IOException
{
this.peer.start();
}
public void syncNotify(String ip, int port, ServerMessage notification) throws IOException, InterruptedException
{
this.peer.syncNotify(ip, port, notification);
}
public void asyncNotify(String ip, int port, ServerMessage notification)
{
this.peer.asyncNotify(ip, port, notification);
}
public IPAddress getIPAddress(String registryIP, int registryPort, String nodeKey) throws ClassNotFoundException, RemoteReadException, IOException
{
return ((PeerAddressResponse)this.peer.read(registryIP, registryPort, new PeerAddressRequest(nodeKey))).getPeerAddress();
}
/*
* The method is useful for most storage systems, which need the partition information to design the upper level distribution strategy. 09/09/2020, Bing Li
*/
public int getPartitionSize(String clusterIP, int clusterPort) throws ClassNotFoundException, RemoteReadException, IOException
{
return ((PartitionSizeResponse)this.peer.read(clusterIP, clusterPort, new PartitionSizeRequest())).getPartitionSize();
}
/*
* The message is designed for the scalability such that all of the current children are replaced by new coming ones. In the storage system, the current ones is full in the disk space. In the case, they have to be replaced. But in other cases, it depends on the application level how to raise the scale and deal with the existing children. The system level cannot help. 09/12/2020, Bing Li
*
* The message is an internal one, like the PartitionSizeRequest/PartitionSizeResponse, which is processed by the cluster root only. Programmers do not need to do anything but send it. So it inherits ServerMessage. 09/12/2020, Bing Li
*/
public int getClusterSize(String clusterIP, int clusterPort) throws ClassNotFoundException, RemoteReadException, IOException
{
return ((ClusterSizeResponse)this.peer.read(clusterIP, clusterPort, new ClusterSizeRequest())).getSize();
}
public ServerMessage read(String ip, int port, ServerMessage request) throws ClassNotFoundException, RemoteReadException, IOException
{
return this.peer.read(ip, port, request);
}
public void selfSyncNotify(ServerMessage notification) throws IOException, InterruptedException
{
this.peer.syncNotify(this.peer.getPeerIP(), this.peer.getPort(), notification);
}
public void selfAsyncNotify(ServerMessage notification)
{
this.peer.asyncNotify(this.peer.getPeerIP(), this.peer.getPort(), notification);
}
public ServerMessage selfRead(ServerMessage request) throws ClassNotFoundException, RemoteReadException, IOException
{
return this.peer.read(this.peer.getPeerIP(), this.peer.getPort(), request);
}
public void addPartners(String ip, int port)
{
this.peer.addPartners(ip, port);
}
public FreeClientPool getClientPool()
{
return this.peer.getClientPool();
}
public ThreadPool getPool()
{
return this.peer.getPool();
}
public String getPeerName()
{
return this.peer.getPeerName();
}
public String getPeerID()
{
return this.peer.getPeerID();
}
public String getPeerIP()
{
return this.peer.getPeerIP();
}
public int getPeerPort()
{
return this.peer.getPort();
}
public String getRegistryIP()
{
return this.peer.getRegistryServerIP();
}
public int getRegistryPort()
{
return this.peer.getRegistryServerPort();
}
public static String getPeerKey(String peerName)
{
return Tools.getHash(peerName);
}
}
|
Java | UTF-8 | 15,921 | 2.015625 | 2 | [] | no_license | package com.whcs_ucf.whcs_android;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Looper;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import com.dd.CircularProgressButton;
import java.io.IOException;
import java.util.Set;
public class BaseStationConnectActivity extends WHCSActivityWithCleanup {
private ListView pairedList;
private ListView activeList;
private CircularProgressButton pairedbutton;
private CircularProgressButton activeButton;
private BluetoothDeviceAdapter pairedArrayAdapter;
private BluetoothDeviceAdapter activeArrayAdapter;
//some supporting objects are needed to discover active BlueTooth Devices.
//We need to start an asynchronous device finder and then register a
//Broadcast receiver to our application that way when the device finder finishes
//Our application will catch the fact that it is complete.
//An Intent filter is used to catch the
private BroadcastReceiver activeDeviceReceiver;
private Handler asynchronousActivityStartHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_base_station_connect);
Log.d("WHCS-UCF", "V1.4");
this.asynchronousActivityStartHandler = new Handler(Looper.getMainLooper());
//establishes refs to buttons, lists
this.setupGUIVariables();
//sets event listeners for buttons
this.setupButtonListeners();
//sets event listeners for clicking list items
this.setupListListeners();
//Check to see if a Base Station has been connected to before.
//If one has, attempt to connect to it.
this.tryConnectToExistingBasestation();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_base_station_connect, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void setupGUIVariables() {
//Establishes the references to the listviews in the basestation connection activity.
this.pairedList = (ListView)this.findViewById(R.id.pairedListView);
this.activeList = (ListView)this.findViewById(R.id.activeListView);
//Listviews need an adapter to function properly. Here we create and add adapters to the
//listviews
pairedArrayAdapter = new BluetoothDeviceAdapter(this, android.R.layout.simple_list_item_1);
pairedList.setAdapter(pairedArrayAdapter);
activeArrayAdapter = new BluetoothDeviceAdapter(this, android.R.layout.simple_list_item_1);
activeList.setAdapter(activeArrayAdapter);
//Establishes the references to the buttons in the basestation connection activity.
this.pairedbutton = (CircularProgressButton)this.findViewById(R.id.pairedButton);
this.activeButton = (CircularProgressButton)this.findViewById(R.id.activeButton);
//We want activeButton to be showing when it is scanning for devices.
this.activeButton.setIndeterminateProgressMode(true);
}
private void setupButtonListeners() {
pairedbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
listPairedDevices();
}
});
activeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (activeDeviceReceiver == null) {
// Create a BroadcastReceiver for ACTION_FOUND
activeDeviceReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// Add the name and address to an array adapter to show in a ListView
activeArrayAdapter.add(device);
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
//We want the active device button to stop the refeshing effect.
BaseStationConnectActivity.this.cancelDiscovery();
}
}
};
// Register the BroadcastReceiver
//This must be called after activeDeviceReceiver is initialized with the BlueTooth Discovery handler
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(activeDeviceReceiver, filter); // Don't forget to unregister during onDestroy
//Register to receive when BlueTooth discovery stops.
IntentFilter discoveryStopFilter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(activeDeviceReceiver, discoveryStopFilter);
}
listActiveDevices();
}
});
}
private void setupListListeners() {
pairedList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (DebugFlags.DEBUG_CONTROL_MODULE_LIST_ACTIVITY_NO_BASESTATION_CONNECTION) {
BaseStationConnectActivity.this.cancelDiscovery();
startControlModuleListActivity();
return;
} else if(DebugFlags.PERFORM_DEBUG_BASE_STATION_QUERY_FROM_BASE_STATION_CONNECT_ACTIVITY) {
BaseStationConnectActivity.this.cancelDiscovery();
try {
if(issuerAndListenerInitialized) {
destroyIssuerAndListener();
return;
}
BaseStationConnectActivity.this.initIssuerAndListener(activeArrayAdapter.getItem(position));
BaseStationConnectActivity.this.whcsIssuer.queueCommand(WHCSCommand.CreateQueryIfBaseStationCommand(), new ClientCallback() {
@Override
public void onResponse(WHCSCommand command, WHCSResponse response) {
Log.d("WHCS-UCF", "It' the base station.");
}
@Override
public void onTimeOut(WHCSCommand command) {
Log.d("WHCS-UCF", "Timeout trying to connect to base station.");
}
});
} catch (IOException e) {
e.printStackTrace();
}
} else {
Log.d("WHCS-UCF", "beginning to initialize issuer and listener.");
BaseStationConnectActivity.this.cancelDiscovery();
if(issuerAndListenerInitialized) {
destroyIssuerAndListener();
Toast.makeText(BaseStationConnectActivity.this.getApplicationContext(), "Retry in 1 second.", Toast.LENGTH_SHORT).show();
return;
}
performAsynchInitialization(pairedArrayAdapter.getItem(position));
}
}
});
activeList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (DebugFlags.DEBUG_CONTROL_MODULE_LIST_ACTIVITY_NO_BASESTATION_CONNECTION) {
BaseStationConnectActivity.this.cancelDiscovery();
startControlModuleListActivity();
return;
} else if(DebugFlags.PERFORM_DEBUG_BASE_STATION_QUERY_FROM_BASE_STATION_CONNECT_ACTIVITY) {
BaseStationConnectActivity.this.cancelDiscovery();
try {
if(issuerAndListenerInitialized) {
destroyIssuerAndListener();
return;
}
BaseStationConnectActivity.this.initIssuerAndListener(activeArrayAdapter.getItem(position));
BaseStationConnectActivity.this.whcsIssuer.queueCommand(WHCSCommand.CreateQueryIfBaseStationCommand(), new ClientCallback() {
@Override
public void onResponse(WHCSCommand command, WHCSResponse response) {
Log.d("WHCS-UCF", "It' the base station.");
}
@Override
public void onTimeOut(WHCSCommand command) {
Log.d("WHCS-UCF", "Timeout trying to connect to base station.");
}
});
} catch (IOException e) {
e.printStackTrace();
}
} else {
Log.d("WHCS-UCF", "beginning to initialize issuer and listener.");
BaseStationConnectActivity.this.cancelDiscovery();
if(issuerAndListenerInitialized) {
destroyIssuerAndListener();
Toast.makeText(BaseStationConnectActivity.this.getApplicationContext(), "Retry in 1 second.", Toast.LENGTH_SHORT).show();
return;
}
performAsynchInitialization(activeArrayAdapter.getItem(position));
}
}
});
}
private void tryConnectToExistingBasestation() {
if(loadBaseStationDeviceForStop() != null) {
performAsynchInitialization(loadBaseStationDeviceForStop());
}
}
private void performAsynchInitialization(BluetoothDevice device) {
BaseStationConnectActivity.this.asynchInitIssuerAndListener(device, new ConnectionMadeCallback() {
@Override
public void onSuccessfulConnection() {
BaseStationConnectActivity.this.whcsIssuer.queueCommand(WHCSCommand.CreateQueryIfBaseStationCommand(), new ClientCallback() {
@Override
public void onResponse(WHCSCommand command, WHCSResponse response) {
Log.d("WHCS-UCF", "It' the base station.");
saveBaseStationDeviceForStop();
asynchronousActivityStartHandler.post(new ControlModuleListActivityStarter());
}
@Override
public void onTimeOut(WHCSCommand command) {
Log.d("WHCS-UCF", "Timeout trying to connect to base station.");
if(whcsIssuer != null) {
whcsIssuer.stop();
}
if(whcsBluetoothListener != null) {
whcsBluetoothListener.stop();
}
//Toast.makeText(BaseStationConnectActivity.this.getApplicationContext(), "Could not initialize BluetoothConnection", Toast.LENGTH_LONG).show();
}
});
}
@Override
public void onTimeoutConnection() {
Log.d("WHCS-UCF", "Asynch initialization of issuer and listener timed out.");
}
});
}
private void listPairedDevices() {
if(DebugFlags.RUNNING_ON_VM){
listDevicesForVM(pairedList);
return;
}
// get paired devices
Set<BluetoothDevice> pairedDevices = whcsBlueToothAdapter.getBondedDevices();
//Clear everything currently in the list's adapter
pairedArrayAdapter.clear();
// put it's one to the adapter
for(BluetoothDevice device : pairedDevices)
pairedArrayAdapter.add(device);
}
private void listActiveDevices() {
if(DebugFlags.RUNNING_ON_VM){
listDevicesForVM(activeList);
return;
}
if(whcsBlueToothAdapter.isDiscovering()) {
//We're already discovering. We need to wait for that to finish.
return;
}
//Clear the arrayAdapter for a refresh
activeArrayAdapter.clear();
//Begin discovery but notify through text if we weren't able to for some reason.
if(!whcsBlueToothAdapter.startDiscovery()) {
Toast.makeText(this.getApplicationContext(), "BlueTooth Discovery couldn't start.", Toast.LENGTH_LONG).show();
return;
}
//Set progress between 1-99 to get the refreshing look.
this.activeButton.setProgress(50);
}
private class ControlModuleListActivityStarter implements Runnable {
@Override
public void run() {
startControlModuleListActivity();
}
}
private void listDevicesForVM(ArrayAdapter<String> aa) {
aa.clear();
for(int i=0; i<5; i++) {
aa.add("Fake Device number #" + i);
}
}
private void listDevicesForVM(ListView lv) {
ArrayAdapter<String> aa = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
aa.clear();
for(int i=0; i<5; i++) {
aa.add("Fake Device number #" + i);
}
lv.setAdapter(aa);
}
private void startDebugActivity() {
Intent intent = new Intent(getApplicationContext(), DebugActivity.class);
startActivity(intent);
}
private void startControlModuleListActivity() {
Intent intent = new Intent(getApplicationContext(), ControlModuleListActivity.class);
startActivity(intent);
}
private void cancelDiscovery() {
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
if(activeDeviceReceiver != null) {
this.unregisterReceiver(activeDeviceReceiver);
activeDeviceReceiver = null;
}
this.activeButton.setProgress(0);
}
@Override
protected void onStop() {
cancelDiscovery();
stopInitializerThread();
super.onStop();
}
@Override
protected void onDestroy() {
super.onDestroy();
}
}
|
TypeScript | UTF-8 | 702 | 3.625 | 4 | [] | no_license | class CircleGeometryV2 {
private PI: number = 3.14
constructor(public radius: number) {
}
get area() {
return this.PI * (this.radius ** 2)
}
set area(vaule: number) {
this.radius = (vaule / this.PI) ** 0.5
}
public circumference(): number {
return 2 * this.PI * this.radius
}
}
const radomCircle = new CircleGeometryV2(2)
// console.log(radomCircle.area);
radomCircle.radius = 40
// console.log(radomCircle.area);
const anotherRandomCircle = new CircleGeometryV2(2)
console.log(anotherRandomCircle.radius);
console.log(anotherRandomCircle.area)
anotherRandomCircle.area = 3.14 * (5 ** 2);
console.log(anotherRandomCircle.radius);
|
TypeScript | UTF-8 | 410 | 3.3125 | 3 | [] | no_license | import { LinkedList } from "./linked-list";
export class Stack {
storage: LinkedList<unknown>;
constructor() {
this.storage = new LinkedList<unknown>();
}
isEmpty() {
return this.storage.length === 0;
}
peek(): unknown {
return this.storage.tail?.value;
}
push(value: unknown) {
this.storage.push(value);
}
pop(): unknown {
return this.storage.pop()?.value;
}
}
|
Markdown | UTF-8 | 3,473 | 3.03125 | 3 | [
"Apache-2.0"
] | permissive | # ReFramework Template Excel Transaction
Excelファイルのデータをトランザクションとして処理するワークフローテンプレート
## 内容
Excelファイルで管理されているデータを自動処理するロボットを作成するためのテンプレートです。
トランザクションデータを格納したxlsxファイルには以下の形式でデータが格納されていることを想定しています。
| TransactionID | TransactionField1 | TransactionField2 |
| ------------- | ----------------- | ----------------- |
| ID-1 | Field1-1 | Field2-1 |
* Transaction ID: トランザクションID
* Transaction Field1: トランザクションの情報1
* Transaction Field2: トランザクションの情報2
上記3項目は列番号で参照しているため、違う名称でも問題ありません。これら項目は、トランザクションを識別するデータとしてログに出力されるものです。また、列がこれより多い場合も、Process.xamlのパラメータ(in_TransactionItem)にすべての列データが渡されます。
## 設定
Data¥Condig.xlsxで以下の設定ができます。
Settingタブ
| Name | Default | Description |
| ------------------------ | ------------------------ | ---------------------------------------- |
| logF_BusinessProcessName | Framework Excel Template | ワークフローの名称(ログに出力されます) |
| TransactionData | - | トランザクションデータのファイル名 |
| TransactionDataSheet | - | トランザクションデータのシート名 |
Constantsタブ
| Name | Default | Description |
| -------------- | ------- | ------------ |
| MaxRetryNumber | 3 | リトライ回数 |
## 利用方法
1. テンプレート一式をダウンロードします。
2. project.jsonの"name","description"を修正します。
3. Data¥Config.xmlxにトランザクションのファイル名、シート名を設定します。
4. Process.xamlを実装します。
in_TransactionItem(DataRow型)にトランザクションデータが渡されます。データの不備等で処理を再実行できない場合は、BRE(Business Rule Exception)をThrowするように実装してください。
5. トランザクションテストデータを準備します。
Test_Framework\_TransactionTest.xsmlにテストデータを準備します。形式は、以下の通り。
TransactionID, TransactionField1, TransactionField2は、トランザクションデータと同様。Exceptionは、期待する実行結果で以下の3つから選択します。
* Success: 正常終了
* BRE: Business Rule Exception
* AppEx: System Exception
| TransactionID | TransactionField1 | TransactionField2 | Exception |
| ------------- | ----------------- | ----------------- | ----------- |
| ID-1 | Field1-1 | Field2-1 | Exception-1 |
6. トランザクションテストを実施します。
_TransactionTest.xamlを実行することにより_TransactionTest.xsmlの各行のデータでProcess.xamlをテストします。テスト結果は、Test_Framework\_TransactionTest.xsmlのResultタブと、Test_Framework\TransactionTestLog.txtに出力されます。
|
Python | UTF-8 | 90 | 2.859375 | 3 | [] | no_license |
cards = [int(i) for i in input().split(" ")]
print("bust" if sum(cards) >= 22 else "win") |
Java | UTF-8 | 484 | 2.078125 | 2 | [] | no_license | package com.bro.bean;
/**
* Entity to represent property for sell/rent/lease
* @author Zubair Shaikh
* @version 1.0
*/
public class Property {
private Integer propId;
private String propConfig; // Flat/Shop/Plot
private String offerType; // Sell/Lease/Rent
private Double offerPrice;
private Double sqftRate;
private String city;
private String area;
private String address;
private String landmark;
private Owner owner;
private Broker broker;
public Property() {
}
}
|
C++ | UTF-8 | 1,246 | 2.9375 | 3 | [] | no_license | #include <QStringList>
#include <QtAlgorithms>
#include "ConfigPath.h"
#include "ConfigPathElement.h"
namespace conf {
ConfigPath::ConfigPath() { }
ConfigPath::ConfigPath(const char *path) {
parse(path);
}
ConfigPath::ConfigPath(const QString &path) {
parse(path);
}
ConfigPath::~ConfigPath() {
clear();
}
QString ConfigPath::toString() const {
QString path;
foreach (const ConfigPathElement *elm, pathList) {
path += elm->toString() + "/";
}
if (path.endsWith("/")) {
path.chop(1);
}
return path;
}
ConfigPathElement *ConfigPath::next() {
if (pathList.size() == 0) {
return NULL;
}
return pathList.takeFirst();
}
void ConfigPath::clear() {
qDeleteAll(pathList);
pathList.clear();
}
void ConfigPath::parse(const QString &path) {
clear();
QStringList elms = path.split("/", QString::SkipEmptyParts);
if (elms.size() == 0) {
return;
}
foreach (const QString &elm, elms) {
if (ConfigPathElementQuantifier::regexp.exactMatch(elm)) {
pathList.append(new ConfigPathElementQuantifier(elm));
}
else {
pathList.append(new ConfigPathElementName(elm));
}
}
}
}
|
Go | UTF-8 | 1,661 | 2.734375 | 3 | [
"MIT"
] | permissive | // Copyright 2015 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package git
import (
"fmt"
"io"
"strings"
"sync"
)
var (
// logOutput is the writer to write logs. When not set, no log will be produced.
logOutput io.Writer
// logPrefix is the prefix prepend to each log entry.
logPrefix = "[git-module] "
)
// SetOutput sets the output writer for logs.
func SetOutput(output io.Writer) {
logOutput = output
}
// SetPrefix sets the prefix to be prepended to each log entry.
func SetPrefix(prefix string) {
logPrefix = prefix
}
func log(format string, args ...interface{}) {
if logOutput == nil {
return
}
_, _ = fmt.Fprint(logOutput, logPrefix)
_, _ = fmt.Fprintf(logOutput, format, args...)
_, _ = fmt.Fprintln(logOutput)
}
var (
// gitVersion stores the Git binary version.
// NOTE: To check Git version should call BinVersion not this global variable.
gitVersion string
gitVersionOnce sync.Once
gitVersionErr error
)
// BinVersion returns current Git binary version that is used by this module.
func BinVersion() (string, error) {
gitVersionOnce.Do(func() {
var stdout []byte
stdout, gitVersionErr = NewCommand("version").Run()
if gitVersionErr != nil {
return
}
fields := strings.Fields(string(stdout))
if len(fields) < 3 {
gitVersionErr = fmt.Errorf("not enough output: %s", stdout)
return
}
// Handle special case on Windows.
i := strings.Index(fields[2], "windows")
if i >= 1 {
gitVersion = fields[2][:i-1]
return
}
gitVersion = fields[2]
})
return gitVersion, gitVersionErr
}
|
C | GB18030 | 1,905 | 3.171875 | 3 | [] | no_license | //**㷨ʵ
//2012/10/24/18:53
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define RANGE 16
#define N_SIZE 16
#define BUF_SIZE 128
int tmp[BUF_SIZE];
int out[N_SIZE];
int in[N_SIZE];
/*ע⣬ǻڱȽϵ㷨ʱĽΪO(n).
*÷ΧȽխһڹؼַΧȽխԪصĿȽٵ,
*ԪĿȽ϶£ڻҪĿռȽϴҲǽԭ
*ԶԸٻòãԾʱȽСŵ㣬
*ʺе
*ʱӦÿöù鲢ˡ
*/
void CountSort(int *p,int n,int *out,int *tmp)
{
int i,k,m;
int *ip=tmp;
//гʼ
for(i=0;i<n;++i,++ip)
*ip=0;
//ʼ
for(i=0;i<n;++i)
{
k=p[i];
++tmp[k];
}
//СiԪصĿ
for(k=0,i=1;i<n;++i,++k)
tmp[i]+=tmp[k];
for(i=0;i<n;++i)
{
k=p[i];
m=tmp[k];
out[m-1]=k;
--tmp[k];
}
}
//*********************************************************
int main(int argc,char *argv[])
{
int i,seed;
seed=time(NULL);
srand(seed);
for(i=0;i<N_SIZE;++i)
in[i]=rand()%RANGE;
//δԪ
for(i=0;i<N_SIZE;++i)
printf(" %d ",in[i]);
printf("\nʼм\n");
CountSort(in,N_SIZE,out,tmp);
printf("еԪʾ:\n");
for(i=0;i<N_SIZE;++i)
printf(" %d ",out[i]);
printf("\n");
return 0;
} |
Java | UTF-8 | 943 | 2.59375 | 3 | [] | no_license | package edu.wm.cs.mplus.processors;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
import edu.wm.cs.mplus.model.MutationType;
import edu.wm.cs.mplus.model.location.MutationLocation;
import edu.wm.cs.mplus.selector.Selector;
import edu.wm.cs.mplus.selector.SelectorLocationFactory;
public class SelectorsProcessor {
public static List<MutationLocation> process(HashMap<MutationType, List<MutationLocation>> locations){
List<MutationLocation> selectedLocations = new ArrayList<MutationLocation>();
SelectorLocationFactory factory = SelectorLocationFactory.getInstance();
for(Entry<MutationType, List<MutationLocation>> entry : locations.entrySet()){
Selector selector = factory.getSelector(entry.getKey());
MutationLocation selectedLocation = selector.select(entry.getValue());
selectedLocations.add(selectedLocation);
}
return selectedLocations;
}
}
|
C++ | UTF-8 | 1,358 | 3.171875 | 3 | [] | no_license | #ifndef MEDIAS_AVERAGE_H
#define MEDIAS_AVERAGE_H
#include <cmath>
#include <vector>
#include <numeric>
using namespace std;
// Intervalos de Confiança 1
double normal_distribution_cdf(double x, double mu, double std_dev){
auto result = (1 + erf(x-mu/std_dev * sqrt(2)))/2;
return result;
}
double normal_distribution_cdf(double x){
//média zero e desvio padrão 1.
auto result = (1 + erf(x/1 * sqrt(2)))/2;
return result;
}
double normal_distribution_cdf(double x1, double x2, double mu, double std_dev) {
auto result_x1 = normal_distribution_cdf(x1, mu, std_dev);
auto result_x2 = normal_distribution_cdf(x2, mu, std_dev);
if (result_x1 > result_x2){
return result_x1-result_x2;
}else{
return result_x2-result_x1;
}
}
double normal_distribution_cdf(double x1, double x2){
auto result_x1 = normal_distribution_cdf(x1);
auto result_x2 = normal_distribution_cdf(x2);
if (result_x1>result_x2){
return result_x1-result_x2;
}else{
return result_x2-result_x1;
}
}
double mean(const vector<double>& numbers) {
//calculo da média aritmetica
if(numbers.empty()){
return 0.0;
}
double sum;
sum = accumulate(numbers.begin(), numbers.end(), 0);
return (double) sum/(int) numbers.size(); // média dos elementos de numbers
}
#endif
|
Java | UTF-8 | 7,808 | 2 | 2 | [] | no_license | package com.backingapp.ayman.backingapp.UI;
import android.app.Activity;
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Context;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.backingapp.ayman.backingapp.Adapter.RecipeAdapter;
import com.backingapp.ayman.backingapp.Constants;
import com.backingapp.ayman.backingapp.Interfaces.RecipeAdapterListener;
import com.backingapp.ayman.backingapp.Interfaces.RecipesInterface;
import com.backingapp.ayman.backingapp.Models.Recipe;
import com.backingapp.ayman.backingapp.R;
import com.backingapp.ayman.backingapp.RecipesController;
import com.backingapp.ayman.backingapp.RecipesViewModel;
import com.zplesac.connectionbuddy.ConnectionBuddy;
import com.zplesac.connectionbuddy.interfaces.ConnectivityChangeListener;
import com.zplesac.connectionbuddy.models.ConnectivityEvent;
import com.zplesac.connectionbuddy.models.ConnectivityState;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* A placeholder fragment containing a simple view.
*/
public class MainActivityFragment extends Fragment implements RecipeAdapterListener, Observer<List<Recipe>>, ConnectivityChangeListener {
@BindView(R.id.recipeRecyclerView) RecyclerView recipeRecyclerView;
OnRecipeItemClickListener mCallback;
GridLayoutManager gridLayoutManager;
private ArrayList<Recipe> recipesList;
private RecipeAdapter recipeAdapter;
private Parcelable mListState;
private RecipesViewModel recipesViewModel;
public MainActivityFragment() {
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
// This makes sure that the host activity has implemented the callback interface
// If not, it throws an exception
try {
mCallback = (OnRecipeItemClickListener) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString() + " must implement OnRecipeItemClickListener");
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
ButterKnife.bind(this, rootView);
if (savedInstanceState != null) {
recipesList = savedInstanceState.getParcelableArrayList(Constants.RECIPES_LIST_EXTRA);
} else {
recipesViewModel = ViewModelProviders.of(this).get(RecipesViewModel.class);
recipesViewModel.getRecipesLiveData().observe(this, this);
}
return rootView;
}
@Override
public void onStart() {
super.onStart();
ConnectionBuddy.getInstance().registerForConnectivityEvents(this, this);
}
@Override
public void onStop() {
super.onStop();
ConnectionBuddy.getInstance().unregisterFromConnectivityEvents(this);
}
@Override
public void onResume() {
super.onResume();
if (mListState != null) {
gridLayoutManager.onRestoreInstanceState(mListState);
}
}
@Override
public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
if (savedInstanceState != null)
mListState = savedInstanceState.getParcelable(Constants.LIST_STATE_EXTRA);
}
@Override
public void onSaveInstanceState(@NonNull Bundle outState) {
outState.putParcelableArrayList(Constants.RECIPES_LIST_EXTRA, recipesList);
if (gridLayoutManager != null) {
mListState = gridLayoutManager.onSaveInstanceState();
outState.putParcelable(Constants.LIST_STATE_EXTRA, mListState);
}
}
void getRecipes() {
RecipesController.getRecipes(new RecipesInterface() {
@Override
public void onRecipesReceived(ArrayList<Recipe> recipes) {
recipesList = recipes;
recipesViewModel.setRecipes(recipes);
}
@Override
public void onError(String errorMessage) {
Toast.makeText(getContext(), errorMessage, Toast.LENGTH_SHORT).show();
Log.e("getRecipes", errorMessage);
}
});
}
void initRecipeAdapter(List<Recipe> recipeList) {
recipeAdapter = new RecipeAdapter(recipeList, this);
if (getResources().getBoolean(R.bool.isTablet)) {
if (getActivity().getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
gridLayoutManager = new GridLayoutManager(getActivity(), 2);
} else {
gridLayoutManager = new GridLayoutManager(getActivity(), 4);
}
} else {
if (getActivity().getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
gridLayoutManager = new GridLayoutManager(getActivity(), 1);
} else {
gridLayoutManager = new GridLayoutManager(getActivity(), 2);
}
}
recipeRecyclerView.setLayoutManager(gridLayoutManager);
recipeRecyclerView.setHasFixedSize(true);
recipeRecyclerView.setAdapter(recipeAdapter);
}
@Override
public void onRecipeClickListener(Recipe recipe) {
mCallback.onRecipeSelected(recipe);
}
public boolean isTablet(Context context) {
// Verifies if the Generalized Size of the device is XLARGE to be
// considered a Tablet
boolean xlarge = ((context.getResources().getConfiguration().screenLayout &
Configuration.SCREENLAYOUT_SIZE_MASK) ==
Configuration.SCREENLAYOUT_SIZE_XLARGE);
// If XLarge, checks if the Generalized Density is at least MDPI
// (160dpi)
if (xlarge) {
DisplayMetrics metrics = new DisplayMetrics();
Activity activity = (Activity) context;
activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
// MDPI=160, DEFAULT=160, DENSITY_HIGH=240, DENSITY_MEDIUM=160,
// DENSITY_TV=213, DENSITY_XHIGH=320
if (metrics.densityDpi == DisplayMetrics.DENSITY_DEFAULT
|| metrics.densityDpi == DisplayMetrics.DENSITY_HIGH
|| metrics.densityDpi == DisplayMetrics.DENSITY_MEDIUM
|| metrics.densityDpi == DisplayMetrics.DENSITY_TV
|| metrics.densityDpi == DisplayMetrics.DENSITY_XHIGH) {
// Yes, this is a tablet!
return true;
}
}
// No, this is not a tablet!
return false;
}
@Override
public void onChanged(@Nullable List<Recipe> recipes) {
initRecipeAdapter(recipes);
}
@Override
public void onConnectionChange(ConnectivityEvent event) {
if (event.getState().getValue() == ConnectivityState.CONNECTED) {
// device has active internet connection
getRecipes();
} else {
// there is no active internet connection on this device
}
}
public interface OnRecipeItemClickListener {
void onRecipeSelected(Recipe recipe);
}
}
|
JavaScript | UTF-8 | 4,035 | 2.515625 | 3 | [] | no_license | import React, { useState, useEffect } from 'react'
import { useSelector, useDispatch } from 'react-redux'
import { editGraphic, getGraphicsById } from '../actions/GraphicsActions';
import { addGraphic } from './../actions/GraphicsActions';
import Error from '../components/Error'
import Loading from './../components/Loading';
import Success from './../components/Success';
import { getGraphicsByIdReducer, editGraphicReducer } from './../reducers/GraphicsReducer';
export default function EditGraphics({ match }) {
const dispatch = useDispatch()
const [name, setname] = useState('')
const [twogbramprice, settwogbramprice] = useState()
const [fourgbramprice, setfourgbramprice] = useState()
const [eightgbramprice, seteightgbramprice] = useState()
const [image, setimage] = useState('')
const [model, setmodel] = useState('')
const [description, setdescription] = useState('')
const getgraphicidbystate = useSelector(state => state.getGraphicsByIdReducer)
const { graphic, error, loading } = getgraphicidbystate
const editgraphicstate = useSelector((state)=> state.editGraphicReducer)
const {editloading , editerror , editsuccess } = editgraphicstate
useEffect(() => {
if(graphic)
{
if(graphic._id==match.params.graphicid)
{
setname(graphic.name)
setdescription(graphic.description)
setmodel(graphic.model)
settwogbramprice(graphic.prices[0]['two_gb_ram'])
setfourgbramprice(graphic.prices[0]['four_gb_ram'])
seteightgbramprice(graphic.prices[0]['eight_gb_ram'])
setimage(graphic.image)
}
else{
dispatch(getGraphicsById(match.params.graphicid))
}
}
else
{
dispatch(getGraphicsById(match.params.graphicid))
}
}, [graphic , dispatch])
function formHandler(e) {
e.preventDefault();
const editedgraphic = {
_id : match.params.graphicid,
name,
image,
description,
model,
prices: {
two_gb_ram: twogbramprice,
four_gb_ram: fourgbramprice,
eight_gb_ram: eightgbramprice,
}
}
dispatch(editGraphic(editedgraphic))
}
return (
<div>
<div className='text-left shadow-lg p-3 mb-5 bg-white rounded'>
<h1><i><strong>Edit Pizza</strong></i></h1>
{loading && (<Loading />)}
{error && (<Error error='something went wrong' />)}
{editsuccess && (<Success success= ' graphic card details updated successfully'/>)}
{editloading && (<Loading />)}
<form onSubmit={formHandler}>
<input className='form-control' type="text" placeholder="name" value={name} onChange={(e) => { setname(e.target.value) }}></input>
<input className='form-control' type="text" placeholder="2 Gb RAM price" value={twogbramprice} onChange={(e) => { settwogbramprice(e.target.value) }}></input>
<input className='form-control' type="text" placeholder="4 Gb RAM price" value={fourgbramprice} onChange={(e) => { setfourgbramprice(e.target.value) }}></input>
<input className='form-control' type="text" placeholder="8 Gb RAM price" value={eightgbramprice} onChange={(e) => { seteightgbramprice(e.target.value) }}></input>
<input className='form-control' type="text" placeholder="Model" value={model} onChange={(e) => { setmodel(e.target.value) }}></input>
<input className='form-control' type="text" placeholder="description" value={description} onChange={(e) => { setdescription(e.target.value) }}></input>
<input className='form-control' type="text" placeholder="Image" value={image} onChange={(e) => { setimage(e.target.value) }}></input>
<button className='btn mt-3' type='submit' ><i>EDIT Graphic card Details </i></button>
</form>
</div>
</div>
)
}
|
Java | UTF-8 | 802 | 1.9375 | 2 | [] | no_license | package uz.pdp.appdatarest.repository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import org.springframework.data.rest.core.annotation.RestResource;
import uz.pdp.appdatarest.entity.Address;
import uz.pdp.appdatarest.projection.CustomAddress;
@RepositoryRestResource(path = "address", collectionResourceRel = "list", excerptProjection = CustomAddress.class)
public interface AddressRepository extends JpaRepository<Address, Integer> {
@RestResource(path = "byName")
Page<Address> findAllByCity(@Param("city") String city, Pageable pageable);
}
|
Markdown | UTF-8 | 19,180 | 3.046875 | 3 | [] | no_license | ---
title: 'Maker, Builder, Hacker'
tags:
- about
- hackers
- computer science
date: 2017-01-24 02:43:30
categories:
- ethics
layout: post
---
Over the weekend I read *A Portrait of J. Random Hacker*, an article about the people of "the hacker community" according to a Usenet survey (I couldn't find any information about the author other than that his first name might be "James"). The article discusses a few different attributes of "the hacker," to the end of showing outsiders who they are and what makes them tick. <!-- MORE -->In general, the article rejected the pop culture hacker profile (unkempt, overweight basement dweller who hacks day and night while pizza boxes and Mountain Dew bottles pile up around him). Instead, this article portrays hackers as open-minded, avid intellectuals.
> Intelligent. Scruffy. Intense. Abstracted. Surprisingly for a sedentary profession, more hackers run to skinny than fat; both extremes are more common than elsewhere. Tans are rare.
> *[...]*
> When asked, hackers often ascribe their culture's gender- and color-blindness to a positive effect of text-only network channels, and this is doubtless a powerful influence. Also, the ties many hackers have to AI research and [science fiction] literature may have helped them to develop an idea of personhood that is inclusive rather than exclusive- after all, if one's imagination readily grants full human rights to AI programs, robots, dolphins, and extraterrestrial aliens, mere color and gender can't seem very important any more.
As much as the article seems to address the question *what is a hacker?*, its answer would be "someone with these characteristics," an answer I do not find satisfactory. So before I continue my discussion of *A Portrait of J. Random Hacker* I'd like to establish a working definition of "**hacker**".
*Hackers and Painters* is a short essay by Paul Graham about the semantics of "hacker," "computer science," and other terms in that ballpark. For example, if I asked you, "what *is* computer science?" what would you say? Before reading this article, I might have said something to the effect of "the field of mathematics concerned with algorithms and computation." Right away then I might say to myself "well not so fast Mr. Computer Science Major, what are you doing in engineering classes?" Touche. It's gotta be more than that specific area of math. I think Graham puts it well:
> The main reason I don't like [the term "computer science"] is that there's no such thing. Computer science is a grab bag of tenuously related areas thrown together by an accident of history, like Yugoslavia.
> -- Paul Graham, Hackers and Painters
Including such tenuously related areas as [discrete math](https://en.wikipedia.org/wiki/Discrete_mathematics), [processor design](https://en.wikipedia.org/wiki/Processor_design), and [information systems](https://en.wikipedia.org/wiki/Information_system). Let's keep reading:
> At one end you have people who are really mathematicians, but call what they're doing computer science so they can get DARPA grants. In the middle you have people working on something like the natural history of computers-- studying the behavior of algorithms for routing data through networks, for example. And then at the other extreme you have the hackers, who are trying to write interesting software, and for whom computers are just a medium of expression, as concrete is for architects or paint for painters.
> -- Paul Graham, Hackers and Painters
Finally, back to hackers. Graham however seems to be talking about the "hackathon hacker," a tinkerer, a maker. This sort of hacking is widely accepted as such in CS communities even though it is direct opposition to the popular hacker profile (constructive, rather than destructive).
---
The question was posed to me whether I think I am a hacker. While it would be easy for me to say that I identify as a hacker (which I do in some ways) and end it there, I have a more interesting exercise in mind. First, we will assume:
1. That *A Portrait*'s hacker characteristics list is accurate, and
2. That the question "are you a hacker" can be answered by how well you fit that checklist (an admittedly naieve assumption).
The article divides the titular portrait into 18 categories, and I will give myself a score out of 100 in each category based on how well I fit the portrait.
### General Appearance
The article describes the average hacker as "intelligent," "scruffy," "intense," and more likely skinny than fat. There's not a lot to go off in this three-line section. I tend not to be scruffy, though I do tend to be skinny. Overall, I guess I'm about half-hacker here.
**Points awarded:** 50 | **Cumulative hacker score:** 50/100
### Dress
*A Portrait* denies the "National Lampoon nerd stereotype" emphasising that hackers dress for comfort above all else. Long hair (facial and on top) is common, as are printed T-shirts and sandals. Business suits are really the only thing not on the table. I for one happen to enjoy a well-fitted suit, though I appreciate dressing for comfort. That being said, I just don't have the hacker hair (short, trim on top, clean shaven in front) and can't give myself too many points here.
**Points awarded:** 20 | **Cumulative hacker score:** 70/200
### Reading Habits
I like the word the article uses here: "omnivorous." The article emphasises the popularity of science and science fiction among hackers. Yesterday, I finished *Perelandra*, the second installment in C.S. Lewis' *Space Trilogy*. After this trilogy, I plan on tackling Asimov's *Foundation Series*; I think I'm starting to fit in. The article also mentions the ferocity with which hackers consume books: while I wouldn't call myself an aggressive reader, I have (at least recently) been very consistent with my reading, something for which I'll give myself a few points (and a pat on the back).
**Points awarded:** 90 | **Cumulative hacker score:** 160/300
### Other Interests
The article lists "science fiction" (check), "music" (check), and medievalism (maybe not check) as other interests of hackers. It also lists board games like chess (check) and go (not check) and other "intellectual games," logic puzzles, and finally role playing games. I've never gravitated to a game solely because I felt it was intellectual, though I do enjoy logic puzzles and my favorite genre (if you want to call it that) of video game is certainly role playing (I'm looking at you, Bethesda).
**Points awarded:** 65 | **Cumulative hacker score:** 225/400
### Physical Activity and Sports
Apparently, most hackers aren't much into sports. I don't anticipate I'll do well in this category. I do however agree with the hacker sentiment that "sports are something one **does**" (rather than views; this is cited as a reason for the near complete lack of sports spectatorship in hacker circles). You'd much sooner find me running around St. Mary's lake than spending a whole Sunday watching football.
**Points awarded:** 25 | **Cumulative hacker score:** 250/500
### Education
Hackers are "college-degreed" or "self-educated to an equivalent level"; I'm working on it. The hacker community values self-teaching as a manifestation of self-motivation and curiosity (both of which are essential hacker traits). I also value self teaching; my entire career as a developer has, at this point, been built entirely on knowledge I taught myself from the internet (and a couple books) (I've been a paid web developer for the better part of three years [not a skilled or masterful web developer for three years, just paid], a field about which I've learned virtually nothing from my coursework).
**Points awarded:** 100 | **Cumulative hacker score:** 350/600
### Things Hackers Detest and Avoid
This, like the [General Appearance]() section, is short. The whole thing is an enumeration of, believe it or not, things hackers dislike, and from that list I can only pick two that I share: dishonesty and boredom.
**Points awarded:** 25 | **Cumulative hacker score:** 375/700
### Food
Big money, Pat, big money. Ethnic food, spicy food, Chinese food; three groups of food that top the favorites lists of hackers and me. Bonus points since I also fit the food profile of hackers in my area (the article mentions that West coast hackers also love Mexican food). We use pizza and microwave burritos as a tool, not a staple.
**Points awarded:** 100 | **Cumulative hacker score:** 475/800
### Politics
The author puts hackers "vaguely left of center." I see myself as vaguely right of center (though [politicalcompass.org](https://www.politicalcompass.org) puts me just left of center [see below]). The article also names a strong libertarian contingent within the hacker cohort; yours truly is a registered libertarian of the State of California. Furthermore, the article says hackers live by their political ideals day-to-day, something which I also try to do (gotta practice what you preach!) I hesitate to give myself a full score, however, since I lack the political militancy, or at least idiosyncratic ideas hinted at in the article.
**Points awarded:** 90 | **Cumulative hacker score:** 565/900

### Gender and Ethnicity
If you thought that hackers were predominantly white males, then you thought right. While I, when given the opportunity, say I identify with two races (having been raised among both American and [Indo](https://en.wikipedia.org/wiki/Indo_people) culture [it comes as a surprise to most people that I'm part Indonesian, and yes I meant "Indo," not "Indonesian" a few words back]), I am, for all intents and purposes, still white. And a man (that one's a little more cut and dry for me). Fortunately, just like computer science as a whole, the article reports that hackerdom is experiencing an upswing in diversity, particularly from women and Asians. There was something else in this section that really spoke to me: through their exposure to AI research, science fiction, etc., hackers are open minded about what it means to be human (see the blockquote way above). I can't say I've totally figured this issue out, but I can definitely say that my exposure to the mentioned areas has influenced my outlook.
**Points awarded:** 95 | **Cumulative hacker score:** 660/1000
### Religion
Unsurprisingly it seems that hackers are a generally atheistic crowd. I enjoyed the article's mention of "parody religions" like Discordianism and the Church of SubGenius (perhaps [Pastafarianism](https://en.wikipedia.org/wiki/Flying_Spaghetti_Monster) was less popular at the time of writing; it was excluded from this list). I for one am a semi-active Catholic. While I don't see religion (or perhaps more specifically, the practice of religion) at the core of my identity, it's a big enough part that I'm not really with the hackers on this one.
**Points awarded:** 10 | **Cumulative hacker score:** 670/1100
### Ceremonial Chemicals
"Most hackers don't smoke," (check), "and use alcohol in moderation if at all" (check). Psychedelics appear to have lost steam, but are still generally accepted and tolerated (similar to my outlook: I personally don't partake in those drugs, but I don't mind if you do so long as you mind your own business while you do 'em). Finally, the section mentions caffeine. Like pizza and microwave burritos, hackers and I use caffeine as a tool of productivity.
**Points awarded:** 80 | **Cumulative hacker score:** 750/1200
### Communication Style
"They are often better at writing than at speaking." Mmmm, nope. Not me. I was an avid debater in high school, and still maintain some proficiency at public speaking. My writing, however, has definitely gone downhill since then (though I'm hoping that through practice in this blog and by steadily ramping up my reading, that I'll slowly regain some prowess here).
**Points awarded:** 15 | **Cumulative hacker score:** 765/1300
### Geographical Distribution
Not much to discuss here. Hackers are concentrated in SF (my home for next summer) and Boston, with cohorts in LA, the Pacific Northwest (holla) and DC (my home last summer). Since I am from one of these hacker hotspots, and have, since moving out of the house, only chosen to live on one of said hotspots, I'm giving myself full points.
**Points awarded:** 100 | **Cumulative hacker score:** 865/1400
### Sexual Habits
Hackers are, according to the article, tolerant of a wide range lifestyles; cool, me too. The article, however, continues, saying that hackers are "somewhat more likely to live in polygynous, polyandrous relationships, practice open marriage, or live in communes or group houses." I'm sure the first two items in that list don't represent the majority of hackers, so I'll simply address the third. I currently live with five awesome roommates, and love my current setup. That said, when given the choice between roommates and my own place, all other things being equal, I can almost guarantee that I'd take the single. Having a private space to just recharge is a great thing for me.
**Points awarded:** 40 | **Cumulative hacker score:** 905/1500
### Personality Characteristics
The article repeatedly cites **intelligence** as a top hacker trait. When I think about myself, I really don't think (much less say) things like "I'm intelligent," "I'm handsome," and not for an lack of esteem, it's just that subconsciously I think I find that sort of narrative toxic and ego-inflating. Point is, when it comes to checking off the "are you intelligent like a hacker" box, I'm at a bit of a stalemate. Let's keep reading the section (it's the longest one).
The section starts off, after again identifying hackers as intelligent, listing things such as "curiosity" and "neophilism" as hacker traits. My parents could tell you that I was born curious, and if you've read this far, you're probably a curious one yourself (or are Peter Bui-- hi Dr. Bui!). I think this trait goes hand in hand with [neophilism](https://en.wikipedia.org/wiki/Neophile), the love of novelty. I never really knew it before reading *A Portrait* but I think my own neophilism drives a lot of other parts of my personality, like wanderlust, love of reading (and watching videos), and that curiosity we were just talking about.
The article also names a certain sort of "control freakishness" common among hackers. It isn't the same sort of control freak as, for example, a [helicopter parent](https://en.wikipedia.org/wiki/Helicopter_parent), but something more internally directed. Hackers and I love making nifty stuff do nifty things for us. I know that for me personally, this is a good explanation for my attraction to open source software- its guts are exposed to me so I can make it mine (that, and it's free). This section also (perhaps in hyperbole) says that hackers' "code is beautiful, even if their desks are burried in 3 feet of crap;" I might not be working amidst mounds of paper and garbage, but I could never ever claim to be the most organized person I know.
We then get to hackers' motivations. They are attracted by new, interesting, and exciting challenges rather than conventional motivators like social approval and money. While I too am drawn to challenge, I can't claim to be so immune to so-called "conventional motivators." Very recently in my life, I chose a path for money over passion. I'm not saying I don't have passion for what lies down that road, only that I have less for it than for the alternative.
Finally the section addresses the Myers-Briggs scale. I've never vested much weight into the results of these tests, though interestingly ever since I first took it in high school, every time I've taken it (which has been a few times, from different providers), I've gotten [INTP](https://en.wikipedia.org/wiki/INTP). And wouldn't you know it, "hackerdom appears to concentrate the relatively rare INTJ and INTP types."
**Points awarded:** 90 | **Cumulative hacker score:** 995/1600
### Weaknesses of the Hacker Personality
I will readily admit that like hackers, I've had times in my life when I found it challenging to identify emotionally with other people, and even more challenging to open up to them. The article goes on the describe an intellectual arrogance common among hackers, something I don't think I share. When working with someone less skilled than me, I readily adopt the role of teacher (and, conversely, readily adopt the role of student when working with someone more skilled); I wouldn't ever consider myself or anyone **better** as a person than anyone else just based on their intellect.
Hackers evidently are also rather intolerant in technical matters, something manifested in the "perennial **holy wars**" of geeks: EMACS vs ViM, tabs vs spaces, etc. I for one am guilty of fighting in these wars (perhaps even more vigorously than my peers). If you ever work on a project with me, the chances of you, afterwards, not knowing that I use ViM are slim to none-- I'm quite, shall we say, outspoken about it.
The section goes on to discuss such traits as sloppiness and disorganization [IRL](https://www.urbandictionary.com/define.php?term=IRL), difficulty maintaining stable relationships, and symptoms of ADD. I don't really identify with any of these problems, so I'll leave it at that.
**Points awarded:** 50 | **Cumulative hacker score:** 1045/1700
### Miscellaneous
I'm giving this section a smaller weight since it does seem to be less consequential to the hacker portrait.
- [ ] Tend to be cat people
- [ ] Drive either junky cars or unkempt fancy cars (if they have the money)
- [ ] Awful handwriting, often in all caps
**Points awarded:** 0 | **Cumulative hacker score:** 1045/1750
## Summary
I scored 1,045 out of the available 1,750, which is about **60%**. This result doesn't surprise me too much (maybe it's a little lower than I would have estimated before starting). That being said, I think it's important to reiterate what I mentioned earlier: that it's a naieve assumption to say that my results on this self-administered "quiz" could answer whether or not I'm a hacker. In reality, this was a test administered by an outsider (me) to an outsider (also me) and only shows how closely my character matches this "average hacker portrait." I don't think I could really call myself a hacker since I'm not a part of that community (at least not the "underground" IRC channels with secret handles and botnets).
It's hard to say whether or not I'll ever be a part of that community. I think my journey into computer security may lead me there (though it could just as easily be the case that it was my "inner hacker" that led me to that field); I don't know. Regardless, what's certain that the community of above-ground, academic hackers who I take classes with (and just about everything else with too) is one that I'll be with [for a long, long time](http://www.evilenglish.net/wp-content/uploads/2014/05/cheesy-cheese-and-corny-corn__600_450_q50.jpg).
#### Sources
- [*A Portrait of J. Random Hacker*](http://bak.spc.org/dms/archive/profile.html)
- [*Hackers and Painters*](http://www.paulgraham.com/hp.html) -- Paul Graham
|
Python | UTF-8 | 807 | 3.015625 | 3 | [] | no_license | import sys
sys.stdin = open("1946_input.txt")
T = int(input())
for test_case in range(1, T+1):
N = int(input())
data = []
for i in range(N):
Ci, Ki = map(str, input().split())
Ki = int(Ki)
# print(Ci, Ki)
for j in range(Ki):
data.append(Ci)
# print(data)
print(f'#{test_case}')
count = 0
for k in data:
print(k, end='')
count += 1
if count == 10:
count = 0
print()
print()
# T = int(input())
# for test_case in range(1, T+1):
# N = int(input())
# print(f'#{test_case}')
# array = ''
# for i in range(N):
# word, times = map(str, input().split())
# array += word*int(times)
#
# for i in range(0, len(array), 10):
# print(array[i:i+10]) |
Shell | UTF-8 | 551 | 2.9375 | 3 | [] | no_license | #!/usr/bin/env sh
# STATE_FILE="${TMPDIR}/breakvpn"
# touch $STATE_FILE
#
# LAST_STATE=`cat ${STATE_FILE}`
#
# ifconfig | grep -q tun0
#
# CURR_STATE=$?
# echo $CURR_STATE >| $STATE_FILE
#
# if [ "$LAST_STATE" != "$CURR_STATE" ]; then
# if [ ${CURR_STATE} -eq 0 ]; then
# breakvpn youtube.com yelp.com www.yelp.com linkedin.com www.linkedin.com news.ycombinator.com en.wikipedia.org service1.ess.apple.com.akadns.net
# fi
# fi
#lockfile -r 0 ${TMPDIR}/ || exit 1
# if [ `curl ifconfig.me` == "" ]; then
# ifconfig | grep tun0
|
Markdown | UTF-8 | 778 | 2.8125 | 3 | [] | no_license | # 查看Python的版本
> GitHub@[orca-j35](https://github.com/orca-j35),所有笔记均托管于 [python_notes](https://github.com/orca-j35/python_notes) 仓库
可使用终端命令来查看 Python 的版本信息:
```shell
(base) C:\WINDOWS\system32>python -VV
Python 3.7.1 (default, Dec 10 2018, 22:54:23) [MSC v.1915 64 bit (AMD64)]
(base) C:\WINDOWS\system32>python -V
Python 3.7.1
(base) C:\WINDOWS\system32>python --version
Python 3.7.1
```
还可通过 `sys` 模块来查看 Python 的版本信息:
```python
import sys
sys.version
#> '3.7.2 (default, Feb 21 2019, 17:35:59) [MSC v.1915 64 bit (AMD64)]'
sys.version_info
#> sys.version_info(major=3, minor=7, micro=2, releaselevel='final', serial=0)
```
查看 pip 版本信息:
```shell
$ pip --version
```
|
C# | UTF-8 | 137 | 2.609375 | 3 | [] | no_license | public static string RemoveSpecialCharacters(string str)
{
return Regex.Replace(str, "[^a-zA-Z0-9_ ]+", "", RegexOptions.Compiled);
} |
Java | UTF-8 | 1,068 | 2.34375 | 2 | [] | no_license | package com.facebook.login.widget;
public enum LoginButton$ToolTipMode
{
AUTOMATIC("automatic", 0), DISPLAY_ALWAYS("display_always", 1), NEVER_DISPLAY("never_display", 2);
public static ToolTipMode DEFAULT = AUTOMATIC;
private int intValue;
private String stringValue;
private LoginButton$ToolTipMode(String paramString, int paramInt)
{
stringValue = paramString;
intValue = paramInt;
}
public static ToolTipMode fromInt(int paramInt)
{
ToolTipMode[] arrayOfToolTipMode = values();
int j = arrayOfToolTipMode.length;
int i = 0;
while (i < j)
{
ToolTipMode localToolTipMode = arrayOfToolTipMode[i];
if (localToolTipMode.getValue() == paramInt) {
return localToolTipMode;
}
i += 1;
}
return null;
}
public int getValue()
{
return intValue;
}
public String toString()
{
return stringValue;
}
}
/* Location:
* Qualified Name: com.facebook.login.widget.LoginButton.ToolTipMode
* Java Class Version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ |
Java | UTF-8 | 8,182 | 2.359375 | 2 | [] | no_license | package info.scce.m3c.transformer;
import static org.junit.jupiter.api.Assertions.assertEquals;
import info.scce.addlib.dd.bdd.BDD;
import info.scce.addlib.dd.bdd.BDDManager;
import info.scce.m3c.cfps.Edge;
import info.scce.m3c.cfps.EdgeType;
import info.scce.m3c.formula.BoxNode;
import info.scce.m3c.formula.DependencyGraph;
import info.scce.m3c.formula.DiamondNode;
import info.scce.m3c.formula.EquationalBlock;
import info.scce.m3c.formula.FormulaNode;
import info.scce.m3c.formula.OrNode;
import info.scce.m3c.formula.TrueNode;
import info.scce.m3c.formula.visitor.ParserMuCalc;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
public class BDDTransformerTest {
private static DependencyGraph dg;
private static BDDManager bddManager;
private static OrNode orNode;
private static DiamondNode diaNode1;
private static DiamondNode diaNode2;
private static BoxNode boxNode;
private static TrueNode trueNode;
@BeforeAll
public static void setup() {
String formula = "mu X.(<b>[b]true | <>X)";
ParserMuCalc parser = new ParserMuCalc();
FormulaNode ast = parser.parse(formula);
dg = new DependencyGraph(ast);
bddManager = new BDDManager();
orNode = (OrNode) ast.getLeftChild();
diaNode1 = (DiamondNode) orNode.getLeftChild();
diaNode2 = (DiamondNode) orNode.getRightChild();
boxNode = (BoxNode) diaNode1.getLeftChild();
trueNode = (TrueNode) boxNode.getLeftChild();
}
@Test
public void testBDDIdentity() {
BDDTransformer transformer = new BDDTransformer(bddManager, dg.getNumVariables());
for (int var = 0; var < transformer.getBdds().length; var++) {
assertEquals(transformer.getBdds()[var], bddManager.ithVar(var));
}
}
@Test
public void testBDDStateInitialization() {
BDDTransformer transformer = new BDDTransformer(bddManager, dg);
for (EquationalBlock block : dg.getBlocks()) {
for (FormulaNode node : block.getNodes()) {
BDD actual = transformer.getBdds()[node.getVarNumber()];
BDD expected;
if (block.isMaxBlock()) {
expected = bddManager.readOne();
} else {
expected = bddManager.readLogicZero();
}
assertEquals(expected, actual);
}
}
}
@Test
public void testEdgeTransformerMust() {
Edge edge = new Edge(null, null, "b", EdgeType.MUST);
BDDTransformer transformer = new BDDTransformer(bddManager, edge, dg);
BDD bddOrNode = transformer.getBdds()[orNode.getVarNumber()];
BDD expectedBDDOrNode = bddManager.readLogicZero();
assertEquals(expectedBDDOrNode, bddOrNode);
BDD bddDiaNode1 = transformer.getBdds()[diaNode1.getVarNumber()];
BDD expectedBDDDiaNode1 = bddManager.ithVar(diaNode1.getVarNumberLeft());
assertEquals(expectedBDDDiaNode1, bddDiaNode1);
BDD bddDiaNode2 = transformer.getBdds()[diaNode2.getVarNumber()];
BDD expectedBDDDiaNode2 = bddManager.ithVar(diaNode2.getVarNumberLeft());
assertEquals(expectedBDDDiaNode2, bddDiaNode2);
BDD bddBoxNode = transformer.getBdds()[boxNode.getVarNumber()];
BDD expectedBDDBoxNode = bddManager.ithVar(boxNode.getVarNumberLeft());
assertEquals(expectedBDDBoxNode, bddBoxNode);
BDD bddTrueNode = transformer.getBdds()[trueNode.getVarNumber()];
BDD expectedBDDTrueNode = bddManager.readLogicZero();
assertEquals(expectedBDDTrueNode, bddTrueNode);
}
@Test
public void testEdgeTransformerNoMatch() {
Edge edge = new Edge(null, null, "a", EdgeType.MUST);
BDDTransformer transformer = new BDDTransformer(bddManager, edge, dg);
BDD bddOrNode = transformer.getBdds()[orNode.getVarNumber()];
BDD expectedBDDOrNode = bddManager.readLogicZero();
assertEquals(expectedBDDOrNode, bddOrNode);
BDD bddDiaNode1 = transformer.getBdds()[diaNode1.getVarNumber()];
BDD expectedBDDDiaNode1 = bddManager.readLogicZero();
assertEquals(expectedBDDDiaNode1, bddDiaNode1);
BDD bddDiaNode2 = transformer.getBdds()[diaNode2.getVarNumber()];
BDD expectedBDDDiaNode2 = bddManager.ithVar(diaNode2.getVarNumberLeft());
assertEquals(expectedBDDDiaNode2, bddDiaNode2);
BDD bddBoxNode = transformer.getBdds()[boxNode.getVarNumber()];
BDD expectedBDDBoxNode = bddManager.readOne();
assertEquals(expectedBDDBoxNode, bddBoxNode);
BDD bddTrueNode = transformer.getBdds()[trueNode.getVarNumber()];
BDD expectedBDDTrueNode = bddManager.readLogicZero();
assertEquals(expectedBDDTrueNode, bddTrueNode);
}
@Test
public void testEdgeTransformerMay() {
Edge edge = new Edge(null, null, "b", EdgeType.MAY);
BDDTransformer transformer = new BDDTransformer(bddManager, edge, dg);
BDD bddOrNode = transformer.getBdds()[orNode.getVarNumber()];
BDD expectedBDDOrNode = bddManager.readLogicZero();
assertEquals(expectedBDDOrNode, bddOrNode);
BDD bddDiaNode1 = transformer.getBdds()[diaNode1.getVarNumber()];
BDD expectedBDDDiaNode1 = bddManager.readLogicZero();
assertEquals(expectedBDDDiaNode1, bddDiaNode1);
BDD bddDiaNode2 = transformer.getBdds()[diaNode2.getVarNumber()];
BDD expectedBDDDiaNode2 = bddManager.readLogicZero();
assertEquals(expectedBDDDiaNode2, bddDiaNode2);
BDD bddBoxNode = transformer.getBdds()[boxNode.getVarNumber()];
BDD expectedBDDBoxNode = bddManager.ithVar(boxNode.getVarNumberLeft());
assertEquals(expectedBDDBoxNode, bddBoxNode);
BDD bddTrueNode = transformer.getBdds()[trueNode.getVarNumber()];
BDD expectedBDDTrueNode = bddManager.readLogicZero();
assertEquals(expectedBDDTrueNode, bddTrueNode);
}
@Test
public void testComposition() {
BDDTransformer transformer = new BDDTransformer(bddManager, dg);
BDDTransformer identity = new BDDTransformer(bddManager, dg.getNumVariables());
BDDTransformer composition = transformer.compose(identity);
assertEquals(5, composition.getBdds().length);
assertEquals(transformer, composition);
BDDTransformer inverseComposition = identity.compose(transformer);
assertEquals(transformer, inverseComposition);
}
@Test
public void testOrBDDListOnes() {
Edge edge = new Edge(null, null, "b", EdgeType.MUST);
BDDTransformer edgeTransformer = new BDDTransformer(bddManager, edge, dg);
BDDTransformer oneTransformer = new BDDTransformer(bddManager);
oneTransformer.setIsMust(true);
BDD[] oneBDDs = new BDD[dg.getNumVariables()];
for (int var = 0; var < oneBDDs.length; var++) {
oneBDDs[var] = bddManager.readOne();
}
oneTransformer.setBDDs(oneBDDs);
List<BDDTransformer> comps = new ArrayList<>();
comps.add(edgeTransformer);
comps.add(oneTransformer);
BDD disjunction = edgeTransformer.orBddList(comps, diaNode1.getVarNumber());
assertEquals(bddManager.readOne(), disjunction);
}
@Test
public void testOrBDDListZeros() {
Edge edge = new Edge(null, null, "b", EdgeType.MUST);
BDDTransformer edgeTransformer = new BDDTransformer(bddManager, edge, dg);
BDDTransformer oneTransformer = new BDDTransformer(bddManager);
oneTransformer.setIsMust(true);
BDD[] oneBDDs = new BDD[dg.getNumVariables()];
for (int var = 0; var < oneBDDs.length; var++) {
oneBDDs[var] = bddManager.readLogicZero();
}
oneTransformer.setBDDs(oneBDDs);
List<BDDTransformer> comps = new ArrayList<>();
comps.add(edgeTransformer);
comps.add(oneTransformer);
BDD disjunction = edgeTransformer.orBddList(comps, diaNode1.getVarNumber());
assertEquals(bddManager.ithVar(diaNode1.getVarNumberLeft()), disjunction);
}
}
|
Markdown | UTF-8 | 1,147 | 3.296875 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | # :clock4: `timefmt`
> A tiny time converting util for the command line.
[](https://travis-ci.com/PDDStudio/timefmt)
## :package: Installation
You can choose one of the following ways to install `timefmt`
### :beginner: Install via your favorite Node Package Manager
You can use `npm` or `yarn` (or any other package manager of your choice) to install this utility.
```sh
# when using npm
npm i -g timefmt
# when using yarn
yarn global add timefmt
```
### :beers: Install via Homebrew (MacOS)
If you've [Homebrew](https://brew.sh) installed, simply run:
```sh
# tap the timefmt formula
brew tap pddstudio/timefmt
# Install timefmt using brew
brew install timefmt
```
## :question: Usage
_See `timefmt --help` for usage instructions._
Convert `1m 30s` to `ms`:
```sh
timefmt 1m 30s --output ms
# => The given input time 1m 30s equals: 90000 ms
```
### :information_source: Usage Information
```
Run timefmt --help for a list of all available commands, conversion outputs and more.
```
## :star: License
MIT License - See [LICENSE](./LICENSE) for details.
|
Java | GB18030 | 6,721 | 2.953125 | 3 | [] | no_license | import java.awt.Color;
import java.awt.Graphics;
import java.io.FileNotFoundException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Random;
import javax.swing.JPanel;
/**
* ģ
*/
class Snake extends JPanel {
public final static int LEFT = 1; //ĸ
public final static int UP = 2;
public final static int RIGHT = 3;
public final static int DOWN = 4;
private static int NODE_WIDTH = 10; //
private static int NODE_HEIGHT= 10; //߶
private int width = 50; //
private int height = 30; //߶
private int level = 1; //ĬΪһ
private Node food; //ʳ
public boolean[][] matrix; //ijǷϰtrueΪͨ(ʳλҲΪtrue)falseΪͨ
private LinkedList<Node> snakeModel = new LinkedList<Node>(); //壬ͷΪͷ
private LinkedList<Node> barrier = new LinkedList<Node>(); //ϰ
private boolean running = false; //ϷǷ
private int direction = UP; //ǰ˶,ĬΪ
private int score = 0; //
private int timeInterval = 350;// ʱ䣨ٶȣ
private double speedChangeRate = 0.75;// ٶȸı̶
private boolean paused = true;// Ϸ״̬
public void setLevel(int level) {
this.level = level;
}
public int getLevel() {
return level;
}
public void setRunning(boolean state) {
running = state;
}
public boolean getRunning() {
return running;
}
public void setTimeInterval(int timeInterval) {
this.timeInterval = timeInterval;
}
public int getTimeInterval() {
return timeInterval;
}
public void setPaused(boolean state) {
this.paused = state;
}
public boolean getPaused() {
return paused;
}
//ı䷽
public void setDirection(int direction) {
if (this.direction % 2 != direction % 2) {// ͻ
this.direction = direction;
}
}
//ϰ
public void setBarrier(boolean matrix[][]) {
for (int i = 0; i < 30; i++)
for (int j = 0; j < 50; j++) {
if (true == matrix[i][j]) {
barrier.add(new Node(j, i));
}
}
}
//Ϸʼ
public void initial() throws FileNotFoundException {
//ʼ
String fileName;
switch(level) {
case 1:
fileName = "matrix1.txt";
break;
case 2:
fileName = "matrix2.txt";
break;
case 3:
fileName = "matrix3.txt";
break;
case 4:
fileName = "matrix4.txt";
break;
case 5:
fileName = "matrix5.txt";
break;
case 6:
fileName = "matrix6.txt";
break;
case 7:
fileName = "matrix7.txt";
break;
case 8:
fileName = "matrix8.txt";
break;
case 9:
fileName = "matrix9.txt";
break;
case 10:
fileName = "matrix10.txt";
break;
default: fileName = "matrix1.txt";
}
//ʼ
matrix = GreedSnake.readMatrix(fileName);
//ϰԭ
barrier.clear();
setBarrier(matrix); //ϰֻδĹmatrix³ʼ
direction = 2;
score = 0;
timeInterval = 350;
paused = true;
//ģԭ
snakeModel.clear();
int x = 0, y = 0;
for (int i = 0; i < 8; i++) { //ʼ,ʼΪ8,λĻ
x = width / 2 + i;
y = height / 2;
Node node = new Node(x, y);
matrix[y][x] = true; //λΪϰ
snakeModel.addLast(node);
}
//ʳ
food = createFood();
repaint();
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
//ɫɫ
g.setColor(Color.LIGHT_GRAY);
g.fillRect(0, 0, 500, 300);
//ɫƷְ
g.setColor(Color.WHITE);
g.drawString("" + String.valueOf(level) + "", 220, 20);
g.drawString(String.valueOf(score) + " ", 250, 20);
//ڻɫߵͷ
g.setColor(Color.DARK_GRAY);
drawNode(g, snakeModel.getFirst());
//ɫ
g.setColor(Color.BLACK);
Iterator<Node> snakeModelIt = snakeModel.iterator();
snakeModelIt.next();
while (snakeModelIt.hasNext()) {
drawNode(g, snakeModelIt.next());
}
//ɫʳ
g.setColor(Color.RED);
drawNode(g, food);
//ϰ
g.setColor(Color.MAGENTA);
Iterator<Node> barrierIt = barrier.iterator();
while (barrierIt.hasNext()) {
drawNode(g, barrierIt.next());
}
}
// 캯
public Snake(boolean[][] matrix) {
this.matrix = matrix; //ϰ
setBarrier(matrix); //ϰֻδĹmatrix³ʼ
int x = 0, y = 0;
for (int i = 0; i < 8; i++) { //ʼ,ʼΪ8,λĻ
x = width / 2 + i;
y = height / 2;
Node node = new Node(x, y);
matrix[y][x] = true; //λΪϰ
snakeModel.addLast(node);
}
//ʳ
food = createFood();
}
//Ƶ,ϷеΪʵʻͼ1/10ϷƶһΪ10ص
private void drawNode(Graphics g, Node n) {
g.fillRect(n.x * NODE_WIDTH, n.y * NODE_HEIGHT, NODE_WIDTH - 1, NODE_HEIGHT - 1);
}
//ƶ
public boolean move() {
int x = snakeModel.getFirst().x;
int y = snakeModel.getFirst().y;
switch(direction) {
case LEFT :
x--;
break;
case UP :
y--;
break;
case RIGHT :
x++;
break;
case DOWN :
y++;
break;
}
if ((x >= 0 && x < width) && (y >= 0 && y < height)) {
if (matrix[y][x]) {// Եʳײ
//Եƻ,ͷ
if (food.x == x && food.y == y) {
Node node = new Node(food.x, food.y);
snakeModel.addFirst(node);
food = createFood();
score++; //һ
return true;
} else { //ϰ
return false;
}
} else { //ͨƶ
Node node = new Node(x, y);
snakeModel.addFirst(node); //µĽ
matrix[y][x] = true; //߾ĵطΪϰ
x = snakeModel.getLast().x;
y = snakeModel.getLast().y;
snakeModel.removeLast(); //ɾһ
matrix[y][x] = false; //뿪ĵطΪϰ
return true;
}
}
//Ϸʧ
return false;
}
//ʳ
private Node createFood() {
Random random = new Random();
int x, y;
do {
x = random.nextInt(width);
y = random.nextInt(height);
} while(matrix[y][x]);
matrix[y][x] = true;
return new Node(x, y);
}
//
public void speedUp() {
if (timeInterval >= 50) //ٶΪ50ms
timeInterval *= speedChangeRate;
}
//
public void speedDown() {
if (timeInterval <= 1000) //СٶΪ1000ms
timeInterval /= speedChangeRate;
}
//ͣʼ
public void changePauseState() {
paused = !paused;
}
} |
Ruby | UTF-8 | 829 | 3.203125 | 3 | [] | no_license | require 'spec_helper'
require_relative '../src/array_chunk'
RSpec.describe ArrayChunk do
describe 'positive test cases' do
it "should return the correct result" do
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
expect(ArrayChunk.chunk(arr, 2)).to eql([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]])
end
it "test case when the chunk size is 1" do
arr = [1, 2, 3]
expect(ArrayChunk.chunk(arr, 1)).to eql([[1], [2], [3]])
end
it "test case when the chunk size is 3" do
arr = [1, 2, 3, 4, 5]
expect(ArrayChunk.chunk(arr, 3)).to eql([[1, 2, 3], [4, 5]])
end
it "test case when the chunk size is 5" do
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
expect(ArrayChunk.chunk(arr, 5)).to eql([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13]])
end
end
end
|
C# | UTF-8 | 4,330 | 2.640625 | 3 | [
"Apache-2.0"
] | permissive | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Jungo.Infrastructure.Cache;
using Newtonsoft.Json;
namespace Jungo.Infrastructure.Config
{
public class JsonFileConfigLoader : IConfigLoader
{
public JsonFileConfigLoader(ICacheFactory cacheFactory, IConfigPathMapper configPathMapper)
{
_cache = cacheFactory.GetCache<string>("Config");
_configPathMapper = configPathMapper;
LocateEnvironment();
}
private readonly IConfigPathMapper _configPathMapper;
private readonly ICache<string> _cache;
private string _environment;
private const string EnvironmentFile = "environment.txt";
private string _configPath;
private void LocateEnvironment()
{
var appPath = _configPathMapper.Map("~");
var dirInfo = new DirectoryInfo(appPath);
while (dirInfo != null && string.IsNullOrEmpty(_configPath))
{
var configDir = Path.Combine(dirInfo.FullName, "Config");
if (Directory.Exists(configDir))
_configPath = configDir;
else
dirInfo = Directory.GetParent(dirInfo.FullName);
}
if (string.IsNullOrEmpty(_configPath))
throw new Exception("No Config folder in or up from application root");
var envirFilename = Path.Combine(_configPath, EnvironmentFile);
if (!File.Exists(envirFilename))
throw new Exception("Missing " + envirFilename);
_environment = File.ReadAllText(envirFilename).Trim();
if (string.IsNullOrEmpty(_environment))
throw new Exception(envirFilename + " is empty. Put the name of your current environment there, such as Development.");
}
#region IConfigLoader Members
public T Get<T>() where T : class
{
string json;
var cacheKey = typeof (T).Name;
if (!_cache.TryGet(cacheKey, out json))
{
if (TryReadConfig(cacheKey, out json))
_cache.Add(cacheKey, json);
}
if (string.IsNullOrEmpty(json)) return null;
var instance = JsonConvert.DeserializeObject<T>(json);
if (instance == null)
throw new Exception("The type " + typeof (T) + " could not be initialized.");
return instance;
}
#endregion
private static string NormalizeName(string name)
{
return name.EndsWith("Config") ? name.Remove(name.Length - 6) : name;
}
private bool TryReadConfig(string configName, out string value)
{
value = null;
try
{
var jsonFile = NormalizeName(configName) + ".json";
var pieces = _environment.Split('.');
var searchPaths = new List<string>
{
Path.Combine(_configPath, "Local", jsonFile),
};
for (var pi = pieces.Length; pi > 0; pi--)
{
var pth = string.Join("\\", pieces, 0, pi);
searchPaths.Add(Path.Combine(_configPath, pth, jsonFile));
}
searchPaths.Add(Path.Combine(_configPath, jsonFile));
var configFileInfo = searchPaths.Select(p => new FileInfo(p))
.FirstOrDefault(fi => fi != null && fi.Exists);
if (configFileInfo == null)
{
//todo: _logger.Debug("Not found {0} in {1}", configKey, string.Join(";", searchPaths));
return false;
}
using (var f = configFileInfo.OpenText())
{
value = f.ReadToEnd();
}
//todo: _logger.Debug("Read configuration '{0}' for '{1}' from {2}", configKey.Name, configKey.ToString(), configFileInfo.FullName);
return true;
}
catch (Exception e)
{
//todo: _logger.Warn(e, "Cannot resolve configuration file for {0}: {1}", configKey, e.Message);
}
return false;
}
}
}
|
Java | UTF-8 | 434 | 3.046875 | 3 | [] | no_license | package mypack;
public class DP implements Comparable<DP> {
private double x;
public DP(double x){
this.x = x;
}
public double getX() {
return x;
}
@Override
public int compareTo(DP o) {
/*if (this.x >= o.getX()) {
return 1;
}else{
return -1;
}*/
return (this.getX() <o.getX() ? -1 : (this.getX() == o.getX() ? 0 : 1));
}
}
|
C++ | UTF-8 | 501 | 2.875 | 3 | [] | no_license | #include<iostream>
using namespace std;
class LongDouble{
public:
LongDouble(double x=0.0):db(x){}
operator double();
operator float();
operator int();
private:
int in;
double db;
};
LongDouble::operator double(){
cout<<"operator double"<<endl;
return db;
}
LongDouble::operator float(){
cout<<"operator float"<<endl;
return db;
}
LongDouble::operator int(){
return db;
}
int mainExam14_44(){
LongDouble ldobj(2.3);
int ex1=ldobj;
float ex2=ldobj;
return 0;
}
|
C | UTF-8 | 1,566 | 3.265625 | 3 | [
"MIT"
] | permissive | /*
Biblioteca desenvolvida por Hélter Pinheiro para trabalho de E.D
Lista simplesmente encadeada
Data: 21/10/2018
*/
#ifndef LISTA_H_
#define LISTA_H_
#define TRUE 0
#define FALSE 1
/*
estrutura correspondente ao nó da lista
*/
typedef struct _slnode_{
struct _slnode_*next;
void *data;
}Slnode;
/*
Nós da lista
*/
typedef struct _sllist_{
Slnode *first;
Slnode *cur;
}Sllist;
#ifdef LISTA_C_
Sllist* sllCreate(); // cria uma lista simplesmente encadeada
void* sllFirst(Sllist *l); // retorna o primeiro da lista
void* sllGetNext(Sllist *l); // prega o próximo nó da lista
int sllDestroy(Sllist *l); // destroi a lisa (apenas quando não há nenhum nó sobrando)
int sllInsertFirst(Sllist *l, void *data);// insere na primeira posição da lista
void *sllRemoveSpec(Sllist *l, void* key, int (*comp)(void*,void*)); // remove determinado nó da lista
void *sllQuery(Sllist *l, void *key, int(*comp)(void*,void*)); //procura determinado nó da lista
int sllInsertAfterSpec(Sllist *l, void *key, int(*comp)(void*,void*), void*data);// insere na lista um nó depois do nó especificado
#else
extern Sllist* sllCreate();
extern void* sllFirst(Sllist *l);
extern void* sllGetNext(Sllist *l);
extern int sllDestroy(Sllist *l);
extern int sllInsertFirst(Sllist *l, void *data);
extern void *sllRemoveSpec(Sllist *l, void* key, int (*comp)(void*,void*));
extern void *sllQuery(Sllist *l, void *key, int(*comp)(void*,void*));
extern int sllInsertAfterSpec(Sllist *l, void *key, int(*comp)(void*,void*), void*data);
#endif //LISTA_C_
#endif //LISTA_H_
|
TypeScript | UTF-8 | 1,196 | 2.625 | 3 | [
"MIT"
] | permissive | let workspaces:string[] = []
function remove(name:string){
workspaces = workspaces.filter( v => v !== name )
browser.storage.sync.set({ workspaces }).then(() => {
reload()
browser.runtime.sendMessage('reloadContextMenu');
})
}
function reload(){
browser.storage.sync.get(['workspaces']).then((storageGetResult) => {
workspaces = storageGetResult.workspaces || []
const listElement = document.getElementById('workspaces')
if(!listElement) return
while (listElement.lastChild) {
listElement.removeChild(listElement.lastChild);
}
workspaces.forEach((name)=>{
const li = document.createElement('li')
const span = document.createElement('span')
span.innerText = name + '.slack.com'
const a = document.createElement('a')
a.href = '#'
a.innerText = 'x'
a.dataset.name = name
a.addEventListener('click',(e)=>{
console.log("click")
var target = e.target as HTMLAnchorElement;
if (!target) return;
remove(target.dataset.name as string)
})
li.appendChild(span)
li.appendChild(a)
listElement.appendChild(li)
})
})
}
reload()
console.log('options')
|
Python | UTF-8 | 144 | 2.9375 | 3 | [] | no_license | sh=int(input())
si=list(map(int,input().split()))
l1=si[1:sh:2]
l2=si[0:sh:2]
if(sum(l1)>=sum(l2)):
print(sum(l1))
else:
print(sum(l2))
|
Markdown | UTF-8 | 3,958 | 3.53125 | 4 | [] | no_license | # Project1B
## Goals
A startup called Sparkify wants to analyze the data they've been collecting on songs and user activity on their new music streaming app and the data resides in a directory of CSV files on user activity on the app.
In order to answer their question to the data, I will create an Apache Cassandra database.
## Data modeling with NoSQL database
Their questions are three below:
1. Give me the artist, song title and song's length in the music app history that was heard during sessionId = 338, and itemInSession = 4
2. Give me only the following: name of artist, song (sorted by itemInSession) and user (first and last name) for userid = 10, sessionid = 182
3. Give me every user name (first and last) in my music app history who listened to the song 'All Hands Against His Own'
In order to answer these questions, the each queries should be like below:
1. Getting the artist and song title and song's length in the music app history that was heard during sessionId = 338, and itemInSession = 4
SELECT sessionId, iteminsession, artist, song, length
FROM song_per_session
WHERE sessionId = 338 AND iteminsession = 4
2. Getting the name of artist, song (sorted by itemInSession) and user (first and last name)
SELECT artist, song, firstname, lastname
FROM user_listened WHERE userId = 10 AND sessionId = 182
3. Getting every user name (first and last) in my music app history who listened to the song 'All Hands Against His Own'
SELECT firstname , lastname
FROM wholistened_theSong WHERE song = 'All Hands Against His Own' and userId = 10
Therefore, the schema of the tables to be created are below with some description of table schema:
1. For this query iteminsession and sessionid are considered as the composite key. Because these keys make the row unique and be able to know the specific information.'
CREATE TABLE IF NOT EXISTS song_per_session(
sessionId int,
iteminsession int,
artist text,
song text,
length float,
PRIMARY KEY((sessionId, iteminsession))
2. For this query userid and sessionid are considered as the composite key to know who listened the song and what song the user listned during the session. Iteminsessionid is considered as clustering key in order to sort the song's order in ascending.
CREATE TABLE IF NOT EXISTS user_listened(
userId int,
sessionId int,
iteminsession int,
artist text,
song text,
firstName text,
lastName text,
PRIMARY KEY((userId, sessionId), iteminsession)
3. For this query song and userid are considered as the composite key in order to know who listened to the specific song.
CREATE TABLE IF NOT EXISTS wholistened_theSong(
firstName text,
lastName text,
PRIMARY KEY((song, userId))
## Files included in the REPO:
1. event_data consists of files in CSV formats generated from the music app and the files are partitioned by data.
2. event_datafile_new.csv which is denormalized dataset will be created from the CSV files in even_data by running etl.py.
* create_tables.py that automatically drops the tables if they already exists and creates the tables as defined in the sql_queries module.
* etl.py that contains the main program and manages the file processing needed for reading the files in CSV formats and inserting the data to the Apache Cassandra DB tables that was defined by the create_tables.py.
* sql_queries.py that includes the NoSQL DB create & insert statements separeted in their own file for modularity.
* test.ipynb that includes the SELECT statements to verify the data inserted in the each table created.
## Steps to run the projects:
1. Execute the "python create_tables.py" file in the Terminal to create all the DB tables.
2. Execute the "python etl.py" file in the Terminal to extract from all csv files to create eventdatafilenew.csv and insert all records into the tables.
3. Verify the data in the each table by each the SELECT statement written in the cell in the test.ipynb.
|
Python | UTF-8 | 5,110 | 3.078125 | 3 | [] | no_license | __author__ = 'harrigan'
import argparse
import inspect
# Maximum length of the short names (one-dash arguments)
MAXSHORT = 3
class Parsable(object):
"""Mixin to make as parsable."""
_is_parsable = True
class Attrib(object):
"""Container object for command line attributes."""
def __init__(self):
self.varname = None
self.long_name = None
self.short_name = None
self.metavar = None
self.dtype = None
self.defval = None
self.helptxt = None
self.required = False
def get_attribute_help(docstring):
"""From a docstring, get help strings
We expect lines of the form
:param [atrribute_name]: help text
:param docstring: The docstring to parse
:returns: A dictionary of (attribute, help_text)
"""
docdict = dict()
linesplits = docstring.splitlines()
for line in linesplits:
line = line.strip()
if line.startswith(':param'):
colon_split = line.split(':')[1:]
name_split = colon_split[0].split()
if len(name_split) != 2:
continue
docdict[name_split[1]] = colon_split[1]
return docdict
def generate_atributes(c_obj):
"""Yield attributes by iterating over a dictionary of class attributes.
:param c_obj: Class to parse
"""
initargs = inspect.getargspec(c_obj.__init__)
n_defaults = len(initargs.defaults)
n_attr = len(initargs.args)
attr_short_names = set()
for i, attr in enumerate(initargs.args):
if attr == 'self':
continue
ao = Attrib()
# Figure out short name
underscores = attr.split('_')
maxl = max(len(us) for us in underscores)
for short_i in range(1, min(maxl, MAXSHORT)):
attr_short_name = ''.join([us[:short_i] for us in underscores])
if attr_short_name not in attr_short_names:
attr_short_names.add(attr_short_name)
break
else:
attr_short_name = None
# Add it if possible
if attr_short_name is not None:
ao.short_name = '-{}'.format(attr_short_name)
# Long name is just variable name
ao.varname = attr
ao.long_name = '--{}'.format(attr)
ao.metavar = underscores[-1]
# Figure out datatype and default value
if (n_attr - i) <= n_defaults:
defval = initargs.defaults[i - (n_attr - n_defaults)]
ao.dtype = defval.__class__
ao.defval = defval
else:
# TODO: How to specify datatype?
ao.defval = None
ao.dtype = str
ao.required = True
yield ao
def add_subparsers(c_obj, ap_parser):
"""Recurse down subparsers.
:param c_obj: Find subparsers for this class
:param ap_parser: Add subparsers to this argparse.ArgumentParser
:returns: True if we added subparsers
"""
subclasses = c_obj.__subclasses__()
if len(subclasses) > 0:
ap_subparsers = ap_parser.add_subparsers()
for sub_cobj in subclasses:
ap_sp = ap_subparsers.add_parser(sub_cobj._subcommand_shortname,
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
add_to_parser(sub_cobj, ap_sp)
return True
else:
return False
def add_to_parser(c_obj, parser):
"""Add all attributes from an object to a given argparse.ArgumentParser.
:param c_obj: Add attributes from this class
:param parser: Add attributes to this argparse.ArgumentParser
"""
if not add_subparsers(c_obj, parser):
# Only set_defaults for 'leaf' subparsers
parser.set_defaults(c_leaf=c_obj)
docdict = get_attribute_help(c_obj.__doc__)
for ao in generate_atributes(c_obj):
try:
ao.helptxt = docdict[ao.varname]
except KeyError:
ao.helptxt = "[help]"
# Condition on whether we could find a valid short name
if ao.short_name is not None:
parser.add_argument(ao.long_name, ao.short_name,
metavar=ao.metavar, default=ao.defval,
type=ao.dtype, help=ao.helptxt,
required=ao.required)
else:
parser.add_argument(ao.long_name, metavar=ao.metavar,
default=ao.defval, type=ao.dtype,
help=ao.helptxt, required=ao.required)
def parsify(c_obj):
"""Take an object and make all of its attributes command line options.
:param c_obj: A class to parse
"""
first_doc_line = c_obj.__doc__.splitlines()[0]
parser = argparse.ArgumentParser(description=first_doc_line,
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
add_to_parser(c_obj, parser)
args = parser.parse_args()
# Prepare arguments for init
init_dict = vars(args)
c_leaf = args.c_leaf
del init_dict['c_leaf']
c_inst = c_leaf(**init_dict)
return c_inst
|
Java | UTF-8 | 3,494 | 2.34375 | 2 | [] | no_license | package in.jogindersharma.jsframeworkdemo;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import in.jogindersharma.jsutilsframework.ui.activities.SelectSingleImageWithDefaultIntent;
import in.jogindersharma.jsutilsframework.utils.RunTimePermissionUtility;
public class SelectImageActivity extends AppCompatActivity implements View.OnClickListener {
Button bSelectImage;
ImageView ivSelectedImage;
private static final int WRITE_EXTERNAL_REQUEST_CODE = 101;
private static final int PICK_PHOTO_REQUEST_CODE = 102;
String TAG = "SelectImageActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_image);
initLayouts();
}
private void initLayouts() {
bSelectImage = (Button) findViewById(R.id.bSelectImage);
ivSelectedImage = (ImageView) findViewById(R.id.ivSelectedImage);
bSelectImage.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bSelectImage:
if(RunTimePermissionUtility.doWeHaveWriteExternalStoragePermission(SelectImageActivity.this)) {
Log.e(TAG, "Already have Storage Permission");
selectImageFromSdCard();
} else {
Log.e(TAG, "Going to have have Storage Permission");
RunTimePermissionUtility.requestWriteExternalStoragePermission(SelectImageActivity.this, WRITE_EXTERNAL_REQUEST_CODE);
}
break;
}
}
private void selectImageFromSdCard() {
Intent intent = new Intent(SelectImageActivity.this, SelectSingleImageWithDefaultIntent.class);
startActivityForResult(intent, PICK_PHOTO_REQUEST_CODE);
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
Log.e("--", "requestCode : " + requestCode + ", permissions :" + permissions + ",grantResults : " + grantResults);
switch (requestCode){
case WRITE_EXTERNAL_REQUEST_CODE:
if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.e("Permission", "WRITE_EXTERNAL permission has now been granted. Showing result.");
selectImageFromSdCard();
} else {
Log.e("Permission", "WRITE_EXTERNAL permission was NOT granted.");
RunTimePermissionUtility.showReasonBoxForWriteExternalStoragePermission(this, WRITE_EXTERNAL_REQUEST_CODE);
}
break;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case PICK_PHOTO_REQUEST_CODE:
if (resultCode == RESULT_OK) {
String selectedImage = data.getStringExtra("image_path");
ivSelectedImage.setImageBitmap(BitmapFactory.decodeFile(selectedImage));
}
}
}
}
|
JavaScript | UTF-8 | 1,844 | 3.640625 | 4 | [
"MIT"
] | permissive | var mySingleton = (function(){
var instance;
function init () {
// body...
//Singleton
function privateMethod () {
// body...
console.log("I am private");
}
var privateVariable = "I am also private";
var privateRandomNumber = Math.random();
return {
//Public methods and variables
publicMethod : function (argument) {
// body...
console.log("The public can see me!");
},
publicProperty : "I'm also public",
getRandomNumber : function (argument) {
// body...
return privateRandomNumber;
}
};
};
return {
getInstance : function () {
// body...
if(!instance){
instance = init();
}
return instance;
}
}
})();
var myBadSingleton = (function(){
var instance;
function init() {
// body...
var privateRandomNumber=Math.random();
return{
getRandomNumber:function () {
// body...
return privateRandomNumber;
}
};
};
return {
getInstance : function () {
// Always create a new Singleton instance
instance = init();
return instance;
}
};
})();
var singleA = mySingleton.getInstance();
var singleB = mySingleton.getInstance();
console.log(singleA.getRandomNumber() === singleB.getRandomNumber());
var badsingleA = myBadSingleton.getInstance();
var badsingleB = myBadSingleton.getInstance();
console.log(badsingleA.getRandomNumber() !== badsingleB.getRandomNumber()); |
Java | UTF-8 | 1,175 | 2.65625 | 3 | [] | no_license | /**
*
*/
package functions;
import java.rmi.RemoteException;
/**
* @author Pierre Marques
*
*/
public final class GameDescription implements IGameDescription {
private static final long serialVersionUID = 1L;
private final String bindName, name, theme;
public GameDescription(String bindName, String name, String theme) throws RemoteException {
super();
this.bindName = bindName;
this.name = name;
this.theme = theme;
}
public GameDescription(IGameDescription d) throws RemoteException {
this.bindName = d.getBindName();
this.name = d.getName();
this.theme = d.getTheme();
}
/* (non-Javadoc)
* @see functions.IGameDescription#getName()
*/
@Override
public String getName() {
return name;
}
/* (non-Javadoc)
* @see functions.IGameDescription#getBindName()
*/
@Override
public String getBindName() {
return bindName;
}
/* (non-Javadoc)
* @see functions.IGameDescription#getRootIdeaName()
*/
@Override
public String getTheme() {
return theme;
}
@Override
public String toString() {
return new StringBuilder(name)
.append(" about ")
.append(theme)
.append("\n\tat ")
.append(bindName)
.toString();
}
}
|
C++ | UTF-8 | 2,518 | 2.734375 | 3 | [] | no_license | // stringwriter.cpp
// The Windows Forms namespace lives in a different
// assembly, which is not referenced by default as is
// mscorlib.dll, so we must use #using here
#using "System.Windows.Forms.dll"
using namespace System;
using namespace System::IO;
using namespace System::Text;
using namespace System::Windows::Forms;
int main()
{
StringWriter^ sw = gcnew StringWriter();
sw->WriteLine("Pike Place");
sw->WriteLine("Street of Dreams");
sw->WriteLine("(C) 2006 Jeni Hogenson");
sw->WriteLine();
sw->Write("Walking with bare feet\n");
sw->Write("Seattle streets, gospel beat,\n");
sw->Write("She's got magic\n");
sw->WriteLine();
sw->WriteLine("Bag of black upon her back\n" +
"A sensual blend, soul food that is;\n" +
"Local color.");
sw->WriteLine();
String^ jambo = "jambo";
String^ s = String::Format("Open the bag, {0}, {1}.", jambo, jambo);
sw->WriteLine(s);
sw->Write("Make a wish, {0}, {0}.", jambo);
sw->WriteLine();
s = "Feel it, grab it, grope it.\n";
String::Concat(s, "Follow every curve.\n");
String::Concat(s, "Can you wait to find it?\n");
String::Concat(s, "Do you have the nerve?");
sw->WriteLine(s);
sw->WriteLine("A drop of oil, jambo, jambo.");
sw->WriteLine("Whisper in her ear,");
sw->WriteLine("Ask the question in your heart");
sw->WriteLine("that only you can hear");
sw->WriteLine();
StringBuilder^ sb = gcnew StringBuilder();
sb->Append("Fingers now upon your ears,\n");
sb->Append("Waiting for the space\n");
sb->Append("An answer if you're ready now\n");
sb->Append("From the marketplace\n");
sw->WriteLine(sb);
sw->WriteLine("The call of a bird, jambo, jambo.");
sw->WriteLine("The scent of a market flower,");
sw->WriteLine("Open wide to all of it and");
sw->WriteLine("Welcome back your power");
sw->WriteLine();
sw->WriteLine("Jambo this and jambo that,");
sw->WriteLine("Walking with bare feet.");
sw->WriteLine("No parking allowed when down under,");
sw->WriteLine("Keep it to the street.");
sw->WriteLine();
sw->WriteLine("Dead people rising,");
sw->WriteLine("Walking with bare feet,");
sw->WriteLine("No parking allowed when down under,");
sw->WriteLine("Keep it to the street.");
// The resulting string might be displayed to the user in a GUI
MessageBox::Show(sw->ToString(), "Poetry", MessageBoxButtons::OK);
}
|
Markdown | UTF-8 | 2,758 | 2.546875 | 3 | [
"MIT"
] | permissive | # oblivion
Shell alias manager
## Motivation
Shell commands are complex. Each executable has its own interface, and often multiple of these are used in one command. At some point you reach out to a notebook/notepad for writing down this perfectly crafted pipeline with tons of options for each program. Later you find yourself reaching out to that memo too often, and still struggle to memorize it, so you end up making a shell alias for it. As this situation goes on, your shell starts getting cluttered and the aliases start conflicting with one another; so you decide to group commands by theme, functionality or whatever, and come up with a pseudo-namespaces for each group (i.e. prefix each alias related to package management with "pm").
You can think of oblivion as something that helps you define proper alias interfaces.
## Installation
``` bash
curl https://nim-lang.org/choosenim/init.sh -sSf | sh # install Nim
nimble install oblivion
```
## Usage
All you need a file called `config.ini` in `$XDG_CONFIG_DIRS` (which by the way needs to be set) where you put your commands.
This file follows an extended ini format according to Nim's [parsecfg module](https://nim-lang.org/docs/parsecfg.html).
By default, when you install oblivion through nimble, the executable is named `o`.
You can run it with 0 or more arguments:
| # of args | functionality |
|-----------|-----------------------------------------------------|
| 0 | prints the defined interfaces |
| 1 | prints the commands in argument's interface |
| 2 | runs a command in an interface |
| 2+`x` | runs a command and supplies the `x` arguments to it |
If you need parameters for your command, you can specify them as `$1`, `$2`, etc.
Oblivion will verify that the # of arguments you provided matches the # of parameters in the command, and then perform substitution.
You don't have to type out the full name of the interface or command, as long as that's not ambiguous.
## Example
`/etc/xdg/oblivion/config.ini`
``` ini
[package]
list = "eix -c --world"
flags = "equery u $1"
conf = "sudo dispatch-conf"
emerge = "sudo emerge --ask $1"
sync = "sudo eix-sync"
update = "sudo emerge -uDU --ask --with-bdeps=y @world"
unmask = "sudo emerge --ask --autounmask=y --autounmask-write $1"
[configure]
alias = "nvim /usr/share/oh-my-zsh/custom/aliases.zsh"
i3 = "nvim /home/sealmove/.config/i3/config"
nvim = "nvim /etc/xdg/nvim/sysinit.vim"
zsh = "nvim /usr/share/oh-my-zsh/zshrc"
oblivion = "sudo nvim /etc/xdg/oblivion/config.ini"
[net]
myip = "dig +short myip.opendns.com @resolver1.opendns.com"
```
``` bash
$ o p l
= eix -c --world # the command is printed and run
```
|
JavaScript | UTF-8 | 409 | 2.8125 | 3 | [] | no_license | var addOption = document.querySelector('.addOpBtn');
addOption.addEventListener('click', function(e){
var options = e.target.parentNode.previousSibling;
var optionDiv = options.appendChild(document.createElement('div'))
optionDiv.class = 'option'
var input = document.createElement('input');
input.type = 'text';
input.name = 'option';
input.placeholder = 'Option';
optionDiv.appendChild(input);
});
|
Swift | UTF-8 | 2,036 | 2.546875 | 3 | [
"MIT"
] | permissive | //
// RemindPassViewController.swift
// iTraveler
//
// Created by Oleksandr Kurtsev on 15/06/2020.
// Copyright © 2020 Oleksandr Kurtsev. All rights reserved.
//
import UIKit
class RemindPassViewController: UIViewController {
@IBOutlet weak var emailTF: CustomTextField!
@IBOutlet weak var cancelButton: CustomButton!
@IBOutlet weak var sendEmailButton: CustomButton!
override func viewDidLoad() {
super.viewDidLoad()
setBackground()
prepareTextFields()
prepareButtons()
}
// MARK: - Private Method
private func prepareButtons() {
sendEmailButton.setTitle(kButtonSendEmailTitle, for: .normal)
cancelButton.setTitle(kButtonCancelTitle, for: .normal)
cancelButton.backgroundColor = Colors.tropicRed
}
private func prepareTextFields() {
emailTF.placeholder = kLoginTFPlaceholder
emailTF.returnKeyType = .done
emailTF.keyboardType = .emailAddress
emailTF.delegate = self
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
view.endEditing(true)
}
// MARK: - Actions
@IBAction func cancelAction(_ sender: CustomButton) {
sender.shake()
dismiss(animated: true)
}
@IBAction func sendEmailAction(_ sender: CustomButton) {
sender.shake()
AuthManager.shared.resetPassword(email: emailTF.text) { (result) in
switch result {
case .success(_):
self.showAlert(title: kAlertSuccess, message: kRecoveryPassword) {
self.dismiss(animated: true)
}
case .failure(let error):
self.showAlert(title: kAlertError, message: error.localizedDescription)
}
}
}
}
// MARK: - UITextFieldDelegate
extension RemindPassViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
|
Shell | UTF-8 | 1,773 | 4.125 | 4 | [] | no_license | #!/bin/sh
args=""
main() {
mkdir -p output/beanstalk
beanstalkd -b output/beanstalk &
processargs "$@"
defaults
# keep in foreground
while true; do sleep 10000; done
}
processargs() {
while [ "$#" -ge 1 ]; do
case "$1" in
--worker)
spawn "worker" "$2" "$3"
shift 3;;
--scraper)
spawn "scraper" "$2" 1
shift 2;;
*) shift ;;
esac
done
}
defaults() {
service=$(echo "$args" | grep "worker:deduplication")
if [ -z "$service" ]; then
spawn worker deduplication 1 >/dev/null
fi
service=$(echo "$args" | grep "worker:opengit")
if [ -z "$service" ]; then
# spawn a few git workers
spawn worker opengit 2
fi
service=$(echo "$args" | grep "scraper")
if [ -z "$service" ]; then
spawn scraper ssllabs 1
spawn scraper immuniweb 1
fi
}
spawn() {
type="$1"
source="$2"
count="$3"
source=$(echo "$source" | tr "," " ")
i=0
while [ $i -lt "$count" ]; do
bugspider "$type" "$source" &
i=$((i+1))
done
# append argument to args list for default checking
for s in $source; do
args="$args $type:$s"
done
}
usage() {
cat << EOF
Usage: entrypoint [OPTIONS]
Options:
--worker <tube>[,<tube>,...] <count>
Spawn <count> Workers with the defined tube(s)
A defined worker disables only the default worker for the defined tube(s).
--scraper <source>
Spawn a Scraper with the defined Source.
If one scraper is defined, all default scrapers will be deactivated.
Defaults:
worker deduplication 1
worker opengit 2
scraper ssllabs
scraper immuniweb
EOF
}
main "$@"
|
Java | UTF-8 | 877 | 3.34375 | 3 | [] | no_license | package Encapsulation;
/**
* @author Simon
* @version 1.0
* @ID 1930026144
* @date 2020/7/9 10:37
* Knowledge:
* - 无需初始化实例变量
* - Number Primitive (including char): 0 ps: floating points: 0.0
* - Boolean Primitive: false
* - Object Reference: Null
*/
public class PoorDog {
// 声明实例变量但是不初始化
private int size;
private String name;
public int getSize() {
// return 0
return size;
}
public String getName() {
// return null
return name;
}
}
class PoorDogTestDrive {
public static void main(String[] args) {
// 创建 PoorDog 对象
PoorDog one = new PoorDog();
System.out.println("Dog size is " + one.getSize());
System.out.println("Dog name is " + one.getName());
}
}
|
Python | UTF-8 | 2,294 | 2.75 | 3 | [] | no_license | import numpy as np
import torch
import torch.nn as nn
from torch.autograd import Variable
import pyro
from pyro.distributions import Normal
from pyro.infer import SVI
from pyro.optim import Adam
N = 100 # size of toy data
p = 1 # number of features
def build_linear_dataset(N, noise_std=0.1):
X = np.linspace(-6, 6, num=N)
y = 3 * X + 1 + np.random.normal(0, noise_std, size=N)
X, y = X.reshape((N, 1)), y.reshape((N, 1))
X, y = Variable(torch.Tensor(X)), Variable(torch.Tensor(y))
return torch.cat((X, y), 1)
loss_fn = torch.nn.MSELoss(size_average=False)
optim = torch.optim.Adam(regression_model.parameters(), lr=0.01)
num_iterations = 500
def main():
data = build_linear_dataset(N, p)
x_data = data[:, :-1]
y_data = data[:, -1]
for j in range(num_iterations):
# run the model forward on the data
y_pred = regression_model(x_data)
# calculate the mse loss
loss = loss_fn(y_pred, y_data)
# initialize gradients to zero
optim.zero_grad()
# backpropagate
loss.backward()
# take a gradient step
optim.step()
if (j + 1) % 50 == 0:
print("[iteration %04d] loss: %.4f" % (j + 1, loss.data[0]))
# Inspect learned parameters
print("Learned parameters:")
for name, param in regression_model.named_parameters():
print("%s: %.3f" % (name, param.data.numpy()))
def model(data):
# Create unit normal priors over the parameters
x_data = data[:, :-1]
y_data = data[:, -1]
mu, sigma = Variable(torch.zeros(p, 1)), Variable(10 * torch.ones(p, 1))
bias_mu, bias_sigma = Variable(torch.zeros(1)), Variable(10 * torch.ones(1))
w_prior, b_prior = Normal(mu, sigma), Normal(bias_mu, bias_sigma)
priors = {'linear.weight': w_prior, 'linear.bias': b_prior}
# lift module parameters to random variables
lifted_module = pyro.random_module("module", regression_model, priors)
# sample a nn (which also samples w and b)
lifted_nn = lifted_module()
# run the nn forward
latent = lifted_nn(x_data).squeeze()
# condition on the observed data
pyro.observe("obs", Normal(latent, Variable(0.1 * torch.ones(data.size(0)))),
y_data.squeeze())
if __name__ == '__main__':
main()
|
C# | UTF-8 | 1,803 | 2.96875 | 3 | [] | no_license | using CsvHelper;
using DataGenerator.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataGenerator.Services
{
public class CSVTableGenerator
{
public byte[] CreateCSVFileContentFrom(FakeDataTable fakeDataTable)
{
var config = new CsvHelper.Configuration.Configuration();
config.Delimiter = ",";
config.Encoding = Encoding.UTF8;
config.InjectionEscapeCharacter = '\n';
using (MemoryStream table = new MemoryStream())
using (StreamWriter writer = new StreamWriter(table))
using (CsvWriter csvWriter = new CsvWriter(writer, config))
{
AddColumnNamesToContent(csvWriter, fakeDataTable.FakeDataColumns);
AddDataRowsToContent(csvWriter, fakeDataTable.FakeDataColumns, fakeDataTable.RowCount);
writer.Flush();
table.Position = 0;
return table.ToArray();
}
}
private void AddColumnNamesToContent(CsvWriter csvWriter, List<FakeDataColumn> fakeDataColumns)
{
foreach (var column in fakeDataColumns)
{
csvWriter.WriteField(column.Name);
}
csvWriter.NextRecord();
}
private void AddDataRowsToContent(CsvWriter csvWriter, List<FakeDataColumn> dataColumns, long rowCount)
{
for (int i = 0; i < rowCount; i++)
{
for (int j = 0; j < dataColumns.Count; j++)
{
csvWriter.WriteField(dataColumns[j].Data[i]);
}
csvWriter.NextRecord();
}
}
}
}
|
C++ | UTF-8 | 1,156 | 3.296875 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> v;
int n;
long long max_res, min_res;
int seq[12];
// + : 0
// - : 1
// * : 2
// / : 3
// 각 번호별로 맞는 연산자 수만큼 vector에 넣은 후 next_permutation을 이용하여
// 경우의 수를 모두 찾으면서 우선순위 없이 앞에서부터 연산하고
// 최대, 최소값 비교하여 저장
int main(void) {
cin >> n;
for (int i = 0; i < n; i++)
cin >> seq[i];
for (int i = 0; i < 4; i++) {
int temp;
cin >> temp;
for (int j = 0; j < temp; j++) {
v.push_back(i);
}
}
sort(v.begin(), v.end());
min_res = 1000000001;
max_res = -1000000001;
do {
long long result = seq[0];
for (int i = 0; i < v.size(); i++) {
switch (v[i]) {
case 0:
result += seq[i + 1];
break;
case 1:
result -= seq[i + 1];
break;
case 2:
result *= seq[i + 1];
break;
case 3:
result /= seq[i + 1];
break;
}
}
min_res = min(result, min_res);
max_res = max(result, max_res);
} while (next_permutation(v.begin(), v.end()));
cout << max_res << "\n" << min_res << "\n";
return 0;
}
|
Ruby | UTF-8 | 311 | 3.296875 | 3 | [] | no_license | def is_factorion(fact, num)
sum = 0
i = num
while i > 0
i, d = i.divmod(10)
sum += fact[d]
end
return num == sum
end
fact = [1]
for n in 1..10
fact.push(n * fact[n - 1])
end
for j in 1..50000
if is_factorion(fact, j)
printf "%d ", j
end
end
printf("\n")
|
C++ | UTF-8 | 897 | 3.078125 | 3 | [] | no_license | // 1683.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <vector>
#include <iostream>
#include <algorithm>
#include <functional>
using namespace std;
void mPrint(vector<int>tmpVec)
{
for (int i = 0; i < tmpVec.size() - 1;i++)
{
cout << tmpVec[i] << " ";
}
cout << *(tmpVec.end() - 1) << endl;
}
int main()
{
int times;
cin >> times;
if (times<1||times>20)
{
exit(0);
}
vector<int>VecNum;
vector<int>VecBuff;
while (times--)
{
int countScore;
cin >> countScore;
if (countScore<1||countScore>1000)
{
exit(0);
}
while (countScore--)
{
int tmp;
cin >> tmp;
VecNum.push_back(tmp);
}
VecBuff = VecNum;
sort(VecNum.begin(), VecNum.end(), std::less<int>());
if (VecBuff==VecNum)
{
cout << "N/A" << endl;
}
else
{
mPrint(VecNum);
}
VecNum.clear();
VecBuff.clear();
}
return 0;
}
|
Shell | UTF-8 | 1,852 | 2.875 | 3 | [
"Apache-2.0"
] | permissive | #!/bin/bash -xe
# Copyright 2018 Pax Automa Systems, Inc.
#
# 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.
echo \> Setting up Kubernetes >&3
install_manifests() {
local src_path=$1
local tgt_path=$2
mkdir -p $src_path
for manifest in $src_path/*; do
envsubst < $manifest > $tgt_path/$(basename $manifest)
done
}
mkdir -p /mnt/etc/kubernetes/{manifests,addons}
install_manifests /root/manifests/kubelet /mnt/etc/kubernetes/manifests
install_manifests /root/manifests/addons /mnt/etc/kubernetes/addons
cat > /mnt/etc/kubernetes/config <<EOF
KUBE_ALLOW_PRIV="--allow-privileged=true"
KUBE_MASTER="--master=http://127.0.0.1:8080"
EOF
cat > /mnt/etc/kubernetes/kubelet <<EOF
KUBELET_ARGS="--container-runtime=docker \\
--kubeconfig=/etc/kubernetes/kubeconfig.yml \\
--cluster-dns=${OPEROS_DNS_SERVICE_IP} \\
--cluster-domain=${OPEROS_DNS_DOMAIN} \\
--pod-manifest-path=/etc/kubernetes/manifests \\
--node-labels=node-role.kubernetes.io/master=true \\
--register-with-taints=node-role.kubernetes.io/master=true:NoSchedule \\
--network-plugin=cni"
EOF
cat > /mnt/etc/kubernetes/kubeconfig.yml <<EOF
apiVersion: v1
kind: Config
clusters:
- name: local
cluster:
server: http://127.0.0.1:8080
contexts:
- context:
cluster: local
name: kubelet-context
current-context: kubelet-context
EOF
|
C# | UTF-8 | 6,675 | 2.65625 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
using OLC1_PY1_201700988.Estructuras.Conjunto;
namespace OLC1_PY1_201700988.Estructuras.AFD
{
class nodoCabecera
{
private string idEstado;
private ArrayList transiciones;
private string conjuntoContenido;
private string conjuntoGuia;
private bool aceptacion;
public nodoCabecera(string id, string conjuntoGuia, bool aceptar)
{
this.idEstado = id;
this.conjuntoGuia = conjuntoGuia;
this.aceptacion = aceptar;
this.conjuntoContenido = "";
this.transiciones = new ArrayList();
}
public void setIdEstado(string id)
{
this.idEstado = id;
}
public void setTransiciones(ArrayList transiciones)
{
this.transiciones = transiciones;
}
public void setConjunto(string conjunto)
{
this.conjuntoContenido = conjunto;
}
public void setAceptacion(bool aceptar)
{
this.aceptacion = aceptar;
}
public void setConjuntoGuia(string conjunto)
{
this.conjuntoGuia = conjunto;
}
public string getIdEstado()
{
return this.idEstado;
}
public ArrayList getTransiciones()
{
return transiciones;
}
public string getConjunto()
{
return conjuntoContenido;
}
public bool getAceptacion()
{
return aceptacion;
}
public string getConjuntoGuia()
{
return conjuntoGuia;
}
public void addTransicion(string estado, string valor, int esConj)
{
this.transiciones.Add(new nodoTransicion(estado,valor, esConj));
}
public string permitirPaso(string caracter, string estadoActual, string cadena, ArrayList reporte)
{
int movs = 1;
foreach(nodoTransicion next in transiciones)
{
Console.WriteLine("Cadena: " + cadena + " valor: " + next.getValor());
bool esConjunto = false;
//Reconocer si es conjunto
switch (next.getEsConj())
{
case 0:
break;
case 1:
esConjunto = true;
break;
}
//Console.WriteLine("valor: \"" + next.getValor() + "\" char: \"" + caracter+ "\"");
//Si es conjunto
if (esConjunto)
{
if (getConjEvaluar(next.getValor()) != null)
{
if (getConjEvaluar(next.getValor()).existeChar(caracter))
{
reporte.Add(new nodoReporte(caracter, next.getValor(), estadoActual + "->" + next.getEstadoSiguientes()));
return next.getEstadoSiguientes();
}
}
}
//Si no es un conjunto y si el caracter es igual al que se encuentra en la expresion
else if (next.getValor().Equals(caracter))
{
reporte.Add(new nodoReporte(caracter, next.getValor(), estadoActual + "->" + next.getEstadoSiguientes()));
return next.getEstadoSiguientes();
}
//Evaluar los caracteres \t \n [:asfgasfasf:]
else if (next.getValor().Equals(("\\t").ToString()))
{
if (Convert.ToInt32(caracter[0]) == 9)
{
reporte.Add(new nodoReporte(caracter, next.getValor(), estadoActual + "->" + next.getEstadoSiguientes()));
return next.getEstadoSiguientes();
}
}
else if (next.getValor().Equals(("\\n").ToString()))
{
if (Convert.ToInt32(caracter[0]) == 10)
{
reporte.Add(new nodoReporte(caracter, next.getValor(), estadoActual + "->" + next.getEstadoSiguientes()));
return next.getEstadoSiguientes();
}
}
else if (next.getValor().Equals("[:todo:]"))
{
reporte.Add(new nodoReporte(caracter, next.getValor(), estadoActual + "->" + next.getEstadoSiguientes()));
return next.getEstadoSiguientes();
}
//Evaluar si la cadena es de mas caracteres
else if(next.getValor().Length >= 1 && cadena.Length <= next.getValor().Length)
{
//Console.WriteLine("Cadena: " + cadena + " valor: " + next.getValor());
if (cadena.Equals(next.getValor()))
{
reporte.Add(new nodoReporte(cadena, next.getValor(), estadoActual + "->" + next.getEstadoSiguientes()));
return next.getEstadoSiguientes();
}
else
{
//Console.WriteLine(movs + " " + transiciones.Count);
//Saber si estamos en la ultima transicion a evaluar
if (movs == transiciones.Count)
{
//Console.WriteLine("Retornando desde aca movs");
return estadoActual;
}
}
}
movs++;
}
//Insertar error
reporte.Add(new nodoReporte(cadena,"Error Lexico con el caracter "+caracter, "Se vuelve el estado actual ("+estadoActual+") por el error"));
return "Error";
}
private nodoConj getConjEvaluar(string id)
{
foreach (nodoConj conjunto in Program.listConj)
{
if (conjunto.getId().Equals(id))
{
return conjunto;
}
}
return null;
}
}
}
|
Java | UTF-8 | 474 | 3.359375 | 3 | [] | no_license |
package atividade;
import java.util.Scanner;
public class Atividadess {
public static void main(String[] args) {
Scanner teclado = new Scanner (System.in);
String sexo;
System.out.print("Digite seu sexo (M - para masculino / F - para feminino):");
sexo = teclado.next();
if (sexo.equals("M")){
System.out.print("Seja bem-vindo, Senhor!");
}else{
System.out.print("Seja bem-vinda, Senhora!");
}
}
}
|
Java | UTF-8 | 3,905 | 2.203125 | 2 | [] | no_license | package com.mx.intellego.zurich.emc.bussiness.impl;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import com.box.sdk.BoxAPIConnection;
import com.box.sdk.BoxFile;
import com.box.sdk.BoxFileVersion;
import com.box.sdk.BoxFolder;
import com.box.sdk.BoxSharedLink;
import com.box.sdk.Metadata;
import com.mx.intellego.zurich.emc.bussiness.ArhivoBS;
public class Archivo implements ArhivoBS{
private static final String CLIENT_ID = "crfuha6k7q67lcp2n5yoz0xowdz61rb5";
private static final String CLIENT_SECRET = "imvqqYStB4qS2X3ZLHgWt0XoW528zbEc";
private static final String ENTERPRISE_ID = "";
private static final String PUBLIC_KEY_ID = "";
private static final String PRIVATE_KEY_FILE = "";
private static final String PRIVATE_KEY_PASSWORD = "";
private static final String APP_USER_NAME = "";
public boolean subirArhivoBox(File archivo,String nombreArchivo,String token) throws IOException{
//Subir un archivo
boolean resultado = false;
try {
BoxAPIConnection api = new BoxAPIConnection(token);
//Ruta del archivo
BoxFolder rootFolder = BoxFolder.getRootFolder(api);
FileInputStream stream = new FileInputStream(archivo);
rootFolder.uploadFile(stream,nombreArchivo );
stream.close();
resultado =true;
} catch (Exception e) {
e.printStackTrace();
}
return resultado;
}
public boolean crearMetadatoBox(String idArchivo, String map, String valor, String token) {
// TODO M�todo para crear un metadato a un archivo en box.
boolean resultado = false;
try {
BoxAPIConnection api = new BoxAPIConnection(CLIENT_ID,CLIENT_SECRET);
//Ruta del archivo
BoxFolder rootFolder = BoxFolder.getRootFolder(api);
BoxFile file = new BoxFile(api, idArchivo);
file.createMetadata(new Metadata().add(map, valor));
resultado = true;
} catch (Exception e) {
e.printStackTrace();
}
return resultado;
}
public boolean versionarBox(File archivo,String idArchivo, String token) throws FileNotFoundException {
// Metodo para versionar un documento dado su id.
boolean resultado = false;
try {
BoxAPIConnection api = new BoxAPIConnection(token);
//Ruta del archivo
BoxFolder rootFolder = BoxFolder.getRootFolder(api);
BoxFile file = new BoxFile(api,idArchivo);
FileInputStream stream = new FileInputStream(archivo);
file.uploadVersion(stream);
resultado = true;
} catch (Exception e) {
e.printStackTrace();
}
return resultado;
}
public String linkVisualizarArchivoBox(String idArchivo, String token){
//Metodo para publicar un link para un archivo
String resultado = "";
try {
BoxAPIConnection api = new BoxAPIConnection(token);
//Ruta del archivo
BoxFolder rootFolder = BoxFolder.getRootFolder(api);
BoxFile file = new BoxFile(api, idArchivo);
BoxSharedLink.Permissions permissions = new BoxSharedLink.Permissions();
permissions.setCanDownload(true);
permissions.setCanPreview(true);
Date unshareDate = new Date();
BoxSharedLink sharedLink = file.createSharedLink(BoxSharedLink.Access.OPEN, null, permissions);
resultado = sharedLink.getURL();
} catch (Exception e) {
e.printStackTrace();
}
return resultado;
}
public String linkDescargarArchivoBox(String idArchivo,String token){
String link = "";
//TODO: Método para descargar un archivo
try {
BoxAPIConnection api = new BoxAPIConnection(token);
//Ruta del archivo
BoxFolder rootFolder = BoxFolder.getRootFolder(api);
BoxFile file = new BoxFile(api, idArchivo);
BoxFile.Info info = file.getInfo();
FileOutputStream stream = new FileOutputStream(info.getName());
file.download(stream);
link = file.getDownloadURL().toString();
stream.close();
} catch (Exception e) {
e.printStackTrace();
}
return link;
}
}
|
Ruby | UTF-8 | 3,799 | 2.640625 | 3 | [
"MIT"
] | permissive | require 'spec_helper'
describe Decanter::Parser do
before(:all) do
Object.const_set('FooParser',
Class.new(Decanter::Parser::ValueParser) do
def self.name
'FooParser'
end
end
)
Object.const_set('BarParser',
Class.new(Decanter::Parser::ValueParser) do
def self.name
'BarParser'
end
end.tap do |parser|
parser.pre :date, :float
end
)
Object.const_set('CheckInFieldDataParser',
Class.new(Decanter::Parser::ValueParser) do
def self.name
'BarParser'
end
end.tap do |parser|
parser.pre :date, :float
end
)
end
describe '#klass_or_sym_to_str' do
subject { Decanter::Parser.klass_or_sym_to_str(klass_or_sym) }
context 'for a string' do
let(:klass_or_sym) { 'Foo' }
it 'raises an argument error' do
expect { subject }
.to raise_error(ArgumentError, "cannot lookup parser for #{klass_or_sym} with class #{klass_or_sym.class}")
end
end
context 'for a class' do
let(:klass_or_sym) do
Class.new do
def self.name
'Foobar'
end
end
end
it 'returns the name of the class + Parser' do
expect(subject).to eq 'FoobarParser'
end
end
context 'for a symbol' do
let(:klass_or_sym) { :hot_dog }
it 'returns the camelized string + Parser' do
expect(subject).to eq 'HotDogParser'
end
# it 'returns the singularized, camelized string + Parser' do
# expect(subject).to eq 'HotDogParser'
# end
end
context 'for a symbol with _data' do
let(:klass_or_sym) { :check_in_field_data }
it 'does not change _data to _datum' do
expect(subject).to eq 'CheckInFieldDataParser'
# expect { subject }
# .to raise_error(NameError, "cannot find parser
# #{klass_or_sym.to_s.singularize.camelize.concat('Parser')}")
end
end
end
describe '#parser_constantize' do
subject { Decanter::Parser.parser_constantize(parser_str) }
context 'when a corresponding parser does not exist' do
let(:parser_str) { 'FoobarParser' }
it 'raises a name error' do
expect { subject }
.to raise_error(NameError, "cannot find parser #{parser_str.concat('Parser')}")
end
end
context 'when a corresponding parser exists' do
let(:parser_str) { 'FooParser' }
it 'returns the parser' do
expect(subject).to eq FooParser
end
end
end
describe '#expand' do
subject { Decanter::Parser.expand(parser) }
context 'when there are no preparsers' do
let(:parser) { Class.new(Decanter::Parser::Base) }
it 'returns an array only containing the original parser' do
expect(subject).to eq [parser]
end
end
context 'when there are preparsers' do
let(:parser) {
Class.new(Decanter::Parser::Base).tap do |parser|
parser.pre :date
end
}
it 'returns an array with the preparsers prepended to the original parser' do
expect(subject).to eq [Decanter::Parser::DateParser, parser]
end
end
end
describe '#parsers_for' do
subject { Decanter::Parser.parsers_for(:bar) }
let(:_data) { Decanter::Parser.parsers_for(:check_in_field_data) }
it 'returns a flattened array of parsers' do
expect(subject).to eq [
Decanter::Parser::DateParser,
Decanter::Parser::FloatParser,
BarParser
]
end
it 'returns Data instead of Datum' do
expect(_data).to eq [
Decanter::Parser::DateParser,
Decanter::Parser::FloatParser,
CheckInFieldDataParser
]
end
end
end
|
Python | UTF-8 | 321 | 3.03125 | 3 | [] | no_license | import json
from typing import BinaryIO, Any
def read_from_exchange(exchange: BinaryIO):
line = exchange.readline()
try:
return json.loads(line)
except:
return {'type':'pass'}
def write_to_exchange(exchange: BinaryIO, obj: Any) -> None:
json.dump(obj, exchange)
exchange.write("\n") |
Markdown | UTF-8 | 21,834 | 2.625 | 3 | [] | permissive | ## Commands
A list of the available commands
#### `sfdx force:apex:class:create`
create an Apex class
```
USAGE
$ sfdx force:apex:class:create -n <string> [-d <string>] [-t <string>] [--apiversion <string>] [--json] [--loglevel
trace|debug|info|warn|error|fatal|TRACE|DEBUG|INFO|WARN|ERROR|FATAL]
OPTIONS
-d, --outputdir=outputdir folder for saving the created files
-n, --classname=classname(required) name of the generated Apex class
-t, --template=ApexException|ApexUnitTest|DefaultApexClass|InboundEmailService [default: DefaultApexClass] template
to use for file creation
--apiversion=apiversion override the api version used for
api requests made by this command
--json format output as json
--loglevel=(trace|debug|info|warn|error|fatal|TRACE|DEBUG|INFO|WARN|ERROR|FATAL) [default: warn] logging level for
this command invocation
DESCRIPTION
If not supplied, the apiversion, template, and outputdir use default values.
The outputdir can be an absolute path or relative to the current working directory.
EXAMPLES
$ sfdx force:apex:class:create -n MyClass
$ sfdx force:apex:class:create -n MyClass -d classes
```
_See code: [src/commands/force/apex/class/create.ts](https://github.com/forcedotcom/salesforcedx-templates/blob/master/src/commands/force/apex/class/create.ts)_
#### `sfdx force:apex:trigger:create`
create an Apex trigger
```
USAGE
$ sfdx force:apex:trigger:create -n <string> [-d <string>] [-e <string>] [-s <string>] [-t <string>] [--apiversion
<string>] [--json] [--loglevel trace|debug|info|warn|error|fatal|TRACE|DEBUG|INFO|WARN|ERROR|FATAL]
OPTIONS
-d, --outputdir=outputdir folder for saving the created files
-e, --triggerevents=before insert|before update|before delete|after insert|after update|after delete|after undelete
[default: before insert] events that fire the trigger
-n, --triggername=triggername (required) name of the generated Apex trigger
-s, --sobject=sobject [default: SOBJECT] sObject to create a trigger on
-t, --template=ApexTrigger [default: ApexTrigger] template to use for file creation
--apiversion=apiversion override the api version used for api requests made by this command
--json format output as json
--loglevel=(trace|debug|info|warn|error|fatal|TRACE|DEBUG|INFO|WARN|ERROR|FATAL) [default: warn] logging level for this command invocation
DESCRIPTION
If not supplied, the apiversion, template, and outputdir use default values.
The outputdir can be an absolute path or relative to the current working directory.
EXAMPLES
$ sfdx force:apex:trigger:create -n MyTrigger
$ sfdx force:apex:trigger:create -n MyTrigger -s Account -e 'before insert, after upsert'
$ sfdx force:apex:trigger:create -n MyTrigger -d triggers
```
_See code: [src/commands/force/apex/trigger/create.ts](https://github.com/forcedotcom/salesforcedx-templates/blob/master/src/commands/force/apex/trigger/create.ts)_
#### `sfdx force:lightning:app:create`
create a Lightning app
```
USAGE
$ sfdx force:lightning:app:create -n <string> [-d <string>] [-t <string>] [--apiversion <string>] [--json] [--loglevel
trace|debug|info|warn|error|fatal|TRACE|DEBUG|INFO|WARN|ERROR|FATAL]
OPTIONS
-d, --outputdir=outputdir folder for saving the created files
-n, --appname=appname (required) name of the generated
Lightning app
-t, --template=DefaultLightningApp [default: DefaultLightningApp]
template to use for file creation
--apiversion=apiversion override the api version used for
api requests made by this command
--json format output as json
--loglevel=(trace|debug|info|warn|error|fatal|TRACE|DEBUG|INFO|WARN|ERROR|FATAL) [default: warn] logging level for
this command invocation
DESCRIPTION
If not supplied, the apiversion, template, and outputdir use default values.
The outputdir can be an absolute path or relative to the current working directory.
If you don’t specify an outputdir, we create a subfolder in your current working directory with the name of your
bundle. For example, if the current working directory is force-app and your Lightning bundle is called myBundle, we
create force-app/myBundle/ to store the files in the bundle.
EXAMPLES
$ sfdx force:lightning:app:create -n myapp
$ sfdx force:lightning:app:create -n myapp -d aura
```
_See code: [src/commands/force/lightning/app/create.ts](https://github.com/forcedotcom/salesforcedx-templates/blob/master/src/commands/force/lightning/app/create.ts)_
#### `sfdx force:lightning:component:create`
create a bundle for an Aura component or a Lightning web component
```
USAGE
$ sfdx force:lightning:component:create -n <string> [-d <string>] [-t <string>] [--type <string>] [--apiversion
<string>] [--json] [--loglevel trace|debug|info|warn|error|fatal|TRACE|DEBUG|INFO|WARN|ERROR|FATAL]
OPTIONS
-d, --outputdir=outputdir folder for saving the created files
-n, --componentname=componentname (required) name of the generated
Lightning component
-t, --template= [default: DefaultLightningCmp]
template to use for file creation
--apiversion=apiversion override the api version used for
api requests made by this command
--json format output as json
--loglevel=(trace|debug|info|warn|error|fatal|TRACE|DEBUG|INFO|WARN|ERROR|FATAL) [default: warn] logging level for
this command invocation
--type=aura|lwc [default: aura] type of the
Lightning component
DESCRIPTION
If not supplied, the apiversion, template, and outputdir use default values.
The outputdir can be an absolute path or relative to the current working directory.
If you don’t specify an outputdir, we create a subfolder in your current working directory with the name of your
bundle. For example, if the current working directory is force-app and your Lightning bundle is called myBundle, we
create force-app/myBundle/ to store the files in the bundle.
To create a Lightning web component, pass --type lwc to the command. If you don’t include a --type value, Salesforce
CLI creates an Aura component by default.
EXAMPLES
$ sfdx force:lightning:component:create -n mycomponent
$ sfdx force:lightning:component:create -n mycomponent --type lwc
$ sfdx force:lightning:component:create -n mycomponent -d aura
$ sfdx force:lightning:component:create -n mycomponent --type lwc -d lwc
```
_See code: [src/commands/force/lightning/component/create.ts](https://github.com/forcedotcom/salesforcedx-templates/blob/master/src/commands/force/lightning/component/create.ts)_
#### `sfdx force:lightning:event:create`
create a Lightning event
```
USAGE
$ sfdx force:lightning:event:create -n <string> [-d <string>] [-t <string>] [--apiversion <string>] [--json]
[--loglevel trace|debug|info|warn|error|fatal|TRACE|DEBUG|INFO|WARN|ERROR|FATAL]
OPTIONS
-d, --outputdir=outputdir folder for saving the created files
-n, --eventname=eventname (required) name of the generated
Lightning event
-t, --template=DefaultLightningEvt [default: DefaultLightningEvt]
template to use for file creation
--apiversion=apiversion override the api version used for
api requests made by this command
--json format output as json
--loglevel=(trace|debug|info|warn|error|fatal|TRACE|DEBUG|INFO|WARN|ERROR|FATAL) [default: warn] logging level for
this command invocation
DESCRIPTION
If not supplied, the apiversion, template, and outputdir use default values.
The outputdir can be an absolute path or relative to the current working directory.
If you don’t specify an outputdir, we create a subfolder in your current working directory with the name of your
bundle. For example, if the current working directory is force-app and your Lightning bundle is called myBundle, we
create force-app/myBundle/ to store the files in the bundle.
EXAMPLES
$ sfdx force:lightning:app:create -n myevent
$ sfdx force:lightning:event:create -n myevent -d aura
```
_See code: [src/commands/force/lightning/event/create.ts](https://github.com/forcedotcom/salesforcedx-templates/blob/master/src/commands/force/lightning/event/create.ts)_
#### `sfdx force:lightning:interface:create`
create a Lightning interface
```
USAGE
$ sfdx force:lightning:interface:create -n <string> [-d <string>] [-t <string>] [--apiversion <string>] [--json]
[--loglevel trace|debug|info|warn|error|fatal|TRACE|DEBUG|INFO|WARN|ERROR|FATAL]
OPTIONS
-d, --outputdir=outputdir folder for saving the created files
-n, --interfacename=interfacename (required) name of the generated
Lightning interface
-t, --template=DefaultLightningIntf [default: DefaultLightningIntf]
template to use for file creation
--apiversion=apiversion override the api version used for
api requests made by this command
--json format output as json
--loglevel=(trace|debug|info|warn|error|fatal|TRACE|DEBUG|INFO|WARN|ERROR|FATAL) [default: warn] logging level for
this command invocation
DESCRIPTION
If not supplied, the apiversion, template, and outputdir use default values.
The outputdir can be an absolute path or relative to the current working directory.
If you don’t specify an outputdir, we create a subfolder in your current working directory with the name of your
bundle. For example, if the current working directory is force-app and your Lightning bundle is called myBundle, we
create force-app/myBundle/ to store the files in the bundle.
EXAMPLES
$ sfdx force:lightning:interface:create -n myinterface
$ sfdx force:lightning:interface:create -n myinterface -d aura
```
_See code: [src/commands/force/lightning/interface/create.ts](https://github.com/forcedotcom/salesforcedx-templates/blob/master/src/commands/force/lightning/interface/create.ts)_
#### `sfdx force:lightning:test:create`
create a Lightning test
```
USAGE
$ sfdx force:lightning:test:create -n <string> [-d <string>] [-t <string>] [--json] [--loglevel trace|debug|info|warn|error|fatal|TRACE|DEBUG|INFO|WARN|ERROR|FATAL]
OPTIONS
-d, --outputdir=outputdir folder for saving the created files
-n, --testname=testname (required) name of the generated Lightning test
-t, --template=DefaultLightningTest [default: DefaultLightningTest] template to use for file creation
--json format output as json
--loglevel=(trace|debug|info|warn|error|fatal|TRACE|DEBUG|INFO|WARN|ERROR|FATAL) [default: warn] logging level for this command invocation
DESCRIPTION
The outputdir can be an absolute path or relative to the current working directory.
EXAMPLES
$ sfdx force:lightning:test:create -n MyLightningTest
$ sfdx force:lightning:test:create -n MyLightningTest -d lightningTests
```
_See code: [src/commands/force/lightning/test/create.ts](https://github.com/forcedotcom/salesforcedx-templates/blob/master/src/commands/force/lightning/test/create.ts)_
#### `sfdx force:project:create`
create a Salesforce DX project
```
USAGE
$ sfdx force:project:create -n <string> [-d <string>] [-p <string>] [-s <string>] [-t <string>] [-x] [--json]
[--loglevel trace|debug|info|warn|error|fatal|TRACE|DEBUG|INFO|WARN|ERROR|FATAL]
OPTIONS
-d, --outputdir=outputdir folder for saving the created files
-n, --projectname=projectname (required) name of the generated
project
-p, --defaultpackagedir=defaultpackagedir [default: force-app] default package
directory name
-s, --namespace=namespace project associated namespace
-t, --template=standard|empty|analytics [default: standard] template to use
for file creation
-x, --manifest generate a manifest (package.xml)
for change-set based development
--json format output as json
--loglevel=(trace|debug|info|warn|error|fatal|TRACE|DEBUG|INFO|WARN|ERROR|FATAL) [default: warn] logging level for
this command invocation
DESCRIPTION
Default values are used if the template, namespace, defaultpackagedir, and outputdir aren’t supplied.
The outputdir can be an absolute path or relative to the current working directory.
EXAMPLES
$ sfdx force:project:create --projectname mywork
$ sfdx force:project:create --projectname mywork --defaultpackagedir myapp
$ sfdx force:project:create --projectname mywork --defaultpackagedir myapp --manifest
$ sfdx force:project:create --projectname mywork --template empty
```
_See code: [src/commands/force/project/create.ts](https://github.com/forcedotcom/salesforcedx-templates/blob/master/src/commands/force/project/create.ts)_
#### `sfdx force:visualforce:component:create`
create a Visualforce component
```
USAGE
$ sfdx force:visualforce:component:create -n <string> -l <string> [-d <string>] [-t <string>] [--apiversion <string>]
[--json] [--loglevel trace|debug|info|warn|error|fatal|TRACE|DEBUG|INFO|WARN|ERROR|FATAL]
OPTIONS
-d, --outputdir=outputdir folder for saving the created files
-l, --label=label (required) Visualforce component
label
-n, --componentname=componentname (required) name of the generated
Visualforce component
-t, --template=DefaultVFComponent [default: DefaultVFComponent]
template to use for file creation
--apiversion=apiversion override the api version used for
api requests made by this command
--json format output as json
--loglevel=(trace|debug|info|warn|error|fatal|TRACE|DEBUG|INFO|WARN|ERROR|FATAL) [default: warn] logging level for
this command invocation
DESCRIPTION
If not supplied, the apiversion, template, and outputdir use default values.
The outputdir can be an absolute path or relative to the current working directory.
Name and label are required.
EXAMPLES
$ sfdx force:visualforce:component:create -n mycomponent -l mylabel
$ sfdx force:visualforce:component:create -n mycomponent -l mylabel -d components
```
_See code: [src/commands/force/visualforce/component/create.ts](https://github.com/forcedotcom/salesforcedx-templates/blob/master/src/commands/force/visualforce/component/create.ts)_
#### `sfdx force:visualforce:page:create`
create a Visualforce page
```
USAGE
$ sfdx force:visualforce:page:create -n <string> -l <string> [-d <string>] [-t <string>] [--apiversion <string>]
[--json] [--loglevel trace|debug|info|warn|error|fatal|TRACE|DEBUG|INFO|WARN|ERROR|FATAL]
OPTIONS
-d, --outputdir=outputdir folder for saving the created files
-l, --label=label (required) Visualforce page label
-n, --pagename=pagename (required) name of the generated
Visualforce page
-t, --template=DefaultVFPage [default: DefaultVFPage] template to
use for file creation
--apiversion=apiversion override the api version used for
api requests made by this command
--json format output as json
--loglevel=(trace|debug|info|warn|error|fatal|TRACE|DEBUG|INFO|WARN|ERROR|FATAL) [default: warn] logging level for
this command invocation
DESCRIPTION
If not supplied, the apiversion, template, and outputdir use default values.
If not supplied, the apiversion, template, and outputdir use default values.
Name and label are required.
EXAMPLES
$ sfdx force:visualforce:page:create -n mypage -l mylabel
$ sfdx force:visualforce:page:create -n mypage -l mylabel -d pages
```
_See code: [src/commands/force/visualforce/page/create.ts](https://github.com/forcedotcom/salesforcedx-templates/blob/master/src/commands/force/visualforce/page/create.ts)_
|
Java | UTF-8 | 528 | 2.875 | 3 | [] | no_license | package cell.facility.restaurant;
import cell.facility.Facility;
import point.Point;
/** Kelas Restaurant bertanggung jawab mengelola Restaurant.
* @author AZIS ADI KUNCORO (13515120)
* @version 3.0
*/
public class Restaurant extends Facility {
/** Konstruktor Restaurant dengan parameter .
* @param p Merupakan posisi Restaurant.
*/
public Restaurant(Point p) {
super(p);
}
/** Metode render untuk kelas Restaurant yang di override dari Kelas Render. */
@Override
public char render() {
return 'R';
}
}
|
PHP | UTF-8 | 2,949 | 2.609375 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Controllers;
use App\Product;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class ProductController extends Controller
{
public function getProducts()
{
// Get products
$products = Product::orderBy('created_at', 'desc')->paginate(10);
// Return collection of products as a resource
return response()->json(['products' => $products]);;
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function postProduct(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required',
'desc' => 'required',
'price' => 'required',
'user_id' => 'required',
'status' => 'required',
]);
if ($validator->fails()) {
return response()->json(['message' => $validator->errors(), 'status' => false], 404);
}
if ($request->hasFile('file')) {
$this->path = $request->file('file')->store('products');
} else {
return response()->json(['message' => 'Please add an Image', 'status' => false], 404);
}
$product = new Product;
$product->name = $request->input('name');
$product->desc = $request->input('desc');
$product->price = $request->input('price');
$product->user_id = $request->input('user_id');
$product->status = $request->input('status');
$product->image = $this->path;
$product->save();
return response()->json(['product' => $product]);
}
public function putProduct(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required',
'desc' => 'required',
'price' => 'required',
'user_id' => 'required',
'status' => 'required',
]);
if ($validator->fails()) {
return response()->json(['message' => $validator->errors(), 'status' => false], 404);
}
$product = Product::findOrFail($request->project_id);
$product->update([
'name' => $request->input('name'),
'desc' => $request->input('desc'),
'price' => $request->input('price'),
'user_id' => $request->input('user_id'),
'status' => $request->input('status'),
]);
return response()->json(['product' => $product]);
}
public function deleteProduct($id)
{
// Get product
$product = Product::findOrFail($id);
if (!$product) {
return response()->json(['message' => 'product not found', 'status' => false], 404);
}
if ($product->delete()) {
return response()->json(['message' => 'Product deleted successfully']);
}
}
}
|
Markdown | UTF-8 | 13,618 | 2.9375 | 3 | [] | no_license | ---
layout: post
title: 【Redis】主从复制
tag: Redis
---
### 主从复制
互联网“三高”架构
●高并发
●高性能
**●高可用**

**你的“Redis”是否高可用**
单机redis的风险与问题
●问题1.机器故障
●现象:硬盘故障、系统崩溃
●本质:数据丢失,很可能对业务造成灾难性打击
●结论:基本上会放弃使用redis.
●问题2.容量瓶颈
●现象:内存不足,从16G升级到64G,从64G升级到128G ,无限升级内存
●本质:穷,硬件条件跟不上
●结论:放弃使用redis
●结论:
为了避免单点Redis服务器故障,准备多台服务器,互相连通。将数据复制多个副本保存在不同的服务器上,<font color="red">连接在一起</font>,并保证数据是<font color="red">同步</font>的。即使有其中一台服务器宕机,其他服务器依然可以继续提供服务,实现Redis的高可用,同时实现数据<font color="red">冗余备份</font>。
**多台服务器连接方案**

主从复制即将master中的数据即时、有效的复制到slave中
特征:一个master可以拥有多个slave ,一个slave只对应一个master
职责:
●master:
●写数据
●执行写操作时,将出现变化的数据自动同步到slave
●读数据(可忽略)
●slave:
●读数据
●写数据(禁止)
高可用集群

#### 主从复制的作用
●读写分离: master写、slave读 ,提高服务器的读写负载能力
●负载均衡:基于主从结构,配合读写分离,由slave分担master负载,并根据需求的变化,改变slave的数量,通过多个从节点分担数据读取负载,大大提高Redis服务器并发量与数据吞吐量
●故障恢复:当master出现问题时,由slave提供服务,实现快速的故障恢复
●数据冗余:实现数据**热备份**,是持久化之外的一种数据冗余方式
●高可用基石:基于主从复制,构建哨兵模式与集群,实现Redis的高可用方案
#### 主从复制工作流程
主从复制过程大体可以分为3个阶段
建立连接阶段(即准备阶段)
数据同步阶段
命令传播阶段

##### 阶段一:建立连接阶段
> 建立slave到master的连接,使master能够识别slave,并保存slave端口号

**主从连接( slave连接master )**
●方式一:客户端发送命令
> slaveof <masterip> <masterport>
●方式二:启动服务器参数
> redis-server -slaveof <masterip> <masterport>
●方式三: 服务器配置
> slaveof <masterip> <masterport>
●slave系统信息
●master_ link_ down_ since_ seconds
●masterhost
●masterport
●master系统信息
●slave_ listening_ _port(多个)



主从断开连接
●客户端发送命令
> slaveof no one
●说明:
slave断开连接后,不会删除已有数据,只是不再接受master发送的数据


##### 阶段二:数据同步阶段工作流程
●在slave初次连接master后 ,复制master中的所有数据到slave
●将slave的数据库状态更新成master当前的数据库状态
RDB快照
部分同步数据是AOF

部分同步数据(部分复制)是指RDB过程种缓存区的数据
上图9,10不是同步阶段的过程
##### 数据同步阶段master说明

1. 如果master数据量巨大,数据同步阶段应避开流量高峰期,避免造成master阻塞,影响业务正常执行
2. 复制缓冲区大小设定不合理,会导致数据溢出。如进行全量复制周期太长,进行部分复制时发现数据已经存在丢失的情况,必须进行第二次全量复制,致使slave陷入死循环状态。
> repl-backlog-size 1mb
3. master单机内存占用主机内存的比例不应过大,建议使用50%-70%的内存,留下30%-50%的内存用于执行bgsave命令和创建复制缓冲区

##### 数据同步阶段slave说明
1.为避免slave进行全量复制、部分复制时服务器响应阻塞或数据不同步,建议关闭此期间的对外服务
> `slave -serve-stale-data yes|no`
2.数据同步阶段, master发送给slave信息可以理解master是slave的一个客户端,主动向slave发送命令
3.多个slave同时对master请求数据同步, master发送的RDB文件增多,会对带宽造成巨大冲击,如果master带宽不足,因此数据同步需要根据业务需求,适量错峰
4.slave过多时,建议调整拓扑结构,由一主多从结构变为树状结构,中间的节点既是master ,也是slave。注意使用树状结构时,由于层级深度,导致深度越高的slave与最顶层master间数据同步延迟较大,数据一致性变差,应谨慎选择
##### 阶段三:命令传播阶段
●当master数据库状态被修改后,导致主从服务器数据库状态不一致,此时需要让主从数据同步到一致的状态,同步的动作称为**命令传播**
●master将接收到的数据变更命令发送给slave , slave接收命令后执行命令
**命令传播阶段的部分复制**
●命令传播阶段出现了断网现象
●网络闪断闪连 忽略
●短时间网络中断 部分复制
●长时间网络中断 全量复制
●**部分复制**的三个核心要素
●服务器的运行id ( run id )
●主服务器的复制积压缓冲区
●主从服务器的复制偏移量
##### 服务器的运行id ( run id )
●概念:服务器运行ID是每一台服务器每次运行的身份识别码,一台服务器多次运行可以生成多个运行id
●组成:运行id由40位字符组成,是一个随机的十六进制字符
> 例如: fdc9ff13b9bbaab28db42b3d50f852bb5e3fcdce
●作用:运行id被用于在服务器间进行传输,识别身份
如果想两次操作均对同一台服务器进行,必须每次操作携带对应的运行id ,用于对方识别
●实现方式:运行id在每台服务器启动时自动生成的, master在首次连接slave时,会将自己的运行ID发送给slave , slave保存此ID ,通过info Server命令,可以查看节点的runid .

##### 复制缓冲区
●概念:复制缓冲区,又名复制积压缓冲区,是一个**先进先出( FIFO )的队列**,用于存储服务器执行过的命令,每次传播命令, master都会将传播的命令记录下来,并存储在复制缓冲区
●复制缓冲区默认数据存储空间大小是1M ,由于存储空间大小是固定的,当入队元素的数量大于队列长度时,最先入队的元素会被弹出,而新元素会被放入队列
●由来:每台服务器启动时,如果开启有AOF或被连接成为master节点,即创建复制缓冲区
●作用:用于保存master收到的所有指令(仅影响数据变更的指令, 例如set , select )
●数据来源:当master接收到主客户端的指令时,除了将指令执行,会将该指令存储到缓冲区中


##### 主从服务器复制偏移量(offset)
●概念:一个数字,描述复制缓冲区中的**指令字节位置**
●分类:
●master复制偏移量:记录发送给所有slave的指令字节对应的位置(**多个**)
●slave复制偏移量:记录slave接收master发送过来的指令字节对应的位置( **一个)**
●数据来源:
master端:发送一次记录一次
slave端:接收一次记录一次
●作用:同步信息,比对master与slave的差异,当slave断线后,恢复数据使用
##### 数据同步+命令传播阶段工作流程

##### 心跳机制
●进入命令传播阶段候, master与slave间需要进行信息交换,使用心跳机制进行维护,实现双方连接保持在线
●master心跳:
●指令:PING
●周期:由repl-ping-slave-period决定,默认10秒
●作用:判断slave是否在线
●查询: INFO replication 获取slave最后一次连接时间间隔, lag项维持在0或1视为正常
●slave心跳任务
●指令: REPLCONF ACK {offset}
●周期:1秒
●作用1 :汇报slave自己的复制偏移量,获取最新的数据变更指令
●作用2 :判断master是否在线
**心跳阶段注意事项**
●当slave多数掉线 ,或延迟过高时, master为保障数据稳定性,将拒绝所有信息同步操作
> min-slaves-to-write 2
> min-slaves-max-lag 8
slave数量少于2个,或者所有slave的延迟都大于等于10秒时,强制关闭master写功能,停止数据同步
●slave数量由slave发送REPLCONF ACK命令做确认
●slave延迟由slave发送REPLCONF ACK命令做确认

#### 主从复制常见问题
**频繁的全量复制( 1 )**
伴随着系统的运行, master的数据量会越来越大, 一旦master重启 , runid将发生变化,会导致全部slave的全量复制操作
**内部优化调整方案:**(自带的)
1. master内部创建master_ repl id变量,使用runid相同的策略生成,长度41位,并发送给所有slave
2. 在master关闭时执行命令shutdown save ,进行RDB持久化,将runid与offset保存到RDB文件中
●repl-id repl-offset
●通过redis-check-rdb命令可以查看该信息

3. master重启后加载RDB文件,恢复数据
重启后,将RDB文件中保存的repl-id与repl-offset加载到内存中
●master_ repl_ id = repl master_repl_offset = repl-offset
●通过info命令可以查看该信息
作用:
本机保存上次runid ,重启后恢复该值,使所有slave认为还是之前的master
**频繁的全量复制( 2 )**
●问题现象
●网络环境不佳,出现网络中断, slave不提供服务
●问题原因
●复制缓冲区过小,断网后slave的offset越界,触发全量复制
●最终结果
●slave反复进行全量复制
●解决方案
●修改复制缓冲区大小
> rep1- -backlog-size
●建议设置如下:
1.测算从master到slave的重连平均时长second
2.获取master平均每秒产生写命令数据总量write_ size_ per_ second
3.最优复制缓冲区空间= 2 * second * write_ size_ per_ second
**频繁的网络中断( 1 )**
●问题现象
master的CPU占用过高或slave频繁断开连接
●问题原因
●slave每1秒发送REPLCONF ACK命令到master
●当slave接到了慢查询时( keys *, hgetall等) ,会大量占用CPU性能
master每1秒调用复制定时函数replicationCron() ,比对slave发现长时间没有进行响应
●最终结果
●master各种资源(输出缓冲区、带宽、连接等)被严重占用
●解决方案
●通过设置合理的超时时间,确认是否释放slave
> repl-timeout
该参数定义了超时时间的阈值(默认60秒) , 超过该值,释放slave
**频繁的网络中断( 2 )**
●问题现象
> slave与master连接断开
●问题原因
●master发送p ing指令频度较低
●master设定超时时间较短
●ping指令在网络中存在丢包
●解决方案
●提高ping指令发送的频度
> repl-ping- slave -period
超时时间repl-time的时间至少是ping指令频度的5到10倍,否则slave很容易判定超时
**数据不一致**
●问题现象
●多个slave获取相同数据不同步
●问题原因
●网络信息不同步,数据发送有延迟
●解决方案
●优化主从间的网络环境,通常放置在同-一个机房部署,如使用阿里云等云服务器时要注意此现象
●监控主从节点延迟(通过offset )判断,如果slave延迟过大,暂时屏蔽程序对该slave的数据访问
> `slave- serve- stale-data yes| no`
开启后仅响应info、slaveof等少数命令 (慎用,除非对数据一致性要求很高 ) |
C++ | UTF-8 | 840 | 2.6875 | 3 | [] | no_license | /*
* =====================================================================================
*
* Filename: source.cpp
*
* Description:
*
* Version: 1.0
* Created: 05/07/2013 12:10:28 AM
* Revision: none
* Compiler: gcc
*
* Author: Zhujin Liang (LZJ), alfredtofu@gmail.com
* Organization:
*
* =====================================================================================
*/
#include <iostream>
using namespace std;
class Dog
{
public:
virtual void bark() = 0;
};
class YellowDog: public Dog
{
public:
void bark()
{
cout << "YYYYellow" << endl;
}
};
class WhiteDog: public Dog
{
public:
void bark()
{
cout << "WWWWhite" << endl;
}
};
class BlackDog: public Dog
{
public:
void bark()
{
cout << "BBBBlack" << endl;
}
};
|
Markdown | UTF-8 | 1,512 | 2.625 | 3 | [
"MIT"
] | permissive | # Geezify-Lua
geezifylua is a luarock(i.e. package for the lua language) that converts geez-script numbers to arabic and viceversa.
## Installation
```lua
luarocks install geezifylua
```
## Usage
```lua
geezifylua = require "geezifylua""
geezifylua.geezify.geezify(12) #=> '፲፪'
geezifylua.geezify.geezify(3033) #=> '፴፻፴፫'
geezifylua.geezify.geezify(100200000) #=> '፼፳፼'
geezifylua.geezify.geezify(333333333) #=> '፫፼፴፫፻፴፫፼፴፫፻፴፫'
geezifylua.arabify.arabify('፲፪') #=> 12
geezifylua.arabify.arabify('፴፻፴፫') #=> 3033
geezifylua.arabify.arabify('፼፳፼') #=> 100200000
geezifylua.arabify.arabify('፫፼፴፫፻፴፫፼፴፫፻፴፫') #=> 333333333
```
## Contributing
Bug reports and pull requests are welcome on GitHub at https://github.com/yilkalargaw/geezify-lua. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.
## License
This lua-rock is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
## Code of Conduct
Everyone interacting in the geezify-lua project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/yilkalargaw/geezify-lua/blob/master/CODE_OF_CONDUCT.md).
|
Java | UTF-8 | 2,039 | 2.828125 | 3 | [] | no_license | package com.connectfour;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class DiagonalCheckerTest {
Boardable board;
Checker diagonalChecker;
@BeforeEach
void initBoardAndGameChecker(){
board = new TestClasses.TestBoard();
diagonalChecker = new DiagonalChecker(new MoveValidator());
}
@Test
void testIsGameOverReturnsTrueIf4InARowUpLeft(){
setLeftDiagonalWin(board);
assertTrue(diagonalChecker.isGameOver(board));
}
@Test
void testIsGameOverReturnsTrueIf4InARowUpRight(){
setRightDiagonalWin(board);
assertTrue(diagonalChecker.isGameOver(board));
}
@Test
void testIsGameOverReturnsFalseWhenEmpty(){
assertFalse(diagonalChecker.isGameOver(board));
}
@Test
void testIsGameOverReturnsFalseIfMixedDiscs(){
setUpMixedDiagonal(board);
assertFalse(diagonalChecker.isGameOver(board));
}
//helper methods
void setLeftDiagonalWin(Boardable board){
Discable testDisc = new TestClasses.TestDisc();
board.addDisc(testDisc, 0, 0);
board.addDisc(testDisc, 1, 1);
board.addDisc(testDisc, 2, 2);
board.addDisc(testDisc, 3, 3);
}
void setRightDiagonalWin(Boardable board){
Discable testDisc = new TestClasses.TestDisc();
board.addDisc(testDisc, 3, 0);
board.addDisc(testDisc, 2, 1);
board.addDisc(testDisc, 1, 2);
board.addDisc(testDisc, 0, 3);
}
void setUpMixedDiagonal(Boardable board){
Discable testDisc = new TestClasses.TestDisc();
Discable testDisc2 = new Disc("blue");
board.addDisc(testDisc, 0, 0);
board.addDisc(testDisc, 1, 1);
board.addDisc(testDisc2, 2, 2);
board.addDisc(testDisc, 3, 3);
board.addDisc(testDisc, 3, 0);
board.addDisc(testDisc, 1, 2);
board.addDisc(testDisc2, 2, 1);
board.addDisc(testDisc, 0, 3);
}
} |
Java | UTF-8 | 3,652 | 2.25 | 2 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | package org.cloudfoundry.multiapps.controller.core.cf.apps;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.stream.Stream;
import org.cloudfoundry.multiapps.common.test.TestUtil;
import org.cloudfoundry.multiapps.common.util.JsonUtil;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import com.sap.cloudfoundry.client.facade.domain.CloudApplication;
class ApplicationStartupStateCalculatorTest {
public static Stream<Arguments> testComputeCurrentState() {
return Stream.of(
// @formatter:off
// (0)
Arguments.of("started-app.json", ApplicationStartupState.STARTED),
// (1)
Arguments.of("stopped-app.json", ApplicationStartupState.STOPPED),
// (2) The number of running instances is different than the number of total instances:
Arguments.of("app-in-inconsistent-state-0.json", ApplicationStartupState.INCONSISTENT),
// (3) The number of running instances is not zero when the requested state is stopped:
Arguments.of("app-in-inconsistent-state-1.json", ApplicationStartupState.INCONSISTENT),
// (4) The number of running and the number of total instances is zero, but the requested state is started:
Arguments.of("app-in-inconsistent-state-2.json", ApplicationStartupState.INCONSISTENT),
// (5) The number of running instances is bigger than the number of total instances:
Arguments.of("app-in-inconsistent-state-3.json", ApplicationStartupState.INCONSISTENT)
// @formatter:on
);
}
@ParameterizedTest
@MethodSource
void testComputeCurrentState(String pathToFileContainingAppJson, ApplicationStartupState expectedState) {
String appJson = TestUtil.getResourceAsString(pathToFileContainingAppJson, getClass());
CloudApplication app = JsonUtil.fromJson(appJson, CloudApplication.class);
assertEquals(expectedState, new ApplicationStartupStateCalculator().computeCurrentState(app));
}
public static Stream<Arguments> testComputeDesiredState() {
return Stream.of(
// @formatter:off
// (0)
Arguments.of("app-with-no-start-attribute-true.json", true, ApplicationStartupState.STOPPED),
// (1)
Arguments.of("app-with-no-start-attribute-true.json", false, ApplicationStartupState.STOPPED),
// (2)
Arguments.of("app-with-no-start-attribute-false.json", true, ApplicationStartupState.STARTED),
// (3)
Arguments.of("app-with-no-start-attribute-false.json", false, ApplicationStartupState.STARTED),
// (4)
Arguments.of("app-without-no-start-attribute.json", true, ApplicationStartupState.STOPPED),
// (5)
Arguments.of("app-without-no-start-attribute.json", false, ApplicationStartupState.STARTED)
// @formatter:on
);
}
@ParameterizedTest
@MethodSource
void testComputeDesiredState(String pathToFileContainingAppJson, boolean shouldNotStartAnyApp, ApplicationStartupState expectedState) {
String appJson = TestUtil.getResourceAsString(pathToFileContainingAppJson, getClass());
CloudApplication app = JsonUtil.fromJson(appJson, CloudApplication.class);
assertEquals(expectedState, new ApplicationStartupStateCalculator().computeDesiredState(app, shouldNotStartAnyApp));
}
}
|
C++ | UTF-8 | 1,641 | 3.359375 | 3 | [] | no_license | #ifndef AVLTREE_H
#define AVLTREE_H
#include <vector>
#include <functional>
using namespace std;
/***
* An AVLTree implementation using Desmond's implementation
* @Typename KeyType the datatype for the Key object (must have implemented comparison operators)
* @Typename DataType the datatype for the data object (must have implemented assignment operator)
*/
template<typename KeyType, typename DataType>
class AVLTree{
private:
struct AVLNode{
AVLNode(const KeyType& key, const DataType& data): left(), right(), key(key), data(data), height(0){}
~AVLNode();
AVLTree left;
AVLTree right;
KeyType key;
DataType data;
int height;
bool operator<(const AVLNode& rhs);
};
AVLNode* root = nullptr;
unsigned int size = 0;
AVLTree& leftSubtree();
AVLTree& rightSubtree();
const AVLTree& leftSubtree() const;
const AVLTree& rightSubtree() const;
int height() const;
int bfactor() const;
// AVLTree operation
void rotateL();
void rotateR();
void balance();
void updateHeight();
public:
AVLTree() = default;
~AVLTree();
// element access
const DataType& find(const KeyType& key) const;
DataType& find(const KeyType& key);
const AVLNode& max() const;
const AVLNode& min() const;
// modifier
bool add(const KeyType& key, const DataType& data);
bool remove(const KeyType& key);
// capacity
bool contains(const KeyType& key) const;
unsigned int getSize();
bool empty() const;
void clear();
// descriptor
void toKeyVector(vector<KeyType>& vector) const;
void toVector(vector<DataType>& vector) const;
void print(int depth = 0) const;
};
#endif // AVLTREE_H
|
Markdown | UTF-8 | 5,791 | 2.921875 | 3 | [] | no_license | ## Code of Conduct
> All attendees of Codefreeze are required to agree with the following Code of Conduct.
Codefreeze isn't an officially organised event.
For enforcement of this Code of Conduct, we only have official authority of the private accommodation we are using for sessions and the activities we organise.
With everything else, we will try to work on enforcement with the Suomen Latu staff and local authorities.
This is still a public space used by non-participants as well, please don't assume that everyone has read or will follow this Code of Conduct.
This Code of Conduct applies to the event itself, and to all digital spaces that are related to the event, such as GitHub, Slack, Matrix and Trello.
### Inclusiveness
A goal of Codefreeze is to be inclusive and welcoming to attendees with the most varied and diverse backgrounds possible.
Please read our full Code of Conduct before booking, discussing online and before coming to Codefreeze. But please don’t feel intimidated by it—these are simple rules, and they will make life better for everyone at Codefreeze.
### Why we have a Code of Conduct
We are dedicated to create an event where everybody can learn, teach, share, network and have a good time. This can only work if we are inclusive to the largest number of contributors, and if we create an environment, where everybody feels safe and welcome.
Yes, we value discussion and disagreement. And discussion can become heated. But there have to be rules, and there has to be a red line.
In this Code of Conduct, we lay out those rules and red lines.
### Safe Environment
We are committed to providing a friendly, safe and welcoming environment for all, regardless of gender, sexual orientation, age, field of expertise, ability, ethnicity, socioeconomic status, and religion (or lack thereof).
And so we invite all those who participate in Codefreeze, and the community surrounding the event, to help us create safe and positive experiences for everyone. With your help, this event can be a great experience for everyone!
Treat everyone professionally. Everybody at the conference is a professional in their field. Treat all attendees as equals. Ask before you teach. Do not explain things without being asked.
Be welcoming, friendly, and patient. Give people the benefit of the doubt. Ask questions before jumping to conclusions.
Be respectful. Not all of us will agree with each other all the time, but disagreement is no excuse for poor behaviour and poor manners. We might all experience some frustration now and then, but we cannot allow that frustration to turn into a personal attack.
Be aware of the effect your words may have on others. We are a community of professionals, and we conduct ourselves professionally. Be kind to others. Do not insult or put down other participants. Harassment and other exclusionary behavior aren't acceptable.
Be careful with jokes. We do not tolerate any Code of Conduct violations, even if “it was just a joke”.
Admit when you do not know something. Encourage others to admit when they do not know something—and never joke about it. We are all here to learn.
There might be people taking photographs. If you don't want to be photographed let them know. If you want to publish a photo, ask the people in the photograph first.
If you're involved in outdoor activities, look after each other and be mindful that not everyone has the same ability. Please respect nature and the instructions from the official guides.
### Code of Conduct Violations
If you think someone has violated our Code of Conduct—even if you were not directly involved, like you just overheard a conversation—please:
- Let the person know that what they did is not appropriate and ask them to stop if you feel able to do so
- Contact the volunteers of Codefreeze (See contact details below). We will discuss any possible action with you first.
But please give people the benefit of doubt. If there is even a slight chance that this was a misunderstanding (e.g. the person did not speak in their native language, and did not find the right words), try to sort it out in a friendly, constructive way.
When we learn about a Code of Conduct violations, volunteers will hear both sides, and then take action we deem appropriate, such as:
- Give a warning
- Have a longer talk about our values
- Ask the staff to expel the person, though we don't have the authority to do so ourselves (see above)
- Exclude the person from our privately used accommodation & activities we organise
- Call the authorities
- Inform organisers of other events
### Unacceptable Behaviour
Unacceptable behaviour includes, but is not limited to:
- Harassment, and other exclusionary behaviour. Deliberate intimidation and threats.
- Aggressive or sexualized language and content. Unwanted sexual advances.
- Insulting or putting down other participants.
- Publishing or telling others, that a participant belongs to a particular identity group without asking their consent first, e.g outing someone.
- “Well-actuallies”: Telling people what they “actually meant to say”.
- Other conduct which could reasonably be considered inappropriate in a professional setting.
To clarify, although this doesn't take away from the other rules, it is ok to be naked in private saunas and changing rooms, but not mandatory. If you are unsure about what is appropriate or if you're uncomfortable about this, please talk to a volunteer listed below.
### Need Help?
If you need help, have any further questions or have any other concerns, please contact a volunteer immediately.
- Find and talk to the volunteers at the conference
- Ask in the [`#info`](https://matrix.to/#/#info:matrix.codefreeze.fi) channel on [Matrix](/chat)
- Contact a volunteer on Matrix
|
C++ | UTF-8 | 545 | 2.578125 | 3 | [] | no_license | #pragma once
#include "Background.h"
class BackgroundManager
{
public:
BackgroundManager();
~BackgroundManager();
void setUp(sf::RenderWindow* window); // Sets up background objects
void moveWithView(char direction, float dt); // Moves background objects
void render(sf::RenderWindow* window); // Renders background objects
private:
// Background Textures
sf::Texture skylineTexture;
sf::Texture buildingsTexture;
sf::Texture nearBuildingsTexture;
std::vector<Background> backgrounds; // Vector holding background objects
}; |
Java | UTF-8 | 3,861 | 1.875 | 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 rest.modelo.entidad;
/**
*
* @author USUARIO
*/
public class Usuario {
private String usuarioid;
private String personaid;
private String nombres;
private String nombre;
private String apellidos;
private String tipopersonaid;
private String nombretipoper;
private String areaid;
private String nombrearea;
private String perfilid;
private String nombreperfil;
private String usuario;
private String contrasena;
private String codigo;
private String habitacion;
private String culto;
private String estado;
private String userIdReg;
public Usuario() {
}
public String getUsuarioid() {
return usuarioid;
}
public void setUsuarioid(String usuarioid) {
this.usuarioid = usuarioid;
}
public String getPersonaid() {
return personaid;
}
public void setPersonaid(String personaid) {
this.personaid = personaid;
}
public String getNombres() {
return nombres;
}
public void setNombres(String nombres) {
this.nombres = nombres;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getApellidos() {
return apellidos;
}
public void setApellidos(String apellidos) {
this.apellidos = apellidos;
}
public String getTipopersonaid() {
return tipopersonaid;
}
public void setTipopersonaid(String tipopersonaid) {
this.tipopersonaid = tipopersonaid;
}
public String getNombretipoper() {
return nombretipoper;
}
public void setNombretipoper(String nombretipoper) {
this.nombretipoper = nombretipoper;
}
public String getAreaid() {
return areaid;
}
public void setAreaid(String areaid) {
this.areaid = areaid;
}
public String getNombrearea() {
return nombrearea;
}
public void setNombrearea(String nombrearea) {
this.nombrearea = nombrearea;
}
public String getPerfilid() {
return perfilid;
}
public void setPerfilid(String perfilid) {
this.perfilid = perfilid;
}
public String getNombreperfil() {
return nombreperfil;
}
public void setNombreperfil(String nombreperfil) {
this.nombreperfil = nombreperfil;
}
public String getUsuario() {
return usuario;
}
public void setUsuario(String usuario) {
this.usuario = usuario;
}
public String getContrasena() {
return contrasena;
}
public void setContrasena(String contrasena) {
this.contrasena = contrasena;
}
public String getCodigo() {
return codigo;
}
public void setCodigo(String codigo) {
this.codigo = codigo;
}
public String getHabitacion() {
return habitacion;
}
public void setHabitacion(String habitacion) {
this.habitacion = habitacion;
}
public String getCulto() {
return culto;
}
public void setCulto(String culto) {
this.culto = culto;
}
public String getEstado() {
return estado;
}
public void setEstado(String estado) {
this.estado = estado;
}
public String getUserIdReg() {
return userIdReg;
}
public void setUserIdReg(String userIdReg) {
this.userIdReg = userIdReg;
}
}
|
Python | UTF-8 | 9,698 | 2.890625 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
第18章:模型融合stacking
数据获取
"""
import os
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
import variable_encode as var_encode
from sklearn.metrics import confusion_matrix,recall_score, auc, roc_curve,precision_score,accuracy_score
from sklearn.model_selection import GridSearchCV
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from xgboost import XGBClassifier
from sklearn.model_selection import KFold
import matplotlib.pyplot as plt
import matplotlib
matplotlib.rcParams['font.sans-serif']=['SimHei'] # 用黑体显示中文
matplotlib.rcParams['axes.unicode_minus']=False # 正常显示负号
import warnings
warnings.filterwarnings("ignore") ##忽略警告
##数据读取
def data_read(data_path,file_name):
df = pd.read_csv( os.path.join(data_path, file_name), delim_whitespace = True, header = None )
##变量重命名
columns = ['status_account','duration','credit_history','purpose', 'amount',
'svaing_account', 'present_emp', 'income_rate', 'personal_status',
'other_debtors', 'residence_info', 'property', 'age',
'inst_plans', 'housing', 'num_credits',
'job', 'dependents', 'telephone', 'foreign_worker', 'target']
df.columns = columns
##将标签变量由状态1,2转为0,1;0表示好用户,1表示坏用户
df.target = df.target - 1
##数据分为data_train和 data_test两部分,训练集用于得到编码函数,验证集用已知的编码规则对验证集编码
data_train, data_test = train_test_split(df, test_size=0.2, random_state=100,stratify=df.target)
return data_train, data_test
##离散变量与连续变量区分
def category_continue_separation(df,feature_names):
categorical_var = []
numerical_var = []
if 'target' in feature_names:
feature_names.remove('target')
##先判断类型,如果是int或float就直接作为连续变量
numerical_var = list(df[feature_names].select_dtypes(include=['int','float','int32','float32','int64','float64']).columns.values)
categorical_var = [x for x in feature_names if x not in numerical_var]
return categorical_var,numerical_var
if __name__ == '__main__':
path = 'D:\\code\\chapter18'
data_path = os.path.join(path ,'data')
file_name = 'german.csv'
##读取数据
data_train, data_test = data_read(data_path,file_name)
sum(data_train.target ==0)
data_train.target.sum()
##区分离散变量与连续变量
feature_names = list(data_train.columns)
feature_names.remove('target')
categorical_var,numerical_var = category_continue_separation(data_train,feature_names)
###离散变量直接WOE编码
var_all_bin = list(data_train.columns)
var_all_bin.remove('target')
##训练集WOE编码
df_train_woe, dict_woe_map, dict_iv_values ,var_woe_name = var_encode.woe_encode(data_train,data_path,categorical_var, data_train.target,'dict_woe_map', flag='train')
##测试集WOE编码
df_test_woe, var_woe_name = var_encode.woe_encode(data_test,data_path,categorical_var, data_test.target, 'dict_woe_map',flag='test')
#####连续变量缺失值做填补
for i in numerical_var:
if sum(data_train[i].isnull()) >0:
data_train[i].fillna(data_train[i].mean(),inplace=True)
if sum(data_test[i].isnull()) >0:
data_test[i].fillna(data_test[i].mean(),inplace=True)
###组成分箱后的训练集与测试集
data_train.reset_index(drop=True,inplace=True)
data_test.reset_index(drop=True,inplace=True)
var_1 = numerical_var
var_1.append('target')
data_train_1 = pd.concat([df_train_woe[var_woe_name],data_train[var_1]],axis=1)
data_test_1 = pd.concat([df_test_woe[var_woe_name],data_test[var_1]],axis=1)
####取出训练数据与测试数据
var_all = list(data_train_1.columns)
var_all.remove('target')
####变量归一化
scaler = StandardScaler().fit(data_train_1[var_all])
data_train_1[var_all] = scaler.transform(data_train_1[var_all])
data_test_1[var_all] = scaler.transform(data_test_1[var_all])
x_train = np.array(data_train_1[var_all])
y_train = np.array(data_train_1.target)
x_test = np.array(data_test_1[var_all])
y_test = np.array(data_test_1.target)
########stacking模型融合
kfold = KFold(n_splits=5)
##存放概率预测结果
y_pred_1 = np.zeros(x_train.shape[0])
y_pred_2 = np.zeros(x_train.shape[0])
y_pred_3 = np.zeros(x_train.shape[0])
for train_index, test_index in kfold.split(x_train):
##K折中的建模部分
x_train_temp = x_train[train_index,:]
y_train_temp = y_train[train_index]
##K折中的预测部分
x_pre_temp = x_train[test_index,:]
y_pre_temp = y_train[test_index]
##一级模型
##随机森林模型
RF_model_1 = RandomForestClassifier(random_state=0, n_jobs=-1, criterion='entropy',
n_estimators=100,
max_depth=3,
max_features=0.8,
min_samples_split=50,
class_weight={1: 2, 0: 1},
bootstrap=True)
RF_model_fit_1 = RF_model_1.fit(x_train_temp, y_train_temp)
##给出概率预测
y_pred_1[test_index] = RF_model_fit_1.predict_proba(x_pre_temp)[:, 1]
##xgboost模型
xgboost_model_1 = XGBClassifier(random_state=0, n_jobs=-1,
n_estimators=100,
max_depth=2,
min_child_weight=2,
subsample=0.8, colsample_bytree=0.8,
learning_rate=0.02,
scale_pos_weight=2)
xgboost_model_fit_1 = xgboost_model_1.fit(x_train_temp, y_train_temp)
##给出概率预测
y_pred_2[test_index] = xgboost_model_fit_1.predict_proba(x_pre_temp)[:, 1]
##svm模型
svm_model_1 = SVC(kernel='rbf',C =0.5,gamma=0.1,class_weight= {1: 2, 0: 1},probability=True)
svm_model_fit_1 = svm_model_1.fit(x_train_temp, y_train_temp)
##给出概率预测
y_pred_3[test_index] = svm_model_fit_1.predict_proba(x_pre_temp)[:, 1]
##将预测概率输出与原特征合并,构造新的训练集
y_pred_all = np.vstack([y_pred_1, y_pred_2,y_pred_3]).T
x_train_1 = np.hstack([x_train,y_pred_all])
##训练二级模型
##设置待优化的超参数
lr_param = {'C': [0.01, 0.1, 0.2, 0.5, 1, 1.5, 2],
'class_weight': [{1: 1, 0: 1}, {1: 2, 0: 1}, {1: 3, 0: 1}]}
##初始化网格搜索
lr_gsearch = GridSearchCV(
estimator=LogisticRegression(random_state=0, fit_intercept=True, penalty='l2', solver='saga'),
param_grid=lr_param, cv=3, scoring='f1', n_jobs=-1, verbose=2)
##执行超参数优化
lr_gsearch.fit(x_train_1, y_train)
print('logistic model best_score_ is {0},and best_params_ is {1}'.format(lr_gsearch.best_score_,
lr_gsearch.best_params_))
##最有参数训练模型
##用最优参数,初始化Logistic回归模型
LR_model_2 = LogisticRegression(C=lr_gsearch.best_params_['C'], penalty='l2', solver='saga',
class_weight=lr_gsearch.best_params_['class_weight'])
##训练Logistic回归模型
LR_model_fit = LR_model_2.fit(x_train_1, y_train)
##测试集预测结果
##先用一级模型进行概率预测
##给出概率预测
ytest_pred_1= RF_model_fit_1.predict_proba(x_test)[:, 1]
ytest_pred_2 = xgboost_model_fit_1.predict_proba(x_test)[:, 1]
ytest_pred_3 = svm_model_fit_1.predict_proba(x_test)[:, 1]
##构造新特征矩阵
ytest_pred_all = np.vstack([ytest_pred_1, ytest_pred_2,ytest_pred_3]).T
x_test_1 = np.hstack([x_test,ytest_pred_all])
##用二级模型进行预测
y_pred = LR_model_fit.predict(x_test_1)
y_pred_proba = LR_model_fit.predict_proba(x_test_1)[:, 1]
###看一下混沌矩阵
cnf_matrix = confusion_matrix(y_test, y_pred)
recall_value = recall_score(y_test, y_pred)
precision_value = precision_score(y_test, y_pred)
acc = accuracy_score(y_test, y_pred)
print(cnf_matrix)
print('Validation set: model recall is {0},and percision is {1}'.format(recall_value,
precision_value))
##计算Ks值、AR
fpr, tpr, thresholds = roc_curve(y_test, y_pred_proba)
roc_auc = auc(fpr, tpr)
ks = max(tpr - fpr)
ar = 2*roc_auc-1
print('test set: model AR is {0},and ks is {1},auc={2}'.format(ar,
ks,roc_auc))
##绘制K-s曲线
plt.figure(figsize=(10,6))
fontsize_1 = 12
plt.plot(np.linspace(0,1,len(tpr)),tpr,'--',color='black')
plt.plot(np.linspace(0,1,len(tpr)),fpr,':',color='black')
plt.plot(np.linspace(0,1,len(tpr)),tpr - fpr,'-',color='grey')
plt.grid()
plt.xticks( fontsize=fontsize_1)
plt.yticks( fontsize=fontsize_1)
plt.xlabel('概率分组',fontsize=fontsize_1)
plt.ylabel('累积占比%',fontsize=fontsize_1)
|
Markdown | UTF-8 | 1,392 | 2.90625 | 3 | [] | no_license | # parallel-corpus-for-lexical-normalization
Hi,
This is a parallel corpus of slang sentences (sentences that may contain slang words) and formal sentences (sentances that only contain formal words) in Indonesian language. This dataset, consisting of 4,910 parallel sentence pairs, was used by <a href="https://colips.org/conferences/ialp2020/proceedings/papers/IALP2020_P32.pdf">Kurnia and Yulianti (2020)</a> for lexical/text normalization using statistical machine translation. The sentences in this dataset come from Instagram post that were collected in previous research (Salsabila et al., 2018) to build Indonesian colloquial lexicon. In this dataset, the --- is used as a separator between parallel sentence pairs; and the ~~~ symbol is used as a separator between a slang sentence and its corresponding formal sentence.
Please cite this paper if you use this dataset:<br>
@inproceedings{kurnia2020statistical,<br>
title={<b>Statistical Machine Translation Approach for Lexical Normalization on Indonesian Text</b>},<br>
author={<b>Kurnia, Ajmal and Yulianti, Evi</b>},<br>
booktitle={2020 International Conference on Asian Language Processing (IALP)},<br>
pages={288--293},<br>
year={2020},<br>
organization={IEEE}<br>
}
If you have any questions regarding this dataset, you may contact ajmal.kurnia@ui.ac.id.
Thank you!
|
Python | UTF-8 | 385 | 2.796875 | 3 | [] | no_license | import MySQLdb
#You must specify your localhost, login name, password for MySQL
#as well as the Database you are inserting into.
#This is to be setup beforehand while logged into MySQL.
host = 'localhost'
username = 'you'
password = 'password'
db = 'Database name'
def dbstuff():
database = MySQLdb.connect(host, username, password, db)
return database.cursor(), database
|
C | UTF-8 | 14,372 | 2.78125 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "base.h"
#include "cvector.h"
#include "nkctree.h"
static void _nkctree_alloc_rows( FR_nkctree * self ,
unsigned int row_count ){
self->row_count = row_count;
self->rows = malloc( sizeof( float* ) * row_count );
}
static void ntimes_print( char c , int n ){
for( int i = 0 ; i < n ; i++ ){
printf( "%c" , c );
}
}
void FR_nkctree_print( FR_nkctree * self ){
unsigned int w = self->width;
unsigned int hw = w/2;
const int chars = 4;
for( unsigned int r = 0 ; r < self->row_count ; r++ ){
unsigned int aw = self->rows[r]->size;
unsigned int skip = (w - aw)/2;
skip *= (chars+1);
for( int s = 0 ; s < skip ; s++ ){
printf(" ");
}
for( unsigned int c = 0 ; c < aw ; c++ ){
if( (c % self->set_size) != (self->set_size-1) ){
printf("%.2f " , ((float*)self->rows[r]->chunk)[c] );
}
else{
printf("%.2f|" , ((float*)self->rows[r]->chunk)[c] );
}
}
printf("\n");
}
}
void FR_nkctree_2latex( FR_nkctree * self ){
unsigned int w = self->width;
unsigned int hw = w/2;
const int chars = 4;
ntimes_print( 'c' , self->width / self->set_size );
for( unsigned int r = 0 ; r < self->row_count ; r++ ){
unsigned int aw = self->rows[r]->size;
unsigned int skip = (w - aw)/2;
skip /= self->set_size;
for( int s = 0 ; s < skip ; s++ ){
printf(" & ");
}
for( unsigned int c = 0 ; c < aw ; c++ ){
if( (c % self->set_size) != (self->set_size-1) ){
printf(" %.1f , " , ((float*)self->rows[r]->chunk)[c] );
}
else{
/* last item */
if( (aw == w) && (c == w-1) ){
printf("%.1f " , ((float*)self->rows[r]->chunk)[c] );
}
else{
printf("%.1f & " , ((float*)self->rows[r]->chunk)[c] );
}
}
}
for( int s = 1 ; s < skip ; s++ ){
printf(" & ");
}
printf("\\\\\n");
}
}
FR_matrix * FR_nkctree_val_to_mat( FR_nkctree * self ,
float * val ){
FR_matrix * out = FR_matrix_new( self->set_size , 1 , sizeof(float) );
memcpy( out->matrix_values[0] , val , sizeof(float) * self->set_size);
return out;
}
unsigned FR_matrix_crisp_p( FR_matrix * fm ){
for( unsigned y = 0 ; y < fm->rows ; y++ ){
for( unsigned x = 0; x < fm->cols ; x++ ){
float val = ((float**)fm->matrix_values)[y][x];
if( val != 1.0 &&
val != 0.0 ){
return 0;
}
}
}
return 1;
}
void FR_nkctree_sols( FR_nkctree * self ,
FR_matrix * Q ,
FR_matrix * T )
{
unsigned int w = self->width;
unsigned int hw = w/2;
const int chars = 4;
for( unsigned int r = 0 ; r < self->row_count ; r++ ){
unsigned int aw = self->rows[r]->size;
unsigned int skip = (w - aw)/2;
skip *= (chars+1);
for( int s = 0 ; s < skip ; s++ ){
printf(" ");
}
for( unsigned int c = 0 ; c < aw ; c++ ){
if( (c % self->set_size) == 0 ){
FR_matrix * Sol =
FR_nkctree_val_to_mat( self,
&(((float*)self->rows[r]->chunk)[c]));
if( FR_minsolution_fuzz_p( Sol , Q ,
T , self->k ) )
{
printf("%s" , KRED );
}
else if( FR_solution_fuzz_p( Sol , Q , T ) )
{
printf("%s" , KGRN );
}
else{
printf("%s" , KNRM );
}
FR_matrix_free( Sol );
}
if( (c % self->set_size) != (self->set_size-1) ){
printf("%.2f " , ((float*)self->rows[r]->chunk)[c] );
}
else{
printf("%.2f|" , ((float*)self->rows[r]->chunk)[c] );
}
}
printf("\n");
}
printf( "%s" , KNRM );
}
void FR_nkctree_2tikz( FR_nkctree * self ,
FR_matrix * Q ,
FR_matrix * T )
{
unsigned int w = self->width;
unsigned int hw = w/2;
const int chars = 4;
unsigned node_id = 0;
printf("%% height: %d\n" , self->row_count );
printf("\\documentclass[11pt]{article}\n"
"\\usepackage{amsmath}\n"
"\\usepackage{tikz}\n"
"\\usetikzlibrary{arrows,shapes,trees,patterns,backgrounds,svg.path}\n"
"\\begin{document}\n"
"\\begin{tikzpicture}[show background rectangle, scale=0.25, transform shape]\n");
FR_matrix * gtst = FR_eq_gtst_fuzz( Q , T );
for( unsigned int r = 0 ; r < self->row_count ; r++ ){
unsigned int aw = self->rows[r]->size;
unsigned int skip = (w - aw)/2;
unsigned left = skip/ self->set_size;
unsigned bottom = self->row_count-r;
for( unsigned int c = 0 ; c < aw ; c++ ){
if( (c % self->set_size) == 0 ){
FR_matrix * Sol =
FR_nkctree_val_to_mat( self,
&(((float*)self->rows[r]->chunk)[c]));
/* if( FR_matrix_crisp_p( Sol ) ){
printf("\\tikzstyle{every node} = [circle, fill=white]");
printf("\\node[circle,draw=black,line width=0.1mm, inner sep=1pt,minimum size=14pt] at (%d,%d) {};\n" , left , bottom );
}
*/
if( FR_minsolution_fuzz_p( Sol , Q ,
T , self->k ) )
{
printf("\\tikzstyle{every node} = [circle, fill=red]");
printf("\\node (s%d) at (%d, %d) {};\n" ,
node_id,
left,
bottom
);
}
else if( FR_solution_fuzz_p( Sol , Q , T ) )
{
printf("\\tikzstyle{every node} = [circle, fill=green]\n");
printf("\\node (s%d) at (%d, %d) {};\n" ,
node_id,
left,
bottom
);
}
else{
printf("\\tikzstyle{every node} = [circle, fill=black]");
printf("\\node (s%d) at (%d, %d) {};\n" ,
node_id,
left,
bottom
);
}
if( FR_fuzz_extra_subset_p( Sol , gtst ) ){
printf("\\draw[draw=black] (%f,%f) rectangle (%f,%f);\n" ,
(float)left-0.5 ,
(float)bottom+0.5,
(float)left+0.5,
(float)bottom-0.5);
}
if( c > 0 ){
printf("\\draw [-] (s%d) -- (s%d);\n",
node_id - 1 , node_id );
}
left++;
node_id++;
}
if( (c % self->set_size) != (self->set_size-1) ){
// printf("%.2f " , ((float*)self->rows[r]->chunk)[c] );
}
else{
// printf("%.2f|" , ((float*)self->rows[r]->chunk)[c] );
}
}
printf("\n");
}
printf( " \\end{tikzpicture}\n"
"\\end{document}");
}
unsigned FR_nkctree_sols_count( FR_nkctree * self ,
FR_matrix * Q,
FR_matrix * T , unsigned * min ){
unsigned count = 0;
unsigned int w = self->width;
unsigned int hw = w/2;
const int chars = 4;
if( min ){
*min = 0;
}
for( unsigned int r = 0 ; r < self->row_count ; r++ ){
unsigned int aw = self->rows[r]->size;
unsigned int skip = (w - aw)/2;
skip *= (chars+1);
for( unsigned int c = 0 ; c < aw ; c++ ){
if( (c % self->set_size) == 0 ){
FR_matrix * Sol =
FR_nkctree_val_to_mat( self,
&(((float*)self->rows[r]->chunk)[c]));
if( FR_solution_fuzz_p( Sol , Q , T ) )
{
count++;
if( FR_minsolution_fuzz_p( Sol , Q , T , self->k ) ){
(*min) = (*min) + 1;
printf("[MIN]=>\n");
}
else{
printf("[SOL]=>\n");
}
FR_matrix_fprint( Sol );
}
FR_matrix_free( Sol );
}
}
}
return count;
}
void FR_nkctree_free( FR_nkctree * self ){
for( int r = 0 ; r < self->row_count ; r++ ){
FR_cvector_free( self->rows[r] );
}
free( self->rows );
free( self );
}
static float _a( unsigned int k , unsigned int csz ){
float out = (float)k*(1.0/(float)(csz-1));
return (out > 1.0f ? 1.0f : out );
}
static FR_nkctree * _gen_1case( unsigned int k_chain ){
FR_nkctree * out = calloc( 1 , sizeof( FR_nkctree ) );
out->k = k_chain;
_nkctree_alloc_rows( out , 1 );
out->rows[0] = FR_cvector_new( sizeof(float) );
out->set_size = 1;
for( unsigned int kc = 0 ; kc < k_chain ; kc++ ){
float val = _a( kc , k_chain );
FR_cvector_push( out->rows[0] , (void*)&val );
}
out->width = k_chain;
out->print = FR_nkctree_print;
out->free = FR_nkctree_free;
return out;
}
static FR_nkctree * _gen_2case( unsigned int k_chain ){
FR_nkctree * out = calloc( 1 , sizeof( FR_nkctree ) );
_nkctree_alloc_rows( out , k_chain );
out->set_size = 2;
out->k = k_chain;
unsigned int lt_idx = k_chain -1;
unsigned int chain_len = 1;
for( int ik = 0 ; ik < k_chain ; ik ++ ){
unsigned int r_idx = 0;
unsigned int l_idx = lt_idx;
out->rows[ik] = FR_cvector_new( sizeof(float) );
for( unsigned int icl = 0 ; icl < chain_len ; icl++ ){
float val = _a( l_idx , k_chain );
FR_cvector_push( out->rows[ik] , (void*)&val );
val = _a( r_idx , k_chain );
FR_cvector_push( out->rows[ik] , (void*)&val );
if( icl < chain_len/2 ){
r_idx++;
}
else
{
l_idx++;
}
}
chain_len += 2;
lt_idx--;
}
out->width = out->rows[ out->row_count-1 ]->size;
out->print = FR_nkctree_print;
out->free = FR_nkctree_free;
return out;
}
static void copy_sigma( int sigma , FR_cvector * orig ,
FR_cvector * dest , unsigned int n )
{
int src_idx = sigma*n;
for( int c = 0 ; c < n ; c++ ){
FR_cvector_push( dest , &((float*)orig->chunk)[c+src_idx] );
}
}
/**/
FR_nkctree * FR_nkctree_new( unsigned int n , unsigned int k ){
if( n == 1 ){
return _gen_1case( k );
}
/* if( n == 2 ){
return _gen_2case( k );
}*/
FR_nkctree * prev = FR_nkctree_new( n-1 , k );
FR_cvector ** tree = NULL;
unsigned int rows_c = 0;
unsigned int width = 0;
for( int r = 0 ; r < prev->row_count ; r++ ){
int s = prev->rows[r]->size / (n-1);
if( s < k ){
tree = realloc( tree , (s + rows_c) * sizeof(FR_cvector*) );
for( int sig = s-1 ; sig >= 0 ; sig-- ){
int ks = 0;
tree[rows_c] = FR_cvector_new( sizeof(float) );
for( ks = 0 ; ks < (k-sig) ; ks++ ){
copy_sigma( sig , prev->rows[r] , tree[rows_c] , n-1 );
float aks = _a( ks , k );
FR_cvector_push( tree[rows_c] , (void*)&aks );
}
for( int sit = sig+1 ; sit < s ; sit++ ){
copy_sigma( sit , prev->rows[r],
tree[rows_c] , n-1 );
float aks = _a( ks , k );
FR_cvector_push( tree[rows_c] , (void*)&aks );
}
if( tree[rows_c]->size > width ){ width = tree[rows_c]->size; }
rows_c++;
}
}
else{ /* s >= k */
int a_target_i = 0;
tree = realloc( tree , (k + rows_c) * sizeof(FR_cvector*) );
for( int sig_k = k-1 ; sig_k >= 0 ; sig_k-- ){
tree[rows_c] = FR_cvector_new( sizeof(float) );
/* left chunk generation until break */
int a_i = 0;
for( a_i = 0 ; a_i < a_target_i ; a_i++ ){
copy_sigma( sig_k , prev->rows[r] , tree[rows_c] , n-1 );
float aks = _a( a_i , k );
FR_cvector_push( tree[rows_c] , (void*)&aks );
}
//a_i--;
/* right chunk generation until reach sigma reaches s */
for( int w_sig_k = sig_k ; w_sig_k < s ; w_sig_k++ ){
copy_sigma( w_sig_k , prev->rows[r] , tree[rows_c] , n-1 );
float aks = _a( a_i , k );
FR_cvector_push( tree[rows_c] , (void*)&aks );
}
a_target_i++;
if( tree[rows_c]->size > width ){ width = tree[rows_c]->size; }
rows_c++;
}
}
}
FR_nkctree_free( prev );
FR_nkctree * out = malloc( sizeof( FR_nkctree ) );
out->free = FR_nkctree_free;
out->print = FR_nkctree_print;
out->traverse = NULL;
out->row_count = rows_c;
out->set_size = n;
out->k = k;
/* TODO: establish width in two cases s < k or s >= k
it is easy
*/
out->width = width;
out->rows = tree;
return out;
}
|
Python | UTF-8 | 750 | 4.125 | 4 | [] | no_license | # exercise 52: Letter Grade to Grade Points
grade = input("enter letter grade: ")
points = ""
if grade == "F":
points = 0
elif grade == "D":
points = 1
elif grade == "D+":
points = 1.3
elif grade == "C-":
points = 1.7
elif grade == "C":
points = 2
elif grade == "C+":
points = 2.3
elif grade == "B-":
points = 2.7
elif grade == "B":
points = 3
elif grade == "B+":
points = 3.3
elif grade == "A-":
points = 3.7
elif grade == "A" or grade == "A+":
points = 4
if points != "":
print("a letter grade of {} corresponds to {} points".format(grade, points))
# if points was not assigned a value, it means input was not valid
else:
print("please enter a valid letter grade. Remember to use uppercase.") |
Python | UTF-8 | 5,346 | 3.65625 | 4 | [
"MIT"
] | permissive | #!/usr/bin/env python
# coding: utf-8
# In[19]:
#10:06pm version
import os
import csv
# Assign a variable to load a file from a path.
file_to_load = os.path.join("Resources", "election_results.csv")
# Assign a variable to save the file to a path.
file_to_save = os.path.join("analysis", "election_analysis.txt")
# Challenge County names and county votes
county_name = []
county_options = []
county_votes = {}
# Challenge largest county name and metrics
lcounty = ""
lcounty_votes = 0
# Initialize a total vote counter.
total_votes = 0
# Candidate Options
candidate_options = []
# 1. Declare the empty dictionary.
candidate_votes = {}
# Winning Candidate and Winning Count Tracker
winning_candidate = ""
winning_count = 0
winning_percentage = 0
# Open the election results and read the file.
with open(file_to_load) as election_data:
file_reader = csv.reader(election_data)
# Read the header row.
headers = next(file_reader)
# Print each row in the CSV file.
for row in file_reader:
# Add to the total vote count.
total_votes += 1
# Print the candidate name from each row.
candidate_name = row[2]
# get county name from each row
county_name = row[1]
#logic, if candidate doesn't match then add him to the list
if candidate_name not in candidate_options:
# Add the candidate name to the candidate list.
candidate_options.append(candidate_name)
# 2. Begin tracking that candidate's vote count. start at 0
candidate_votes[candidate_name] = 0
# else add candidate vote each time when candidate name matches
candidate_votes[candidate_name] += 1
# Challenge objective
# if county name is not already there, add it
if county_name not in county_options:
county_options.append(county_name)
#begin tracking county votes initialize with 0
county_votes[county_name] = 0
#add up county votes when it matches
county_votes[county_name] +=1
# challenge open write file
# for loop all counties
with open(file_to_save, "w") as txt_file:
for county in county_votes:
#figure out county vote count and percentages
county_vote = county_votes[county]
county_percent = int(county_vote)/int(total_votes) *100
county_results = (
f"{county}: {county_percent:.1f}% ({county_vote:,})\n")
print(county_results, end="")
txt_file.write(county_results)
# challenge determin winning county
if (county_vote > lcounty_votes):
lcounty_votes = county_vote
lcounty = county
#print the county with the largest turnout
lcounty = (
f"\n------------------\n"
f"Largest County turn out is: {lcounty}\n"
f"\n------------------\n")
print(lcounty)
txt_file.write(lcounty)
# Print the final vote count to the terminal.
election_results = (
f"\nElection Results\n"
f"-------------------------\n"
f"Total Votes: {total_votes:,}\n"
f"-------------------------\n")
print(election_results, end="")
# Save the final vote count to the text file.
txt_file.write(election_results)
# Print the candidate vote dictionary.
# print(candidate_votes)
# Determine the percentage of votes for each candidate by looping through the counts.
# 1. Iterate through the candidate list.
for candidate in candidate_votes:
# 2. Retrieve vote count of a candidate.
votes = candidate_votes[candidate]
# 3. Calculate the percentage of votes.
vote_percentage = int(votes) / int(total_votes) * 100
# 4. Print the candidate name and percentage of votes.
# print(f"{candidate}: received {vote_percentage:.1f}% of the vote.")
# To do: print out each candidate's name, vote count, and percentage of
# votes to the terminal.
# print(f"{candidate}: {vote_percentage:.1f}% ({votes:,})\n")
candidate_results = (f"{candidate}: {vote_percentage:.1f}% ({votes:,})\n")
# Print each candidate, their voter count, and percentage to the terminal.
print(candidate_results)
# Save the candidate results to our text file.
txt_file.write(candidate_results)
# Determine winning vote count and candidate
# 1. Determine if the votes are greater than the winning count.
if (votes > winning_count) and (vote_percentage > winning_percentage):
# 2. If true then set winning_count = votes and winning_percent =
# vote_percentage.
winning_count = votes
winning_percentage = vote_percentage
# 3. Set the winning_candidate equal to the candidate's name.
winning_candidate = candidate
winning_candidate_summary = (
f"-------------------------\n"
f"Winner: {winning_candidate}\n"
f"Winning Vote Count: {winning_count:,}\n"
f"Winning Percentage: {winning_percentage:.1f}%\n"
f"-------------------------\n")
print(winning_candidate_summary)
# Save the winning candidate's name to the text file.
txt_file.write(winning_candidate_summary)
# In[ ]:
|
Java | UTF-8 | 1,450 | 3.40625 | 3 | [] | no_license | package com.svetanis.datastructures.graph.clone;
import static com.google.common.collect.Lists.newLinkedList;
import static com.google.common.collect.Maps.newHashMap;
import static com.svetanis.java.base.collect.Maps.checkedGet;
import static com.svetanis.java.base.collect.Maps.checkedPut;
import java.util.Map;
import java.util.Queue;
public final class CloneGraphWithConnectedComponents {
public static Graph clone(Graph g) {
Map<Node, Node> map = newHashMap();
for (Node node : g.getNodes()) {
if (map.get(node) == null) {
clone(node, map);
}
}
Graph cloned = new Graph();
for (Node node : map.values()) {
cloned.addNode(node);
}
return cloned;
}
public static Node clone(Node src, Map<Node, Node> map) {
Queue<Node> queue = newLinkedList();
queue.offer(src);
checkedPut(map, src, new Node(src.data));
while (!queue.isEmpty()) {
Node node = queue.poll();
Node copy = map.get(node);
if (copy == null) {
copy = new Node(node.data);
checkedPut(map, node, copy);
}
for (Node child : node.children) {
Node clone = map.get(child);
if (clone == null) {
queue.offer(child);
clone = new Node(child.data);
checkedPut(map, child, clone);
}
copy.children.add(clone);
}
}
return checkedGet(map, src);
}
public static void main(String[] args) {
}
}
|
Java | UTF-8 | 2,481 | 2.15625 | 2 | [] | no_license | package com.ecostore.controller.admin.api;
import com.ecostore.model.MenuModel;
import com.ecostore.model.UserModel;
import com.ecostore.service.IMenuService;
import com.ecostore.utils.SessionUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import javax.inject.Inject;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(urlPatterns = "/api-admin-menu")
public class MenuAPI extends HttpServlet {
@Inject
private IMenuService menuService;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ObjectMapper mapper = new ObjectMapper();
request.setCharacterEncoding("UTF8");
response.setContentType("application/json");
MenuModel menuModel = mapper.readValue(request.getInputStream(), MenuModel.class);
UserModel userModel = (UserModel) SessionUtil.getInstance().getValue(request, "USERMODEL");
menuModel.setCreatedBy(userModel.getUsername());
menuModel = menuService.insert(menuModel);
mapper.writeValue(response.getOutputStream(), menuModel);
}
@Override
protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ObjectMapper mapper = new ObjectMapper();
request.setCharacterEncoding("UTF8");
response.setContentType("application/json");
MenuModel menuModel = mapper.readValue(request.getInputStream(), MenuModel.class);
UserModel userModel = (UserModel) SessionUtil.getInstance().getValue(request, "USERMODEL");
menuModel.setModifiedBy(userModel.getUsername());
menuModel = menuService.update(menuModel);
mapper.writeValue(response.getOutputStream(), menuModel);
}
@Override
protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ObjectMapper mapper = new ObjectMapper();
request.setCharacterEncoding("UTF8");
response.setContentType("application/json");
MenuModel menuModel = mapper.readValue(request.getInputStream(), MenuModel.class);
boolean result = menuService.delete(menuModel.getIds());
mapper.writeValue(response.getOutputStream(), result);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.