hexsha
stringlengths 40
40
| size
int64 5
1.05M
| ext
stringclasses 98
values | lang
stringclasses 21
values | max_stars_repo_path
stringlengths 3
945
| max_stars_repo_name
stringlengths 4
118
| max_stars_repo_head_hexsha
stringlengths 40
78
| max_stars_repo_licenses
listlengths 1
10
| max_stars_count
int64 1
368k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 3
945
| max_issues_repo_name
stringlengths 4
118
| max_issues_repo_head_hexsha
stringlengths 40
78
| max_issues_repo_licenses
listlengths 1
10
| max_issues_count
int64 1
134k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 3
945
| max_forks_repo_name
stringlengths 4
135
| max_forks_repo_head_hexsha
stringlengths 40
78
| max_forks_repo_licenses
listlengths 1
10
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 5
1.05M
| avg_line_length
float64 1
1.03M
| max_line_length
int64 2
1.03M
| alphanum_fraction
float64 0
1
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4bffb0fb3e0ede71e36c3009b370906c079b08f3
| 22,112
|
h
|
C
|
Tudat/Astrodynamics/BasicAstrodynamics/convertMeanToEccentricAnomalies.h
|
JPelamatti/ThesisTUDAT
|
b94ce35fb7c8fa44ae83238e296a979dfa3adfe8
|
[
"BSD-3-Clause"
] | null | null | null |
Tudat/Astrodynamics/BasicAstrodynamics/convertMeanToEccentricAnomalies.h
|
JPelamatti/ThesisTUDAT
|
b94ce35fb7c8fa44ae83238e296a979dfa3adfe8
|
[
"BSD-3-Clause"
] | null | null | null |
Tudat/Astrodynamics/BasicAstrodynamics/convertMeanToEccentricAnomalies.h
|
JPelamatti/ThesisTUDAT
|
b94ce35fb7c8fa44ae83238e296a979dfa3adfe8
|
[
"BSD-3-Clause"
] | 1
|
2019-05-30T03:42:22.000Z
|
2019-05-30T03:42:22.000Z
|
/* Copyright (c) 2010-2015, Delft University of Technology
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
* - Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* - Neither the name of the Delft University of Technology nor the names of its contributors
* may be used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Changelog
* YYMMDD Author Comment
* 110210 K. Kumar File created.
* 110215 E. Iorfida Minor changes made.
* 110810 J. Leloux Corrected doxygen documentation.
* 120326 D. Dirkx Changed raw pointers to shared pointers.
* 120421 K. Kumar Removed base class; updated to set values through constructor.
* 120813 P. Musegaas Changed code to new root finding structure. Added option to
* specify which rootfinder and termination conditions to use.
* 120822 P. Musegaas Added functionality for near-parabolic cases. Added option for
* user to specifiy initial guess.
* 120903 P. Musegaas Added additional comments on the scope of the method and
* the 'conversion' of mean anomaly to 0 to 2*PI regime.
* 121205 P. Musegaas Updated code to final version of rootfinders.
* 130116 E. Heeren Minor changes to comments.
* 130120 K. Kumar Added shared-pointer typedef.
* 130123 K. Kumar Added note about near-parabolic cases.
* 140110 E. Brandon Fixed Doxygen comments.
* 150417 D. Dirkx Made modifications for templated element conversions.
*
* References
* Regarding method in general:
* Chobotov, V.A. Orbital Mechanics, Third Edition, AIAA Education Series, VA, 2002.
* Wakker, K. F. Astrodynamics I + II. Lecture Notes AE4-874, Delft University of
* Technology, Delft, Netherlands.
* Regarding the choice of initial guess:
* Musegaas, P., Optimization of Space Trajectories Including Multiple Gravity Assists and
* Deep Space Maneuvers, MSc thesis report, Delft University of Technology, 2012.
* [unpublished so far]. Section available on tudat website (tudat.tudelft.nl)
* under issue #539.
*
* Notes
* There are known to be some issues on some systems with near-parabolic orbits that are very
* close to eccentricity=1.0. For these orbits, the unit tests establish that they are able
* to generate consistent results by converting to and from eccentric anomaly to a precision
* of 1.0e-9. If this quality of solution is not adequate for specific applications, the user
* should investigate the code further.
*
*/
#ifndef TUDAT_CONVERT_MEAN_ANOMALY_TO_ECCENTRIC_ANOMALY_H
#define TUDAT_CONVERT_MEAN_ANOMALY_TO_ECCENTRIC_ANOMALY_H
#include <boost/exception/all.hpp>
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
#include <boost/math/special_functions/asinh.hpp>
#include <cmath>
#include "Tudat/Mathematics/RootFinders/newtonRaphson.h"
#include "Tudat/Mathematics/RootFinders/rootFinder.h"
#include "Tudat/Mathematics/RootFinders/bisection.h"
#include "Tudat/Mathematics/RootFinders/terminationConditions.h"
#include "Tudat/Mathematics/BasicMathematics/mathematicalConstants.h"
#include "Tudat/Mathematics/BasicMathematics/basicMathematicsFunctions.h"
#include "Tudat/Mathematics/BasicMathematics/functionProxy.h"
namespace tudat
{
namespace orbital_element_conversions
{
//! Compute Kepler's function for elliptical orbits.
/*!
* Computes Kepler's function, given as:
* \f[
* f( E ) = E - e * sin( E ) - M
* \f]
* for elliptical orbits, where \f$ E \f$ is the eccentric anomaly, \f$ e \f$ is the
* eccentricity, \f$ M \f$ is the mean anomaly. All eccentricities >= 0.0 and < 1.0 are valid.
* \param eccentricAnomaly Eccentric anomaly.
* \param eccentricity Eccentricity.
* \param meanAnomaly Mean anomaly.
* \return Value of Kepler's function for elliptical orbits.
*/
template< typename ScalarType = double >
ScalarType computeKeplersFunctionForEllipticalOrbits( const ScalarType eccentricAnomaly,
const ScalarType eccentricity,
const ScalarType meanAnomaly )
{
return eccentricAnomaly - eccentricity * std::sin( eccentricAnomaly ) - meanAnomaly;
}
//! Compute first-derivative of Kepler's function for elliptical orbits.
/*!
* Computes the first-derivative of Kepler's function, given as:
* \f[
* \frac{ df( E ) } { dE } = 1 - e * cos( E )
* \f]
* for elliptical orbits, where \f$ E \f$ is the eccentric anomaly, and \f$ e \f$ is the
* eccentricity. All eccentricities >= 0.0 and < 1.0 are valid.
* \param eccentricAnomaly Eccentric anomaly.
* \param eccentricity Eccentricity.
* \return Value of first-derivative of Kepler's function for elliptical orbits.
*/
template< typename ScalarType = double >
ScalarType computeFirstDerivativeKeplersFunctionForEllipticalOrbits(
const ScalarType eccentricAnomaly,
const ScalarType eccentricity )
{
return mathematical_constants::getFloatingInteger< ScalarType >( 1 )-
eccentricity * std::cos( eccentricAnomaly );
}
//! Compute Kepler's function for hyperbolic orbits.
/*!
* Computes Kepler's function, given as:
* \f[
* f( F ) = e * sinh( F ) - F - M
* \f]
* for hyperbolic orbits, where \f$ F \f$ is the hyperbolic eccentric anomaly, \f$ e \f$ is the
* eccentricity, \f$ M \f$ is the mean anomaly. All eccentricities > 1.0 are valid.
* \param hyperbolicEccentricAnomaly Hyperbolic eccentric anomaly.
* \param eccentricity Eccentricity.
* \param hyperbolicMeanAnomaly Hyperbolic mean anomaly..
* \return Value of Kepler's function for hyperbolic orbits.
*/
template< typename ScalarType = double >
ScalarType computeKeplersFunctionForHyperbolicOrbits( const ScalarType hyperbolicEccentricAnomaly,
const ScalarType eccentricity,
const ScalarType hyperbolicMeanAnomaly )
{
return eccentricity * std::sinh( hyperbolicEccentricAnomaly )
- hyperbolicEccentricAnomaly - hyperbolicMeanAnomaly;
}
//! Compute first-derivative of Kepler's function for hyperbolic orbits.
/*!
* Computes the first-derivative of Kepler's function, given as:
* \f[
* \frac{ df( F ) } { dF } = e * cosh( F ) - 1
* \f]
* for hyperbolic orbits, where \f$ F \f$ is the hyperbolic eccentric anomaly, and \f$ e \f$ is
* the eccentricity. All eccentricities > 1.0 are valid.
* \param hyperbolicEccentricAnomaly Hyperbolic eccentric anomaly
* \param eccentricity Eccentricity.
* \return Value of first-derivative of Kepler's function for hyperbolic orbits.
*/
template< typename ScalarType = double >
ScalarType computeFirstDerivativeKeplersFunctionForHyperbolicOrbits(
const ScalarType hyperbolicEccentricAnomaly,
const ScalarType eccentricity)
{
return eccentricity * std::cosh( hyperbolicEccentricAnomaly ) - 1.0;
}
//! Convert mean anomaly to eccentric anomaly.
/*!
* Converts mean anomaly to eccentric anomaly for elliptical orbits for all eccentricities >=
* 0.0 and < 1.0. If the conversion fails or the eccentricity falls outside the valid range,
* then ScalarType::NaN is returned. Calculated with an accuracy of 1.0e-13 for all cases, except
* for some near-parabolic cases in which macine precision problems occur. These are tested
* against an accuracy of 1.0e-9. Near-parabolic in this sense means e > 1.0-1.0e-11. Also
* note that your mean anomaly is automatically transformed to fit within the 0 to 2.0*PI
* spectrum. Numerical tests performed using double ScalarType.
* \param eccentricity Eccentricity of the orbit [-].
* \param aMeanAnomaly Mean anomaly to convert to eccentric anomaly [rad].
* \param useDefaultInitialGuess Boolean specifying whether to use default initial guess [-].
* \param userSpecifiedInitialGuess Initial guess for rootfinder [rad].
* \param aRootFinder Shared-pointer to the rootfinder that is to be used. Default is
* Newton-Raphson using 1000 iterations as maximum and apprximately 1.0e-13 absolute
* X-tolerance (for doubles; 500 times ScalarType resolution ).
* Higher precision may invoke machine precision problems for some values.
* \return Eccentric anomaly [rad].
*/
template< typename ScalarType = double >
ScalarType convertMeanAnomalyToEccentricAnomaly(
const ScalarType eccentricity, const ScalarType aMeanAnomaly,
const bool useDefaultInitialGuess = true,
const ScalarType userSpecifiedInitialGuess = TUDAT_NAN,
boost::shared_ptr< root_finders::RootFinderCore< ScalarType > > aRootFinder =
boost::shared_ptr< root_finders::RootFinderCore< ScalarType > >( ) )
{
using namespace mathematical_constants;
using namespace root_finders;
using namespace root_finders::termination_conditions;
// Set mean anomaly to region between 0 and 2 PI.
ScalarType meanAnomaly = basic_mathematics::computeModulo< ScalarType >(
aMeanAnomaly, getFloatingInteger< ScalarType >( 2 ) *
getPi< ScalarType >( ) );
boost::shared_ptr< RootFinderCore< ScalarType > > rootFinder = aRootFinder;
// Required because the make_shared in the function definition gives problems for MSVC.
if ( !rootFinder.get( ) )
{
ScalarType tolerance = 200.0 * std::numeric_limits< ScalarType >::epsilon( );
// Loosen tolerance for near-parabolic orbits
if( std::fabs( eccentricity - getFloatingInteger< ScalarType >( 1 ) ) <
1.0E5 * std::numeric_limits< ScalarType >::epsilon( ) )
{
tolerance *= 2.5;
}
rootFinder = boost::make_shared< NewtonRaphsonCore< ScalarType > >(
boost::bind(
&RootAbsoluteToleranceTerminationCondition< ScalarType >::
checkTerminationCondition,
boost::make_shared< RootAbsoluteToleranceTerminationCondition
< ScalarType > >( tolerance, 1000 ), _1, _2, _3, _4, _5 ) );
}
// Declare eccentric anomaly.
ScalarType eccentricAnomaly = TUDAT_NAN;
// Check if orbit is elliptical, and not near-parabolic.
if ( eccentricity < getFloatingInteger< ScalarType >( 1 ) &&
eccentricity >= getFloatingInteger< ScalarType >( 0 ) )
{
// Create an object containing the function of which we whish to obtain the root from.
boost::shared_ptr< basic_mathematics::FunctionProxy< ScalarType, ScalarType > > rootFunction
= boost::make_shared< basic_mathematics::FunctionProxy< ScalarType, ScalarType > >(
boost::bind( &computeKeplersFunctionForEllipticalOrbits< ScalarType >, _1,
eccentricity, meanAnomaly ) );
// Add the first derivative of the root function.
rootFunction->addBinding(
-1, boost::bind(
&computeFirstDerivativeKeplersFunctionForEllipticalOrbits< ScalarType >, _1,
eccentricity ) );
// Declare initial guess.
ScalarType initialGuess = TUDAT_NAN;
// Set the initial guess. Check if the default scheme is to be used or a user specified
// value should be used.
// !!!!!!!!!!!!! IMPORTANT !!!!!!!!!!!!!
// If this scheme is changed, please run a very extensive test suite. The root finder
// function tends to be chaotic for some very specific combinations of mean anomaly and
// eccentricity. Various random tests of 100.000.000 samples were done to verify the
// functionality of this one, and of another option for the starter: PI. [Musegaas,2012]
if ( useDefaultInitialGuess )
{
if ( meanAnomaly > getPi< ScalarType >( ) )
{
initialGuess = meanAnomaly - eccentricity;
}
else
{
initialGuess = meanAnomaly + eccentricity;
}
}
else
{
initialGuess = userSpecifiedInitialGuess;
}
// Set eccentric anomaly based on result of Newton-Raphson root-finding algorithm.
eccentricAnomaly = rootFinder->execute( rootFunction, initialGuess );
}
// Eccentricity is invalid: eccentricity < 0.0 or eccentricity >= 1.0.
else
{
boost::throw_exception(
std::runtime_error(
boost::str( boost::format(
"Invalid eccentricity. Valid range is 0.0 <= e < 1.0. "
"Eccentricity was: '%f'." )
% eccentricity ) ) );
}
// Return eccentric anomaly.
return eccentricAnomaly;
}
//! Convert mean anomaly to hyperbolic eccentric anomaly.
/*!
* Converts mean anomaly to hyperbolic eccentric anomaly for hyperbolic orbits for all
* eccentricities > 1.0. If the conversion fails or the eccentricity falls outside the valid
* range, then double::NaN is returned. Calculated with an accuracy of 1.0e-14 for all
* reasonable cases (eccentricities up to 1.0e15, mean anomalies -1.2e12 to 1.2e12, test cases
* using doubles).
* \param eccentricity Eccentricity of the orbit [-].
* \param hyperbolicMeanAnomaly Hyperbolic mean anomaly to convert to eccentric anomaly [rad].
* \param useDefaultInitialGuess Boolean specifying whether to use default initial guess [-].
* \param userSpecifiedInitialGuess Initial guess for rootfinder [rad].
* \param aRootFinder Shared-pointer to the rootfinder that is to be used. Default is
* Newton-Raphson using 1000 iterations as maximum and apprximately 5.0e-15 absolute
* X-tolerance (for doubles; 25 times ScalarType resolution ).
* Higher precision may invoke machine precision problems for some values.
* \return Hyperbolic eccentric anomaly.
*/
template< typename ScalarType = double >
ScalarType convertMeanAnomalyToHyperbolicEccentricAnomaly(
const ScalarType eccentricity, const ScalarType hyperbolicMeanAnomaly,
const bool useDefaultInitialGuess = true,
const ScalarType userSpecifiedInitialGuess = TUDAT_NAN,
boost::shared_ptr< root_finders::RootFinderCore< ScalarType > > aRootFinder =
boost::shared_ptr< root_finders::RootFinderCore< ScalarType > >( ) )
{
using namespace mathematical_constants;
using namespace root_finders;
using namespace root_finders::termination_conditions;
boost::shared_ptr< RootFinderCore< ScalarType > > rootFinder = aRootFinder;
// Required because the make_shared in the function definition gives problems for MSVC.
if ( !rootFinder.get( ) )
{
rootFinder = boost::make_shared< NewtonRaphsonCore< ScalarType > >(
boost::bind(
&RootAbsoluteToleranceTerminationCondition< ScalarType >::
checkTerminationCondition,
boost::make_shared<
RootAbsoluteToleranceTerminationCondition< ScalarType > >(
25.0 * std::numeric_limits< ScalarType >::epsilon( ), 1000 ),
_1, _2, _3, _4, _5 ) );
}
// Declare hyperbolic eccentric anomaly.
ScalarType hyperbolicEccentricAnomaly = TUDAT_NAN;
// Check if orbit is hyperbolic.
if ( eccentricity > getFloatingInteger< ScalarType >( 1 ) )
{
// Create an object containing the function of which we whish to obtain the root from.
boost::shared_ptr< basic_mathematics::FunctionProxy< ScalarType, ScalarType > > rootFunction
= boost::make_shared< basic_mathematics::FunctionProxy< ScalarType, ScalarType > >(
boost::bind( &computeKeplersFunctionForHyperbolicOrbits< ScalarType >, _1,
eccentricity, hyperbolicMeanAnomaly ) );
// Add the first derivative of the root function.
rootFunction->addBinding(
-1, boost::bind(
&computeFirstDerivativeKeplersFunctionForHyperbolicOrbits< ScalarType >,
_1, eccentricity ) );
// Declare initial guess.
ScalarType initialGuess = TUDAT_NAN;
// Set the initial guess. Check if the default scheme is to be used or a user specified
// value should be used. See [Wakker, 2007] for derivations of the default values.
// Note that an error was detected in these starter values, as is discussed in
// [Musegaas,2012].
// !!!!!!!!!!!!! IMPORTANT !!!!!!!!!!!!!
// If this scheme is changed, please run a very extensive test suite. The root finder
// function tends to be chaotic for some very specific combinations of mean anomaly and
// eccentricity. Various random tests of 100.000.000 samples were done to verify the
// functionality of this one. [Musegaas,2012]
if ( useDefaultInitialGuess )
{
if ( std::abs( hyperbolicMeanAnomaly ) <
getFloatingInteger< ScalarType >( 6 ) * eccentricity )
{
initialGuess =
std::sqrt( getFloatingInteger< ScalarType >( 8 ) *
( eccentricity - getFloatingInteger< ScalarType >( 1 ) ) /
eccentricity ) *
std::sinh( getFloatingFraction< ScalarType >( 1, 3 ) * boost::math::asinh(
getFloatingInteger< ScalarType >( 3 ) *
hyperbolicMeanAnomaly /
( std::sqrt( getFloatingInteger< ScalarType >( 8 ) *
( eccentricity -
getFloatingInteger< ScalarType >( 1 ) ) /
eccentricity ) *
( eccentricity - getFloatingInteger< ScalarType >( 1 )
) ) ) );
}
else if ( hyperbolicMeanAnomaly > getFloatingInteger< ScalarType >( 6 ) * eccentricity )
{
initialGuess = ( std::log( getFloatingInteger< ScalarType >( 2 ) *
hyperbolicMeanAnomaly / eccentricity ) );
}
else
{
initialGuess = ( - std::log( -getFloatingInteger< ScalarType >( 2 ) *
hyperbolicMeanAnomaly / eccentricity ) );
}
}
else
{
initialGuess = userSpecifiedInitialGuess;
}
// Set hyperbolic eccentric anomaly based on result of Newton-Raphson root-finding
// algorithm.
try
{
hyperbolicEccentricAnomaly = rootFinder->execute( rootFunction, initialGuess );
}
catch( std::runtime_error )
{
rootFinder = boost::make_shared< BisectionCore< ScalarType > >(
boost::bind(
&RootAbsoluteToleranceTerminationCondition< ScalarType >::
checkTerminationCondition,
boost::make_shared<
RootAbsoluteToleranceTerminationCondition< ScalarType > >(
20.0 * std::numeric_limits< ScalarType >::epsilon( ), 1000 ),
_1, _2, _3, _4, _5 ), getFloatingInteger< ScalarType >( 0 ),
getFloatingInteger< ScalarType >( 2 ) * getPi< ScalarType >( ) );
hyperbolicEccentricAnomaly = rootFinder->execute( rootFunction, initialGuess );
}
}
// In this case the orbit is not hyperbolic.
else
{
boost::throw_exception(
std::runtime_error(
boost::str(
boost::format(
"Invalid eccentricity. Valid range is e > 1.0."
"Eccentricity was: '%f'." )
% eccentricity ) ) );
}
// Return hyperbolic eccentric anomaly.
return hyperbolicEccentricAnomaly;
}
} // namespace orbital_element_conversions
} // namespace tudat
#endif // TUDAT_CONVERT_MEAN_ANOMALY_TO_ECCENTRIC_ANOMALY_H
| 49.137778
| 100
| 0.636577
|
25e8366d4cb75f549e539175029ec47c130b54fd
| 1,110
|
cs
|
C#
|
Kontur.Tests.Results/Instantiation/Optional/TernaryOperator_Should.cs
|
skbkontur/result
|
87c41d6d26b280da6accdc2cffc145accaa092c1
|
[
"MIT"
] | 10
|
2021-11-18T18:26:32.000Z
|
2022-01-17T10:10:03.000Z
|
Kontur.Tests.Results/Instantiation/Optional/TernaryOperator_Should.cs
|
skbkontur/result
|
87c41d6d26b280da6accdc2cffc145accaa092c1
|
[
"MIT"
] | null | null | null |
Kontur.Tests.Results/Instantiation/Optional/TernaryOperator_Should.cs
|
skbkontur/result
|
87c41d6d26b280da6accdc2cffc145accaa092c1
|
[
"MIT"
] | 1
|
2021-11-20T08:21:33.000Z
|
2021-11-20T08:21:33.000Z
|
using Kontur.Results;
using NUnit.Framework;
namespace Kontur.Tests.Results.Instantiation.Optional
{
[TestFixture]
internal class TernaryOperator_Should
{
private const int SomeValue = 7;
private static TestCaseData CreateCase(bool flag, Optional<int> result)
{
return new(flag) { ExpectedResult = result };
}
private static readonly TestCaseData[] Cases =
{
CreateCase(true, SomeValue),
CreateCase(false, Kontur.Results.Optional.None()),
};
[TestCaseSource(nameof(Cases))]
public Optional<int> Create_Via_Other_Argument_Implicit_Conversion(bool flag)
{
var optional = flag
? Kontur.Results.Optional.Some(SomeValue)
: Kontur.Results.Optional.None();
return optional;
}
[TestCaseSource(nameof(Cases))]
public Optional<int> Create_Via_Target_Type_Inference(bool flag)
{
return flag
? SomeValue
: Kontur.Results.Optional.None();
}
}
}
| 27.75
| 85
| 0.593694
|
da6e42dd2cd77592e4a4e2bb66654e111eedbf74
| 6,030
|
php
|
PHP
|
src/WW/Vfs/Iterator/Virtual.php
|
wwsh/vfs
|
abba938055605e0497edb00a497d58a7eb6068f4
|
[
"MIT"
] | null | null | null |
src/WW/Vfs/Iterator/Virtual.php
|
wwsh/vfs
|
abba938055605e0497edb00a497d58a7eb6068f4
|
[
"MIT"
] | null | null | null |
src/WW/Vfs/Iterator/Virtual.php
|
wwsh/vfs
|
abba938055605e0497edb00a497d58a7eb6068f4
|
[
"MIT"
] | null | null | null |
<?php
/**
* The MIT License (MIT)
*
* Copyright (c) 2016 WW Software House
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
namespace WW\Vfs\Iterator;
use WW\Vfs\Iterator\Exception\VfsException;
/**
* Class Virtual
* @package AppBundle\Iterator
*/
class Virtual implements IteratorInterface
{
/**
* Contains the virtual file system definition data.
* This is being iterated on.
*
* @var array
*/
private $vfs;
/**
* Currently parsed path.
*
* @var string
*/
private $path;
/**
* The current data.
*
* @var
*/
private $cursor;
/**
* Virtual constructor.
* @param $vfsDefinition
* @param string $path
* @throws \Exception
*/
public function __construct($path, $vfsDefinition)
{
if (is_string($vfsDefinition)) {
if (false === file_exists($vfsDefinition)) {
throw new VfsException('File not found');
}
if (false === is_readable($vfsDefinition)) {
throw new VfsException('No permission to read file: ' . $vfsDefinition);
}
$contents = file_get_contents($vfsDefinition);
$this->vfs = json_decode($contents, true);
} elseif (is_array($vfsDefinition)) {
$this->vfs = $vfsDefinition;
}
if (null === $vfsDefinition || empty($vfsDefinition) || empty($this->vfs)) {
throw new \Exception('VFS empty');
}
if ($path === null) {
$path = key($this->vfs);
}
$this->path = $path;
if (!isset($this->vfs[$path])) {
throw new \Exception('Path not found');
}
$this->cursor = $this->vfs[$path];
$this->rewind();
}
/**
* Whenever we need to convert the current iterator to string,
* in other words, iterator must be printable (return current filename).
*
* @return string
*/
public function __toString()
{
if (!current($this->cursor)) {
return '';
}
$key = key($this->cursor);
$result = !is_numeric($key) ? $key : current($this->cursor);
return (string)$result;
}
/**
* Getting the filename. Using the __toString()
*
* @return string
*/
public function getFilename()
{
$current = $this->current();
return (string)$current;
}
/**
* Getting the path being iterated.
*
* @return null|string
*/
public function getPath()
{
return $this->path;
}
/**
* Getting the isDirectory flag.
*
* Actually, we don't keep such information.
* We presume that numeric keys mean we have reached the file level.
*
* @return bool
*/
public function isDir()
{
$key = key($this->cursor);
return $this->valid() ? !is_numeric($key) : false;
}
/**
* Always false. Not supported.
*
* @return bool
*/
public function isDot()
{
return false;
}
/**
* Inversion of isDir()
*
* @return bool
*/
public function isFile()
{
return $this->valid() ? !$this->isDir() : false;
}
/**
* The classic iterator returns a file structure.
* We are returning ourselves just to keep simplicity.
*
* @return mixed
*/
public function current()
{
$current = current($this->cursor);
if (!$current) {
return false;
}
return $this;
}
/**
* This is internally driven by the php array key mechanism.
*
* @return mixed
*/
public function next()
{
return next($this->cursor);
}
/**
* If we are at the end, php's current no longer returns anything
* except false.
*
* @return bool
*/
public function valid()
{
$current = current($this->cursor);
if (!$current) {
return false;
}
return true;
}
/**
* Entering a sub-element in the data tree.
*
* Determining a new "mounting point" in the array
* and creating an iterator copy with it.
* This makes the recursion possible.
*
* @return Virtual|bool
*/
public function getChildren()
{
$current = current($this->cursor);
$key = key($this->cursor);
if (!$current) {
return false;
}
$newPath = $this->path . '/' . $key;
$subVfs = [
$newPath => $current
];
return new self($newPath, $subVfs);
}
/**
* Obviously files cannot have children :)
*
* @return bool
*/
public function hasChildren()
{
return $this->isDir();
}
/**
* Based on classic php's rewind() method.
*/
public function rewind()
{
reset($this->cursor);
}
}
| 22.669173
| 88
| 0.554892
|
2cccaf2fcfb042d4bb2d9a8cc0c43129b65f30da
| 2,755
|
py
|
Python
|
PyBank/main.py
|
ali-beer/python-challenge
|
94f8557efb3495bf6eda01aa302bcc43c83a31b3
|
[
"ADSL"
] | null | null | null |
PyBank/main.py
|
ali-beer/python-challenge
|
94f8557efb3495bf6eda01aa302bcc43c83a31b3
|
[
"ADSL"
] | null | null | null |
PyBank/main.py
|
ali-beer/python-challenge
|
94f8557efb3495bf6eda01aa302bcc43c83a31b3
|
[
"ADSL"
] | null | null | null |
## PyBank
# Import os module and module for reading CSV files
import os
import csv
csvpath = os.path.join("Resources","budget_data.csv")
# Create variables to store data
date = []
profit_losses = []
amount = 0
# Open and read csv
with open(csvpath) as csvfile:
csv_reader = csv.reader(csvfile, delimiter=",")
# Read the header row first (stores the line that it skips)
csv_header = next(csv_reader)
# Read each row of data (everything 1 indent in from here is in the for loop)
for row in csv_reader:
# Add date to month list
date.append(row[0])
# Add profit/losses to list
profit_losses.append(int(row[1]))
# Add Profit/Losses to amount variable
amount += int(row[1])
# The total months
month_count = (len(date))
# Create List to store the changes in "Profit/Losses" over the entire period
profit_losses_change = []
# Enumerate allows you to keep track of index and item itself whereas a 'for loop' keeps track of item only.
# Note: If range of length is 10, -1 is telling it to only loop 9 times
for i, item in enumerate(range(len(profit_losses)-1)):
change = (profit_losses[i+1] - profit_losses[i])
profit_losses_change.append(change)
# The average change
average_change = round(sum(profit_losses_change) / len(profit_losses_change), 2)
# The greatest increase and decrease in profits (date and amount) over the entire period
max_increase = max(profit_losses_change)
max_decrease = min(profit_losses_change)
# Locate the index value of greatest increase and decrease in profits
max_increase_index = profit_losses_change.index(max_increase)
max_decrease_index = profit_losses_change.index(max_decrease)
# Obtain the date associated with greatest increase and decrease
date_max_increase = date[profit_losses_change.index(max_increase)+1]
date_max_decrease = date[profit_losses_change.index(max_decrease)+1]
# Print results
print("Financial Analysis")
print('----------------------------------------------')
print(f'Total months: {month_count}')
print(f'Total: ${amount}')
print(f'Average Change: ${average_change}')
print(f'Greatest Increase in Profits: {date_max_increase} (${max_increase})')
print(f'Greatest Decrease in Profits: {date_max_decrease} (${max_decrease})')
# Write results to text file
f = open("Analysis/Output.txt", "w")
f.write('Financial Analysis\n')
f.write('--------------------------------------------------\n')
f.write(f'Total months: {month_count}\n')
f.write(f'Total: ${amount}\n')
f.write(f'Average Change: ${average_change}\n')
f.write(f'Greatest Increase in Profits: {date_max_increase} (${max_increase})\n')
f.write(f'Greatest Decrease in Profits: {date_max_decrease} (${max_decrease})\n')
f.close()
| 35.320513
| 109
| 0.703811
|
69c00642bac61abc1cfc1928d2ff555d7d0e809b
| 396
|
dart
|
Dart
|
main.dart
|
nareshfeb/m2plist
|
a9a241256471471aee9ca500aa2f051301b0695c
|
[
"MIT"
] | null | null | null |
main.dart
|
nareshfeb/m2plist
|
a9a241256471471aee9ca500aa2f051301b0695c
|
[
"MIT"
] | null | null | null |
main.dart
|
nareshfeb/m2plist
|
a9a241256471471aee9ca500aa2f051301b0695c
|
[
"MIT"
] | null | null | null |
import 'package:flutter/material.dart';
import 'package:m2ptask/homepage.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
const MyApp({Key key}) : super(key: key);
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
return Homepage();
}
}
| 20.842105
| 46
| 0.674242
|
6627e8ab1484486b7fd5b43da6fd62f580364bc3
| 17,531
|
py
|
Python
|
src_nlp/tensorflow/depreciated/toward-control/model.py
|
ashishpatel26/finch
|
bf2958c0f268575e5d51ad08fbc08b151cbea962
|
[
"MIT"
] | 1
|
2019-02-12T09:22:00.000Z
|
2019-02-12T09:22:00.000Z
|
src_nlp/tensorflow/depreciated/toward-control/model.py
|
loopzxl/finch
|
bf2958c0f268575e5d51ad08fbc08b151cbea962
|
[
"MIT"
] | null | null | null |
src_nlp/tensorflow/depreciated/toward-control/model.py
|
loopzxl/finch
|
bf2958c0f268575e5d51ad08fbc08b151cbea962
|
[
"MIT"
] | 1
|
2020-10-15T21:34:17.000Z
|
2020-10-15T21:34:17.000Z
|
from __future__ import print_function
from config import args
from utils import gumbel_softmax_sample, inverse_sigmoid
from modified_tf_classes import BasicDecoder, BeamSearchDecoder
import numpy as np
import tensorflow as tf
class Model:
def __init__(self, params):
self.params = params
self.scopes = {
'E': 'Encoder',
'D': 'Discriminator',
'G': 'Generator'}
self.build_placeholders()
self.build_global_helpers()
# initialize the base VAE by equation 4
self.build_train_vae_graph()
print("[1/5] VAE Graph Built")
# train the discriminator D by eqation 11
self.build_train_discriminator_graph()
print("[2/5] Discriminator Graph Built")
# train the generator by eqation 8 and encoder by equation 4
self.build_train_generator_encoder_graph()
print("[3/5] Generator and Encoder Graphs Built")
self.build_prior_inference_graph()
print("[4/5] Prior Inference Graph Built")
self.build_posterior_inference_graph()
print("[5/5] Posterior Inference Graph Built")
self.saver = tf.train.Saver()
self.model_path = './saved/model.ckpt'
def build_train_vae_graph(self):
z_mean, z_logvar = self.encoder(self.enc_inp)
z = self.reparam(z_mean, z_logvar)
latent_vec = tf.concat((z, self.draw_c_prior()), -1)
outputs = self.generator(latent_vec)
self.train_vae_nll_loss = self.seq_loss_fn(*outputs)
self.train_vae_kl_w = self.kl_w_fn()
self.train_vae_kl_loss = self.kl_loss_fn(z_mean, z_logvar)
loss_op = self.train_vae_nll_loss + self.train_vae_kl_w * self.train_vae_kl_loss
self.train_vae_op = self.optimizer.apply_gradients(
self.gradient_clipped(loss_op), global_step=self.global_step)
def build_train_discriminator_graph(self):
logits_real = self.discriminator(self.enc_inp, is_training=True)
self.train_clf_loss = self.sparse_cross_entropy_fn(logits_real, self.labels)
self.train_clf_acc = tf.reduce_mean(tf.to_float(tf.equal(tf.argmax(logits_real, 1), self.labels)))
c_prior = self.draw_c_prior()
latent_vec = tf.concat((self.draw_z_prior(), c_prior), -1)
_, logits_gen = self.generator(latent_vec, reuse=True)
ids_gen = tf.argmax(logits_gen[:, :-1, :], -1)
logits_fake = self.discriminator(ids_gen, reuse=True, refeed=True)
entropy = - tf.reduce_sum(tf.log(tf.nn.softmax(logits_fake)))
self.L_u = self.cross_entropy_fn(logits_fake, c_prior) + args.beta * entropy
loss_op = self.train_clf_loss + args.lambda_u * self.L_u
self.train_clf_op = self.optimizer.minimize(
loss_op, var_list=tf.trainable_variables(self.scopes['D']), global_step=self.global_step)
def build_train_generator_encoder_graph(self):
z_mean, z_logvar = self.encoder(self.enc_inp, reuse=True)
z = self.reparam(z_mean, z_logvar)
c = self.draw_c(self.discriminator(self.enc_inp, reuse=True))
latent_vec = tf.concat((z, c), -1)
outputs = self.generator(latent_vec, reuse=True)
self.train_ge_vae_nll_loss = self.seq_loss_fn(*outputs)
self.train_ge_vae_kl_w = self.kl_w_fn()
self.train_ge_vae_kl_loss = self.kl_loss_fn(z_mean, z_logvar)
vae_loss = self.train_ge_vae_nll_loss + self.train_ge_vae_kl_w * self.train_ge_vae_kl_loss
z_prior = self.draw_z_prior()
c_prior = self.draw_c_prior()
latent_vec = tf.concat((z_prior, c_prior), -1)
_, logits_gen = self.generator(latent_vec, reuse=True)
self.temperature = self.temperature_fn()
gumbel_softmax = gumbel_softmax_sample(logits_gen[:, :-1, :], self.temperature)
c_logits = self.discriminator(gumbel_softmax, reuse=True, refeed=True, gumbel=True)
self.l_attr_c = self.cross_entropy_fn(c_logits, c_prior)
z_mean_gen, z_logvar_gen = self.encoder(gumbel_softmax, reuse=True, gumbel=True)
self.l_attr_z = self.mutinfo_loss_fn(z_mean_gen, z_logvar_gen)
generator_loss_op = vae_loss + (args.lambda_c*self.l_attr_c) + (args.lambda_z*self.l_attr_z)
encoder_loss_op = vae_loss
self.train_generator_op = self.optimizer.apply_gradients(
self.gradient_clipped(generator_loss_op, scope=self.scopes['G']))
self.train_encoder_op = self.optimizer.apply_gradients(
self.gradient_clipped(encoder_loss_op, scope=self.scopes['E']))
def build_prior_inference_graph(self):
latent_vec = tf.concat((self.draw_z_prior(), self.draw_c_prior()), -1)
self.prior_gen_ids = self.generator(latent_vec, inference=True)
def build_posterior_inference_graph(self):
z_mean, z_logvar = self.encoder(self.enc_inp, reuse=True)
z = self.reparam(z_mean, z_logvar)
c_logits = self.discriminator(self.enc_inp, reuse=True)
latent_vec = tf.concat((z, self.draw_c(c_logits)), -1)
self.post_gen_ids = self.generator(latent_vec, inference=True)
c_reversed = self.draw_c(tf.log(1 - tf.nn.softmax(c_logits)))
latent_vec = tf.concat((z, c_reversed), -1)
self.post_reverse_gen_ids = self.generator(latent_vec, inference=True)
def encoder(self, inputs, reuse=None, gumbel=False):
with tf.variable_scope(self.scopes['E'], reuse=reuse):
embedding = tf.get_variable(
'embedding', [self.params['vocab_size'], args.embedding_dim], tf.float32)
if not gumbel:
x = tf.nn.embedding_lookup(embedding, inputs)
else:
x = tf.matmul(tf.reshape(inputs, [-1,self.params['vocab_size']]), embedding)
x = tf.reshape(x, [self.batch_size, args.max_len, args.embedding_dim])
_, (state_fw, state_bw) = tf.nn.bidirectional_dynamic_rnn(
cell_fw = self.rnn_cell(args.rnn_size//2, reuse=reuse),
cell_bw = self.rnn_cell(args.rnn_size//2, reuse=reuse),
inputs = x,
sequence_length = self.enc_seq_len,
dtype = tf.float32)
birnn_state = tf.concat((state_fw, state_bw), -1)
z_mean = tf.layers.dense(birnn_state, args.latent_size, reuse=reuse)
z_logvar = tf.layers.dense(birnn_state, args.latent_size, reuse=reuse)
return z_mean, z_logvar
def discriminator(self, inputs, reuse=None, refeed=False, gumbel=False, is_training=False):
with tf.variable_scope(self.scopes['D'], reuse=reuse):
embedding = tf.get_variable(
'embedding', [self.params['vocab_size'], args.embedding_dim], tf.float32)
if not gumbel:
x = tf.nn.embedding_lookup(embedding, inputs)
else:
x = tf.matmul(tf.reshape(inputs, [-1,self.params['vocab_size']]), embedding)
x = tf.reshape(x, [self.batch_size, args.max_len, args.embedding_dim])
x = tf.layers.dropout(x, args.cnn_dropout_rate, training=is_training)
multi_kernels = []
for i, k in enumerate([3, 4, 5]):
_x = tf.layers.conv1d(x, args.cnn_filters, k,
activation=tf.nn.elu, reuse=reuse, name='conv%d'%i)
seq_len = _x.get_shape().as_list()[1] if not refeed else (args.max_len - k + 1)
_x = tf.layers.max_pooling1d(_x, seq_len, 1)
_x = tf.reshape(_x, [self.batch_size, args.cnn_filters])
multi_kernels.append(_x)
x = tf.concat(multi_kernels, -1)
logits = tf.layers.dense(x, args.num_class, reuse=reuse)
return logits
def generator(self, latent_vec, reuse=None, inference=False):
with tf.variable_scope(self.scopes['E'], reuse=True):
embedding = tf.get_variable(
'embedding', [self.params['vocab_size'], args.embedding_dim])
if not inference:
with tf.variable_scope(self.scopes['G'], reuse=reuse):
init_state = tf.layers.dense(latent_vec, args.rnn_size, tf.nn.elu, reuse=reuse)
lin_proj = tf.layers.Dense(self.params['vocab_size'], _scope='decoder/dense', _reuse=reuse)
helper = tf.contrib.seq2seq.TrainingHelper(
inputs = tf.nn.embedding_lookup(embedding, self.dec_inp),
sequence_length = self.dec_seq_len)
decoder = BasicDecoder(
cell = self.rnn_cell(reuse=reuse),
helper = helper,
initial_state = init_state,
concat_z = latent_vec)
decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(
decoder = decoder)
return decoder_output.rnn_output, lin_proj.apply(decoder_output.rnn_output)
else:
with tf.variable_scope(self.scopes['G'], reuse=True):
init_state = tf.layers.dense(latent_vec, args.rnn_size, tf.nn.elu, reuse=True)
decoder = BeamSearchDecoder(
cell = self.rnn_cell(reuse=True),
embedding = embedding,
start_tokens = tf.tile(tf.constant([self.params['<start>']], dtype=tf.int32), [self.batch_size]),
end_token = self.params['<end>'],
initial_state = tf.contrib.seq2seq.tile_batch(init_state, args.beam_width),
beam_width = args.beam_width,
output_layer = tf.layers.Dense(self.params['vocab_size'], _reuse=True),
concat_z = tf.tile(tf.expand_dims(latent_vec, 1), [1, args.beam_width, 1]))
decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(
decoder = decoder,
maximum_iterations = 2 * tf.reduce_max(self.enc_seq_len))
return decoder_output.predicted_ids[:, :, 0]
def build_placeholders(self):
self.enc_inp = tf.placeholder(tf.int32, [None, args.max_len])
self.dec_inp = tf.placeholder(tf.int32, [None, args.max_len+1])
self.dec_out = tf.placeholder(tf.int32, [None, args.max_len+1])
self.labels = tf.placeholder(tf.int64, [None])
def build_global_helpers(self):
self.batch_size = tf.shape(self.enc_inp)[0]
self.enc_seq_len = tf.count_nonzero(self.enc_inp, 1, dtype=tf.int32)
self.dec_seq_len = self.enc_seq_len + 1
self.global_step = tf.Variable(0, trainable=False)
self.optimizer = tf.train.AdamOptimizer()
self.gaussian = tf.truncated_normal([self.batch_size, args.latent_size])
def draw_c_prior(self):
return tf.contrib.distributions.OneHotCategorical(
logits=tf.ones([self.batch_size, args.num_class]), dtype=tf.float32).sample()
def draw_c(self, logits):
return tf.contrib.distributions.OneHotCategorical(logits=logits, dtype=tf.float32).sample()
def draw_z_prior(self):
return self.gaussian
def reparam(self, z_mean, z_logvar):
return z_mean + tf.exp(0.5 * z_logvar) * self.draw_z_prior()
def gradient_clipped(self, loss_op, scope=None):
params = tf.trainable_variables(scope=scope)
gradients = tf.gradients(loss_op, params)
clipped_gradients, _ = tf.clip_by_global_norm(gradients, args.clip_norm)
return zip(clipped_gradients, params)
def seq_loss_fn(self, training_rnn_out, training_logits):
mask = tf.sequence_mask(
self.dec_seq_len, tf.reduce_max(self.dec_seq_len), dtype=tf.float32)
if args.num_sampled >= self.params['vocab_size']:
return tf.reduce_sum(tf.contrib.seq2seq.sequence_loss(
logits = training_logits,
targets = self.dec_out,
weights = mask,
average_across_timesteps = False,
average_across_batch = True))
else:
with tf.variable_scope('Generator/decoder/dense', reuse=True):
weights = tf.transpose(tf.get_variable('kernel'))
biases = tf.get_variable('bias')
return tf.reduce_sum(tf.reshape(mask,[-1]) * tf.nn.sampled_softmax_loss(
weights = weights,
biases = biases,
labels = tf.reshape(self.dec_out, [-1, 1]),
inputs = tf.reshape(training_rnn_out, [-1, args.rnn_size]),
num_sampled = args.num_sampled,
num_classes = self.params['vocab_size'],
)) / tf.to_float(self.batch_size)
def kl_w_fn(self):
return args.kl_anneal_max * tf.sigmoid((10 / args.kl_anneal_bias) * (
tf.to_float(self.global_step) - tf.constant(args.kl_anneal_bias / 2)))
def kl_loss_fn(self, mean, logvar):
return 0.5 * tf.reduce_sum(
tf.exp(logvar) + tf.square(mean) - 1 - logvar) / tf.to_float(self.batch_size)
def sparse_cross_entropy_fn(self, logits, labels):
return tf.reduce_sum(tf.nn.sparse_softmax_cross_entropy_with_logits(
logits=logits, labels=labels))
def cross_entropy_fn(self, logits, labels):
return tf.reduce_sum(tf.nn.softmax_cross_entropy_with_logits_v2(
logits=logits, labels=labels))
def temperature_fn(self):
return args.temperature_anneal_max * inverse_sigmoid((10 / args.temperature_anneal_bias) * (
tf.to_float(self.global_step - args.temperature_start_step) - tf.constant(
args.temperature_anneal_bias / 2)))
def mutinfo_loss_fn(self, z_mean_new, z_logvar_new, epsilon=tf.constant(1e-10)):
distribution = tf.contrib.distributions.MultivariateNormalDiag(
z_mean_new, tf.exp(z_logvar_new), validate_args=True)
mutinfo_loss = -tf.log(tf.add(epsilon, distribution.prob(self.draw_z_prior())))
return tf.reduce_sum(mutinfo_loss) / tf.to_float(self.batch_size)
def mse_fn(self, x1, x2):
return tf.reduce_sum(tf.squared_difference(x1, x2)) / tf.to_float(self.batch_size)
def rnn_cell(self, rnn_size=None, reuse=False):
rnn_size = args.rnn_size if rnn_size is None else rnn_size
return tf.nn.rnn_cell.GRUCell(rnn_size, kernel_initializer=tf.orthogonal_initializer(), reuse=reuse)
def get_new_w(self, w):
idx = self.params['word2idx'][w]
return idx if idx < self.params['vocab_size'] else self.params['word2idx']['<unk>']
def train_vae_session(self, sess, enc_inp, dec_inp, dec_out):
_, nll_loss, kl_w, kl_loss, step = sess.run(
[self.train_vae_op, self.train_vae_nll_loss, self.train_vae_kl_w, self.train_vae_kl_loss,
self.global_step],
{self.enc_inp: enc_inp, self.dec_inp: dec_inp, self.dec_out: dec_out})
return {'nll_loss': nll_loss, 'kl_w': kl_w, 'kl_loss': kl_loss, 'step': step}
def train_discriminator_session(self, sess, enc_inp, dec_inp, dec_out, labels):
_, loss, acc, L_u, step = sess.run(
[self.train_clf_op, self.train_clf_loss, self.train_clf_acc, self.L_u,
self.global_step],
{self.enc_inp: enc_inp, self.dec_inp: dec_inp, self.dec_out: dec_out, self.labels: labels})
return {'clf_loss': loss, 'clf_acc': acc, 'step': step,
'L_u': (args.lambda_u * L_u)}
def train_generator_session(self, sess, enc_inp, dec_inp, dec_out):
_, nll_loss, kl_w, kl_loss, step, temperature, l_attr_z, l_attr_c = sess.run(
[self.train_generator_op, self.train_ge_vae_nll_loss, self.train_ge_vae_kl_w,
self.train_ge_vae_kl_loss, self.global_step, self.temperature, self.l_attr_z, self.l_attr_c],
{self.enc_inp: enc_inp, self.dec_inp: dec_inp, self.dec_out: dec_out})
return {'nll_loss': nll_loss, 'kl_w': kl_w, 'kl_loss': kl_loss, 'step': step,
'temperature': temperature, 'l_attr_z': (args.lambda_z * l_attr_z),
'l_attr_c': (args.lambda_c * l_attr_c)}
def train_encoder_session(self, sess, enc_inp, dec_inp, dec_out):
_, nll_loss, kl_w, kl_loss, step = sess.run(
[self.train_encoder_op, self.train_ge_vae_nll_loss, self.train_ge_vae_kl_w,
self.train_ge_vae_kl_loss, self.global_step],
{self.enc_inp: enc_inp, self.dec_inp: dec_inp, self.dec_out: dec_out})
return {'nll_loss': nll_loss, 'kl_w': kl_w, 'kl_loss': kl_loss, 'step': step}
def prior_inference(self, sess):
predicted_ids = sess.run(self.prior_gen_ids, {self.batch_size: 1, self.enc_seq_len: [15]})[0]
print('G: %s' % ' '.join([self.params['idx2word'][idx] for idx in predicted_ids]))
print('-'*12)
def post_inference(self, sess, sentence):
print('I: %s' % sentence)
print()
sentence = [self.get_new_w(w) for w in sentence.split()][:args.max_len]
sentence = sentence + [self.params['word2idx']['<pad>']] * (args.max_len-len(sentence))
predicted_ids = sess.run(self.post_gen_ids, {self.enc_inp: np.atleast_2d(sentence)})[0]
print('O: %s' % ' '.join([self.params['idx2word'][idx] for idx in predicted_ids]))
print()
predicted_ids = sess.run(self.post_reverse_gen_ids, {self.enc_inp: np.atleast_2d(sentence)})[0]
print('R: %s' % ' '.join([self.params['idx2word'][idx] for idx in predicted_ids]))
print('-'*12)
| 46.255937
| 117
| 0.635959
|
540dd09db056c0d291e39a71ccb56bac257ae996
| 2,833
|
rb
|
Ruby
|
hbase-shell/src/test/ruby/shell/formatter_test.rb
|
jeffreyflukman/hbase
|
8bf966c8e936dec4d83bcbe85c5aab543f14a0df
|
[
"Apache-2.0"
] | 4,857
|
2015-01-02T11:45:14.000Z
|
2022-03-31T14:00:55.000Z
|
hbase-shell/src/test/ruby/shell/formatter_test.rb
|
jeffreyflukman/hbase
|
8bf966c8e936dec4d83bcbe85c5aab543f14a0df
|
[
"Apache-2.0"
] | 4,070
|
2015-05-01T02:52:57.000Z
|
2022-03-31T23:54:50.000Z
|
hbase-shell/src/test/ruby/shell/formatter_test.rb
|
jeffreyflukman/hbase
|
8bf966c8e936dec4d83bcbe85c5aab543f14a0df
|
[
"Apache-2.0"
] | 3,611
|
2015-01-02T11:33:55.000Z
|
2022-03-31T11:12:19.000Z
|
#
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'shell/formatter'
class ShellFormatterTest < Test::Unit::TestCase
# Helper method to construct a null formatter
def formatter
Shell::Formatter::Base.new(:output_stream => STDOUT)
end
#
# Constructor tests
#
define_test "Formatter constructor should not raise error valid IO streams" do
assert_nothing_raised do
Shell::Formatter::Base.new(:output_stream => STDOUT)
end
end
define_test "Formatter constructor should not raise error when no IO stream passed" do
assert_nothing_raised do
Shell::Formatter::Base.new()
end
end
define_test "Formatter constructor should raise error on non-IO streams" do
assert_raise TypeError do
Shell::Formatter::Base.new(:output_stream => 'foostring')
end
end
#-------------------------------------------------------------------------------------------------------
# Printing methods tests
# FIXME: The tests are just checking that the code has no typos, try to figure out a better way to test
#
define_test "Formatter#header should work" do
formatter.header(['a', 'b'])
formatter.header(['a', 'b'], [10, 20])
end
define_test "Formatter#row should work" do
formatter.row(['a', 'b'])
formatter.row(['xxxxxxxxx xxxxxxxxxxx xxxxxxxxxxx xxxxxxxxxxxx xxxxxxxxx xxxxxxxxxxxx xxxxxxxxxxxxxxx xxxxxxxxx xxxxxxxxxxxxxx'])
formatter.row(['yyyyyy yyyyyy yyyyy yyy', 'xxxxxxxxx xxxxxxxxxxx xxxxxxxxxxx xxxxxxxxxxxx xxxxxxxxx xxxxxxxxxxxx xxxxxxxxxxxxxxx xxxxxxxxx xxxxxxxxxxxxxx xxx xx x xx xxx xx xx xx x xx x x xxx x x xxx x x xx x x x x x x xx '])
formatter.row(["NAME => 'table1', FAMILIES => [{NAME => 'fam2', VERSIONS => 3, COMPRESSION => 'NONE', IN_MEMORY => false, BLOCKCACHE => false, LENGTH => 2147483647, TTL => FOREVER, BLOOMFILTER => NONE}, {NAME => 'fam1', VERSIONS => 3, COMPRESSION => 'NONE', IN_MEMORY => false, BLOCKCACHE => false, LENGTH => 2147483647, TTL => FOREVER, BLOOMFILTER => NONE}]"])
end
define_test "Froematter#footer should work" do
formatter.footer()
end
end
| 41.057971
| 365
| 0.699259
|
eb9bf684073ac683f1f26b728e631b5e9a3bb6c6
| 14,617
|
lua
|
Lua
|
2357532056/ui/Additions/TurnProcessing.lua
|
iElden/Civ6-MPH
|
f000db06d308101f0d090baa3a8e356c0cc8c813
|
[
"Apache-2.0"
] | 8
|
2020-09-13T22:35:31.000Z
|
2021-06-23T19:21:16.000Z
|
2357532056/ui/Additions/TurnProcessing.lua
|
iElden/Civ6-MPH
|
f000db06d308101f0d090baa3a8e356c0cc8c813
|
[
"Apache-2.0"
] | 6
|
2020-10-04T12:53:25.000Z
|
2022-01-18T12:59:06.000Z
|
2357532056/ui/Additions/TurnProcessing.lua
|
iElden/Civ6-MPH
|
f000db06d308101f0d090baa3a8e356c0cc8c813
|
[
"Apache-2.0"
] | 8
|
2020-10-04T12:54:28.000Z
|
2021-06-23T00:26:56.000Z
|
-- Copyright 2016-2019, Firaxis Games
-- (Multiplayer) Turn Processing By D. / Jack The Narrator
print("MPH Turn Processing")
include( "Civ6Common" );
include( "Colors") ;
include( "SupportFunctions" ); --DarkenLightenColor
include( "InputSupport" );
include( "InstanceManager" );
-- ===========================================================================
-- Variables
-- ===========================================================================
local m_isRetired : boolean = false;
local m_isClosing : boolean = false;
local g_timeshift = 0
local g_currenttimer = 0
local g_playertime = {}
local b_settimer = false
local b_setprocess = false
-- ===========================================================================
-- Timing Function
-- ===========================================================================
function Refresh_Data()
g_playertime = {}
if GameConfiguration.IsNetworkMultiplayer() ~= true or GameConfiguration.GetValue("CPL_SYNCTURN") ~= true or GameConfiguration.GetValue("CPL_SMARTTIMER") == 1 then
return
end
local localID = Network.GetLocalPlayerID()
local hostID = Network.GetGameHostPlayerID()
local player_ids = GameConfiguration.GetMultiplayerPlayerIDs()
for i, iPlayer in ipairs(player_ids) do
if PlayerConfigurations[iPlayer]:GetLeaderTypeName() ~= "LEADER_SPECTATOR"
and Players[iPlayer]:IsAlive() then
local tmp = {id = iPlayer, turn_length = 60, lag = 0, last = 0, status = 0, t_0 = 0, t_1 = 0, t_start = 0, t_end = 0}
table.insert(g_playertime,tmp)
end
end
end
function CheckReady()
if g_playertime == nil then
return false
end
local bready = true
for i, Player in ipairs(g_playertime) do
if Player.id ~= nil and Players[Player.id] ~= nil then
if Player.status ~= 1 and (Players[Player.id]:IsHuman() == true )then
bready = false
end
end
end
return bready
end
function RefreshStatus()
if g_playertime == nil then
return
end
local text = ""
for i, Player in ipairs(g_playertime) do
if Player.id ~= nil then
local name = ""
if Players[Player.id]:IsHuman() then
name = PlayerConfigurations[Player.id]:GetPlayerName()
else
name = "AI #"..Player.id
end
if name ~= nil then
name = Locale.Lookup(name)
else
name = "Player #"..Player.id
end
text = text..name.." - "
if Player.status ~= 1 then
text = text.." [COLOR_Civ6Red]PROCESSING[ENDCOLOR][NEWLINE]"
else
text = text.." [COLOR_Civ6Green]READY[ENDCOLOR][NEWLINE]"
end
end
end
Controls.Player_Status:SetText(text)
end
function SmartTimer()
-- 0: Competitive
-- 1: None
-- 2: Lege
-- 3: S1AL
-- 4: Sephis
if GameConfiguration.GetValue("CPL_SMARTTIMER") == 1 then
return
end
local tot_cities = 0
local tot_units = 0
local tot_humans = 0
local b_war = false
local currentTurn = Game.GetCurrentGameTurn()
for i = 0, PlayerManager.GetWasEverAliveMajorsCount() -1 do
if Players[i]:IsAlive() == true then
if Players[i]:IsHuman() == true then
tot_humans = tot_humans + 1
tot_cities = tot_cities + Players[i]:GetCities():GetCount()
tot_units = tot_units + Players[i]:GetUnits():GetCount()
if Players[i]:GetDiplomacy():IsAtWarWithHumans() == true then
b_war = true
end
end
end
end
local avg_cities = 0
local avg_units = 0
if tot_humans > 0 then
avg_cities = math.floor( tot_cities / tot_humans )
avg_units = math.floor( tot_units / tot_humans )
end
local timer = 0
if GameConfiguration.GetValue("CPL_SMARTTIMER") == 0 then
timer = 30 + avg_cities * 4 + avg_units * 1 + g_timeshift
if currentTurn > 5 and currentTurn < 11 then
timer = timer + 5
end
if currentTurn > 10 and currentTurn < 21 then
timer = timer + 15
end
if currentTurn > 20 and currentTurn < 31 then
timer = timer + 35
end
if currentTurn > 30 and currentTurn < 51 then
timer = timer + 40
end
if currentTurn > 50 and currentTurn < 76 then
timer = timer + 45
end
if currentTurn > 75 and currentTurn < 101 then
timer = timer + 50
end
if currentTurn > 100 then
timer = timer + 55
end
if b_teamer == true then
if GameConfiguration.GetValue("CPL_BAN_FORMAT") ~= 3 then
print("More time: Teamer!")
timer = math.floor(timer * 1.1)
end
end
if b_war == true then
if GameConfiguration.GetValue("CPL_BAN_FORMAT") ~= 3 then
print("More time: War!")
timer = math.floor(timer * 1.15)
else
print("More time: War!")
timer = math.floor(timer * 1.05)
end
end
end
if GameConfiguration.GetValue("CPL_SMARTTIMER") == 2 then
if currentTurn < 16 then
timer = 15 + g_timeshift
end
if currentTurn > 15 and currentTurn < 71 then
timer = 45 + g_timeshift
end
if currentTurn > 70 then
timer = 75 + g_timeshift
end
end
if GameConfiguration.GetValue("CPL_SMARTTIMER") == 3 then
timer = 65 + avg_cities * 4 + avg_units * 1 + g_timeshift
if currentTurn > -1 and currentTurn < 10 then
timer = timer - 15
end
if currentTurn > 44 and currentTurn < 90 then
timer = timer + 15
end
if currentTurn > 89 then
timer = timer + 30
end
end
if GameConfiguration.GetValue("CPL_SMARTTIMER") == 5 then
timer = 95 + avg_cities * 4 + avg_units * 1 + g_timeshift
if currentTurn > -1 and currentTurn < 10 then
timer = timer - 25
end
if currentTurn > 44 and currentTurn < 90 then
timer = timer + 30
end
if currentTurn > 89 then
timer = timer + 20
end
end
if GameConfiguration.GetValue("CPL_SMARTTIMER") == 4 then
timer = 30 + currentTurn + g_timeshift
end
local turnSegment = Game.GetCurrentTurnSegment();
if GameConfiguration.GetValue("CPL_SMARTTIMER") ~= 1 then
if turnSegment == WORLD_CONGRESS_STAGE_1 then
timer = 240
elseif turnSegment == WORLD_CONGRESS_STAGE_2 then
timer = 240
end
end
g_currenttimer = timer
end
-- ===========================================================================
-- NEW EVENTS
-- ===========================================================================
function OnLoadScreenClose()
Refresh_Data()
SmartTimer()
end
function OnTurnEnd(turn)
SmartTimer()
if GameConfiguration.GetValue("CPL_SMARTTIMER") ~= 1 then
if (g_currenttimer ~= nil) then
GameConfiguration.SetValue("TURN_TIMER_TIME", g_currenttimer)
GameConfiguration.SetTurnTimerType("TURNTIMER_STANDARD")
end
end
if GameConfiguration.IsNetworkMultiplayer() ~= true or GameConfiguration.GetValue("CPL_SYNCTURN") ~= true or GameConfiguration.GetValue("CPL_SMARTTIMER") == 1 then
return
end
for i, Player in ipairs(g_playertime) do
if Player.id ~= nil then
if Players[Player.id]:IsAlive() == false then
Player.id = nil
end
Player.status = 0
Player.t_end = os.time()
end
end
b_settimer = false
Events.GameCoreEventPublishComplete.Add(OnTick)
RefreshStatus()
end
-- End
function OnLocalPlayerTurnEnd(playerID)
if GameConfiguration.IsNetworkMultiplayer() ~= true or GameConfiguration.GetValue("CPL_SYNCTURN") ~= true or GameConfiguration.GetValue("CPL_SMARTTIMER") == 1 then
return
end
local localID = Network.GetLocalPlayerID()
for i, Player in ipairs(g_playertime) do
if localID == Player.id then
Player.t_1 = os.time()
Player.last = Player.t_1 - Player.t_0
end
end
end
function OnRemotePlayerTurnEnd(playerID)
if GameConfiguration.IsNetworkMultiplayer() ~= true or GameConfiguration.GetValue("CPL_SYNCTURN") ~= true or GameConfiguration.GetValue("CPL_SMARTTIMER") == 1 then
return
end
for i, Player in ipairs(g_playertime) do
if playerID == Player.id then
Player.t_1 = os.time()
end
end
end
-- Start
function OnRemotePlayerTurnBegin(playerID)
if GameConfiguration.IsNetworkMultiplayer() ~= true or GameConfiguration.GetValue("CPL_SYNCTURN") ~= true or GameConfiguration.GetValue("CPL_SMARTTIMER") == 1 then
return
end
for i, Player in ipairs(g_playertime) do
if playerID == Player.id then
Player.status = 1
Player.t_0 = os.time()
end
end
RefreshStatus()
end
function OnLocalPlayerTurnBegin()
local localID = Network.GetLocalPlayerID()
for i, Player in ipairs(g_playertime) do
if localID == Player.id then
Player.status = 1
Player.t_0 = os.time()
end
end
RefreshStatus()
end
-----------------------------------------------------------------------------------------------
function OnTick()
if GameConfiguration.IsNetworkMultiplayer() ~= true or GameConfiguration.GetValue("CPL_SYNCTURN") ~= true or GameConfiguration.GetValue("CPL_SMARTTIMER") == 1 then
Events.GameCoreEventPublishComplete.Remove(OnTick)
return
end
local localID = Network.GetLocalPlayerID()
local hostID = Network.GetGameHostPlayerID()
if CheckReady() == false then
if( b_setprocess == false ) then
GameConfiguration.SetValue("TURN_TIMER_TIME", 60)
LuaEvents.InGame_OpenTurnProcessing()
b_setprocess = true
end
return
else
if b_settimer == false then
SmartTimer()
if GameConfiguration.GetValue("CPL_SMARTTIMER") ~= 1 then
if (g_currenttimer ~= nil) then
GameConfiguration.SetValue("TURN_TIMER_TIME", g_currenttimer)
GameConfiguration.SetTurnTimerType("TURNTIMER_STANDARD")
LuaEvents.InGame_CloseTurnProcessing()
b_setprocess = false
end
end
b_settimer = true
Events.GameCoreEventPublishComplete.Remove(OnTick)
end
end
end
function OnAdjustTime(time_value:number)
g_timeshift = time_value
SmartTimer()
if (g_currenttimer ~= nil) then
GameConfiguration.SetValue("TURN_TIMER_TIME", g_currenttimer)
GameConfiguration.SetTurnTimerType("TURNTIMER_STANDARD")
end
end
-- ===========================================================================
-- Screen Handling
-- ===========================================================================
-- ===========================================================================
function KeyHandler( key:number )
local bHandled:boolean = false;
if key == Keys.U then
if (not ContextPtr:IsHidden() ) then
Close();
end
bHandled = true;
end
return bHandled;
end
-- ===========================================================================
-- If this is receiving input (e.g., is visible) then do not let any input
-- fall past it. Forge will send input to popups and children first before
-- this context gets a crack at it.
-- ===========================================================================
function OnInput( pInputStruct:table )
local uiMsg:number = pInputStruct:GetMessageType();
local key:number = pInputStruct:GetKey();
if uiMsg == KeyEvents.KeyUp then
return KeyHandler( pInputStruct:GetKey() );
elseif uiMsg == KeyEvents.KeyDown and not (key == Keys.VK_ALT or key == Keys.VK_CONTROL or key == Keys.VK_SHIFT) then
-- Don't consume Alt, Control, or Shift so those can be used for keybindings
return true;
end
return false;
end
-- ===========================================================================
-- Callback
-- ===========================================================================
-- ===========================================================================
-- Raised (typically) from InGame since when this is hidden it will not
-- receive input from ForgeUI.
-- ===========================================================================
function OnShow()
if m_isClosing then
print("Show was requested on menu that is in the midst of closing.");
return;
end
-- Stop any particle effects from drawing on top of the menu.
EffectsManager:PauseAllEffects();
Controls.AlphaIn:SetToBeginning();
Controls.AlphaIn:Play();
end
function OnOpen()
local turn = "Turn #"..Game.GetCurrentGameTurn()
Controls.Processing_Text_Number:SetText(turn)
-- Don't show pause menu if the player has retired (forfeit) from the game - fixes TTP 20129
if not ContextPtr:IsHidden() then
UI.PlaySound("UI_Screen_Close");
end
if not m_isRetired then
UI.PlaySound("Play_UI_Click");
ContextPtr:SetHide(false);
end
end
-- ===========================================================================
function Close()
if(m_isClosing) then
print("Menu is already closing.");
return;
end
m_isClosing = true;
EffectsManager:ResumeAllEffects(); -- Resume any continous particle effects.
if(Controls.AlphaIn:IsStopped()) then
-- Animation is good for a nice clean animation out..
Controls.AlphaIn:Reverse();
else
-- Animation is not in an expected state, just reset all...
Controls.AlphaIn:SetToBeginning();
ShutdownAfterClose();
UI.DataError("Forced closed() of the in game top options menu. (Okay if someone was spamming ESC.)");
end
CloseImmediately()
end
function CloseImmediately()
ContextPtr:SetHide(true);
m_isClosing = false;
end
-- ===========================================================================
function ShutdownAfterClose()
print("ShutdownAfterClose()")
m_isClosing = false;
ContextPtr:SetHide(true);
end
-- ===========================================================================
-- Dervive off this in a MOD file for adding additional functionality
-- ===========================================================================
function LateInitialize()
end
-- ===========================================================================
function OnInit( isReload:boolean )
LateInitialize();
if isReload then
if not ContextPtr:IsHidden() then
OnShow();
end
end
end
function OnShutdown()
LuaEvents.InGame_OpenTurnProcessing.Remove( OnOpen );
LuaEvents.InGame_CloseTurnProcessing.Remove( Close );
LuaEvents.UITimeAdjust.Remove( OnAdjustTime )
Events.LocalPlayerTurnBegin.Remove( OnLocalPlayerTurnBegin )
Events.RemotePlayerTurnBegin.Remove( OnRemotePlayerTurnBegin )
Events.RemotePlayerTurnEnd.Remove( OnRemotePlayerTurnEnd );
Events.LocalPlayerTurnEnd.Remove(OnLocalPlayerTurnEnd );
Events.TurnEnd.Remove(OnTurnEnd)
Events.LoadScreenClose.Remove(OnLoadScreenClose);
end
-- ===========================================================================
function Initialize()
Refresh_Data()
SmartTimer()
ContextPtr:SetInitHandler( OnInit );
ContextPtr:SetInputHandler( OnInput, true );
ContextPtr:SetShowHandler( OnShow );
ContextPtr:SetShutdown( OnShutdown );
LuaEvents.InGame_OpenTurnProcessing.Add( OnOpen );
LuaEvents.InGame_CloseTurnProcessing.Add( Close );
LuaEvents.UITimeAdjust.Add( OnAdjustTime )
Events.LocalPlayerTurnBegin.Add( OnLocalPlayerTurnBegin )
Events.RemotePlayerTurnBegin.Add( OnRemotePlayerTurnBegin )
Events.RemotePlayerTurnEnd.Add( OnRemotePlayerTurnEnd );
Events.LocalPlayerTurnEnd.Add(OnLocalPlayerTurnEnd );
Events.TurnEnd.Add(OnTurnEnd)
Events.LoadScreenClose.Add(OnLoadScreenClose);
end
Initialize();
| 26.384477
| 165
| 0.640145
|
32cb38e68b8b2a7c0c4e7219b5e036c7656721bb
| 1,242
|
lua
|
Lua
|
prototypes/styles/style-label.lua
|
Pouka-dev/FactorioStorageEnergistics
|
138f7f64e197e3539dd7c4031b0b8527917f79d3
|
[
"MIT"
] | 2
|
2021-09-03T22:47:21.000Z
|
2022-01-03T16:43:53.000Z
|
prototypes/styles/style-label.lua
|
Pouka-dev/re_storage_energistics
|
138f7f64e197e3539dd7c4031b0b8527917f79d3
|
[
"MIT"
] | 2
|
2021-09-05T13:07:32.000Z
|
2021-09-12T15:41:19.000Z
|
prototypes/styles/style-label.lua
|
Pouka-dev/re_storage_energistics
|
138f7f64e197e3539dd7c4031b0b8527917f79d3
|
[
"MIT"
] | null | null | null |
-- Description: GUI styles Frame
local default_gui = data.raw["gui-style"].default
local shadowColor = {r = 0.2, g = 0.2, b = 0.25}
-------------------------------------------------------------------------------
-- Style label
--
-- @type Label
--
-------------------------------------------------------------------------------
-- Style of default
--
-- @field [parent=#Label] default
default_gui[Constants.Names.Styles.Labels.SEItemTableItemLabel] = {
type = "label_style",
parent = "label",
font = "default-semibold"
}
default_gui[Constants.Names.Styles.Labels.SEElecticUsageLabelTL] = {
type = "label_style",
parent = "electric_usage_label",
top_padding = 14 - 1,
left_padding = 0,
font = "default-small-bold",
font_color = shadowColor
}
default_gui[Constants.Names.Styles.Labels.SEElecticUsageLabelBR] = {
type = "label_style",
parent = "electric_usage_label",
top_padding = 14 + 1,
left_padding = 2,
font = "default-small-bold",
font_color = shadowColor
}
default_gui[Constants.Names.Styles.Labels.SEElecticUsageLabelCount] = {
type = "label_style",
parent = "electric_usage_label",
top_padding = 14,
left_padding = 1,
font = "default-small-bold",
font_color = {r = 1, g = 1, b = 1}
}
| 23.884615
| 79
| 0.599839
|
e41d0fb7de606e1ef6eeaa4282c140c450304212
| 560
|
lua
|
Lua
|
plugins/cwweapons/items/attachments/sh_saigafh.lua
|
LtTaylor97/taylors-ix-plugins
|
72a7471218c3aa1d3bdfddcf67df942a8e413b7f
|
[
"MIT"
] | 1
|
2022-02-26T18:03:51.000Z
|
2022-02-26T18:03:51.000Z
|
plugins/cwweapons/items/attachments/sh_saigafh.lua
|
LtTaylor97/taylors-ix-plugins
|
72a7471218c3aa1d3bdfddcf67df942a8e413b7f
|
[
"MIT"
] | null | null | null |
plugins/cwweapons/items/attachments/sh_saigafh.lua
|
LtTaylor97/taylors-ix-plugins
|
72a7471218c3aa1d3bdfddcf67df942a8e413b7f
|
[
"MIT"
] | null | null | null |
ITEM.name = "Saiga-12 Flash Hider"
ITEM.description = "A Flash Hider explicitly made for the Saiga-12 Shotgun"
ITEM.category = "Attachments"
ITEM.model = "models/Items/BoxSRounds.mdl"
ITEM.width = 1
ITEM.height = 1
ITEM.slot = 2
ITEM.weight = 1
ITEM.price = 7000
ITEM.isAttachment = true
ITEM.attSearch = { "kk_ins2_flashhider_big_shotgun", }
-- Slot Numbers Defined:
-- Sights = 1
-- Barrels = 2
-- Lasers/Lights = 3
-- Magazines = 4
-- Underbarrel = 5
-- Additional slots can be added so long as they line up with the SWEP's attachment code appropriately.
| 26.666667
| 103
| 0.728571
|
cda23f4d616b35c974964e73fe0ffc0c2d56de87
| 2,718
|
cs
|
C#
|
CityWeather/CityWeather/Rain.cs
|
Winterpuma/bmstu_CG_CP
|
ae39406f11eeedf0de418b215f96c3514d361bb1
|
[
"MIT"
] | 6
|
2020-04-17T16:10:31.000Z
|
2021-12-07T09:48:27.000Z
|
CityWeather/CityWeather/Rain.cs
|
Winterpuma/bmstu_CG_CP
|
ae39406f11eeedf0de418b215f96c3514d361bb1
|
[
"MIT"
] | null | null | null |
CityWeather/CityWeather/Rain.cs
|
Winterpuma/bmstu_CG_CP
|
ae39406f11eeedf0de418b215f96c3514d361bb1
|
[
"MIT"
] | null | null | null |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
namespace CityWeather
{
class Drop
{
int x, y, z;
public Drop(int x, int y, int z)
{
this.x = x;
this.y = y;
this.z = z;
}
public void Update(int dx, int dy, int dz)
{
x += dx;
y += dy;
z += dz;
}
public void Draw(Graphics g, Pen pen, int dx, int dy)
{
g.DrawLine(pen, x, y, x + dx, y + dy);
}
public int GetDepth()
{
return z;
}
public bool IsVisible(int maxZ)
{
if (z > maxZ)
return true;
return false;
}
public bool IsNextVisible(int maxZ, int dz)
{
if ((z + dz) > maxZ)
return true;
return false;
}
public Point GetPoint()
{
return new Point(x, y);
}
public Point GetNextPoint(int dx, int dy)
{
return new Point(x + dx, y + dy);
}
public static bool IsBelow(Drop d)
{
if (d.y > 1000)
return true;
return false;
}
}
class ParticleSystem
{
List<Drop> system;
Vector direction;
int xMax, yMax;
static Random rnd = new Random();
public ParticleSystem(int width, int height, Vector dir, int intensity)
{
system = new List<Drop>();
direction = dir;
xMax = width;
yMax = height;
InitParticles(intensity);
}
public void InitParticles(int intensity)
{
for (int i = 0; i < intensity; i++)
system.Add(new Drop(rnd.Next(-400, xMax + 400), 0, 700)); // не 700!
}
private void UpdateParticles()
{
foreach (Drop drop in system)
{
drop.Update((int)direction.x, (int)direction.y, (int)direction.z);
}
system.RemoveAll(Drop.IsBelow);
}
public void DrawParticles(Graphics g, Pen pen)
{
foreach (Drop drop in system)
{
drop.Draw(g, pen, (int)direction.x, (int)direction.y);
}
}
public void ProcessSystem(Graphics g, Pen pen)
{
DrawParticles(g, pen);
UpdateParticles();
}
public bool IsEmpty() // Эффективно ли?
{
return (system.Count == 0);
}
}
}
| 21.919355
| 84
| 0.449595
|
6648880b686684a717ab3e20c6da1b424b2d8cf0
| 1,720
|
py
|
Python
|
BD_usuariosCadastrados.py
|
MathewsJosh/Python-Chat
|
6f9c2e18282cb887651ccb614ae43bdaf443f6df
|
[
"MIT"
] | null | null | null |
BD_usuariosCadastrados.py
|
MathewsJosh/Python-Chat
|
6f9c2e18282cb887651ccb614ae43bdaf443f6df
|
[
"MIT"
] | null | null | null |
BD_usuariosCadastrados.py
|
MathewsJosh/Python-Chat
|
6f9c2e18282cb887651ccb614ae43bdaf443f6df
|
[
"MIT"
] | null | null | null |
import sqlite3
import os.path
# Deleta o arquivo de dados de chat se o mesmo existir
os.remove("Bancos de dados/usuariosCadastrados.db")
# Variavel global
caminho = "Bancos de dados/usuariosCadastrados.db"
# Verifica se o arquivo usuariosCadastrados existe
existe = os.path.exists(caminho)
# Cria o arquivo
connection = sqlite3.connect(caminho)
# Navega pelo arquivo
c = connection.cursor()
# Método de criação da tabela do banco de dados
def criar_tabela():
c.execute(
"""CREATE TABLE IF NOT EXISTS dados (
nome text,
senha text,
UNIQUE(nome)
)""")
# Método auxiliarde entrada de dados e criação de tabela
def entradaauxiliar():
criar_tabela()
c.execute("INSERT OR IGNORE INTO dados (nome, senha) VALUES ('admin', 'admin')")
c.execute("INSERT OR IGNORE INTO dados (nome, senha) VALUES ('adm', 'adm')")
connection.commit()
# Método de entrada dos dados do usuário para o cadastramento
def entradaDados(nome, senha):
criar_tabela()
c.execute("INSERT OR IGNORE INTO dados (nome, senha) VALUES ('admin', 'admin')")
c.execute("INSERT OR IGNORE INTO dados (nome, senha) VALUES ('adm', 'adm')")
c.execute("INSERT OR REPLACE INTO dados (nome, senha) VALUES ('"+nome+"','"+senha+"')")
connection.commit()
# Método que retorna o nome e senha do usuário cadastrado
def leDados(nome,senha):
entradaauxiliar()
sql = 'SELECT * FROM dados WHERE nome=? and senha=?'
for linha in c.execute(sql, (nome,senha,)):
if linha == "":
return False
else:
return True
# Método que fecha a conexão com o banco de dados(nunca usado)
def fechaConexao():
c.close()
connection.close()
| 30.175439
| 91
| 0.668605
|
e9a3d3798ce6900bf86b29f5cff7de13d2d12041
| 1,672
|
dart
|
Dart
|
lib/data/repositories/expense_repository.dart
|
Sheikhsoft/flutter-mobile
|
dab704b49fe0f096a95f0bf81300ba31b7ea8128
|
[
"AAL"
] | 1
|
2019-10-05T21:28:09.000Z
|
2019-10-05T21:28:09.000Z
|
lib/data/repositories/expense_repository.dart
|
Sheikhsoft/flutter-mobile
|
dab704b49fe0f096a95f0bf81300ba31b7ea8128
|
[
"AAL"
] | null | null | null |
lib/data/repositories/expense_repository.dart
|
Sheikhsoft/flutter-mobile
|
dab704b49fe0f096a95f0bf81300ba31b7ea8128
|
[
"AAL"
] | null | null | null |
import 'dart:async';
import 'dart:convert';
import 'dart:core';
import 'package:invoiceninja_flutter/data/models/serializers.dart';
import 'package:built_collection/built_collection.dart';
import 'package:invoiceninja_flutter/redux/auth/auth_state.dart';
import 'package:invoiceninja_flutter/data/models/models.dart';
import 'package:invoiceninja_flutter/data/web_client.dart';
class ExpenseRepository {
const ExpenseRepository({
this.webClient = const WebClient(),
});
final WebClient webClient;
Future<BuiltList<ExpenseEntity>> loadList(
CompanyEntity company, AuthState auth) async {
final dynamic response =
await webClient.get(auth.url + '/expenses?per_page=500', company.token);
final ExpenseListResponse expenseResponse =
serializers.deserializeWith(ExpenseListResponse.serializer, response);
return expenseResponse.data;
}
Future<ExpenseEntity> saveData(
CompanyEntity company, AuthState auth, ExpenseEntity expense,
[EntityAction action]) async {
final data = serializers.serializeWith(ExpenseEntity.serializer, expense);
dynamic response;
if (expense.isNew) {
response = await webClient.post(
auth.url + '/expenses', company.token, json.encode(data));
} else {
var url = auth.url + '/expenses/' + expense.id.toString();
if (action != null) {
url += '?action=' + action.toString();
}
response = await webClient.put(url, company.token, json.encode(data));
}
final ExpenseItemResponse expenseResponse =
serializers.deserializeWith(ExpenseItemResponse.serializer, response);
return expenseResponse.data;
}
}
| 32.153846
| 80
| 0.719498
|
3842d7d83c87499a0d03d6ce5479273aa22e625c
| 8,601
|
php
|
PHP
|
vcard.php
|
juliensnz/Rglsit
|
937be83a9bc2a179a4802532b8866178d09b1326
|
[
"Apache-2.0"
] | 1
|
2016-06-08T11:56:48.000Z
|
2016-06-08T11:56:48.000Z
|
vcard.php
|
juliensnz/Rglsit
|
937be83a9bc2a179a4802532b8866178d09b1326
|
[
"Apache-2.0"
] | null | null | null |
vcard.php
|
juliensnz/Rglsit
|
937be83a9bc2a179a4802532b8866178d09b1326
|
[
"Apache-2.0"
] | null | null | null |
<?php
function type($line)
{
$size = strlen($line);
$cpt = 0;
while(($car = $line[$cpt]) != ":" && $cpt < $size)
{
$type .= $car;
$cpt++;
}
if($cpt != $size)
{
return utf8_decode($type);
}
else
{
return NULL;
}
}
function primaryType($line)
{
$size = strlen($line);
$cpt = 0;
while(($car = $line[$cpt]) != ":" && $car != ";" && $cpt < $size)
{
if($car == ".")
{
$type = "";
}
else
{
$type .= $car;
}
$cpt++;
}
if($cpt != $size)
{
return utf8_decode($type);
}
else
{
return NULL;
}
}
function getNextValue($line)
{
$size = strlen($line);
$cpt = 0;
while(($car = $line[$cpt]) != ";" && $cpt < $size)
{
$value .= $car;
$cpt++;
}
$value = trim($value);
//echo "Value : \"".$value."\"";
if($value != "" && $value != NULL && $value != EOL)
{
return utf8_decode($value);
}
else
{
return NULL;
}
}
function getNom($line)
{
//N:Sanchez;Julien;;;
$position = 0;
$size = strlen($line);
while($position < $size)
{
$value = getNextValue(substr($line,$position));
$position += strlen($value)+1;
if($value != NULL)
{
$values[] = $value;
}
}
$result = array (
'familyname' => $values[0],
'firstname' => $values[1]);
return $result;
}
function getTitre($line)
{
//FN:Julien Sanchez
$result = array (
'name' => trim($line)
);
return $result;
}
function getOrg($line)
{
//ORG:Reglisse;
$line = trim($line);
$position = 0;
$size = strlen($line);
while($position < $size)
{
$value = getNextValue(substr($line,$position));
if($value != NULL)
{
$result = array (
'org' => substr(trim($line),$position,$size-1)
);
return $result;
}
$position += strlen($value)+1;
}
return NULL;
}
function getMail($line)
{
$size = strlen($type);
$type = type($line);
$position = strlen($type);
$mail = getNextValue(substr($line,$position+1));
$position = 0;
$size = strlen($type);
while($position < $size)
{
$value = getNextValue(substr($type,$position));
$position += strlen($value)+1;
if($value != NULL)
{
if($value == "type=WORK")
{
$mailType = "WORK";
}
else if($value == "type=HOME")
{
$mailType = "HOME";
}
if(!isset($mailType))
{
$mailType = "OTHER";
}
}
}
$result = array (
'type' => $mailType,
'mail' => $mail);
return $result;
}
function getUrl($line)
{
//item5.URL;type=pref:http\://erambert.me
$size = strlen($line);
$type = type($line);
$position = strlen($type);
$url = getNextValue(substr($line,$position+1));
return $url;
}
function getTel($line)
{
//TEL;type=CELL;type=pref:06 22 71 23 15
$size = strlen($line);
$type = type($line);
$position = strlen($type);
$tel = getNextValue(substr($line,$position+1));
$position = 0;
$size = strlen($type);
while($position < $size)
{
$value = getNextValue(substr($type,$position));
$position += strlen($value)+1;
//echo primaryType($value);
if($value != NULL)
{
if($value == "type=WORK")
{
$telType = "WORK";
}
else if($value == "type=HOME")
{
$telType = "HOME";
}
else if($value == "type=CELL")
{
$telType = "CELL";
}
if(!isset($telType))
{
$telType = "OTHER";
}
}
}
$result = array (
'type' => $telType,
'tel' => $tel);
return $result;
}
function getAdr($line)
{
$size = strlen($line);
$type = type($line);
$position = strlen($type)+1;
while($position < $size)
{
$value = getNextValue(substr($line,$position));
$position += strlen($value)+1;
if($value != NULL)
{
$adr .= $value." ";
}
}
$position = 0;
$size = strlen($type);
while($position < $size)
{
$value = getNextValue(substr($type,$position));
$position += strlen($value)+1;
if($value != NULL)
{
if($value == "type=WORK")
{
$adrType = "WORK";
}
else if($value == "type=HOME")
{
$adrType = "HOME";
}
if(!isset($adrType))
{
$adrType = "OTHER";
}
}
}
$result = array (
'type' => $adrType,
'adr' => $adr);
return $result;
}
function getImg($file)
{
$img = "";
while(primaryType($data = fgets($file)) == NULL)
{
$img .= trim($data);
}
return $img;
}
function displayImg($img)
{
echo '<img class="photo" src="data:image/gif;base64,' . $img .'" />';
}
function displayArray($array)
{
foreach($array as $cle => $value)
{
if(getType($value) != "array")
{
echo $value." ";
}
else
{
displayArray($value);
}
}
echo "<br/>";
}
function parseVCard($path)
{
if($vcard = fopen($path, 'r'))
{
if(($data = trim(fgets($vcard))) == "BEGIN:VCARD" || $data == "begin:vcard")
{
// fgets($vcard);
while(!feof($vcard))
{
$data = fgets($vcard);
switch (primaryType($data))
{
case "N":
$name = getNom(substr($data,2));
//displayArray($name);
break;
case "FN":
$title = getTitre(substr($data,3));
//displayArray($title);
break;
case "NICKNAME":
$nickname = getTitre(substr($data,9));
//displayArray($title);
break;
case "ORG":
$org = getOrg(substr($data,4));
//displayArray($org);
break;
case "URL":
$url[] = getUrl(substr($data,0));
//displayArray($url);
break;
case "EMAIL":
$mail[] = getMail(substr($data,6));
//displayArray($mail);
break;
case "TEL":
$tel[] = getTel(substr($data,4));
//displayArray($tel);
break;
case "ADR":
$adr[] = getAdr($data);
//displayArray($adr[0]);
break;
case "PHOTO":
$photo = getImg($vcard);
//displayImg($photo);
break;
case "n":
$name = getNom(substr($data,2));
//displayArray($name);
break;
case "fn":
$title = getTitre(substr($data,3));
//displayArray($title);
break;
case "nickname":
$nickname = getTitre(substr($data,9));
//displayArray($title);
break;
case "org":
$org = getOrg(substr($data,4));
//displayArray($org);
break;
case "url":
$url[] = getUrl(substr($data,0));
//displayArray($url);
break;
case "email":
$mail[] = getMail(substr($data,6));
//displayArray($mail);
break;
case "tel":
$tel[] = getTel(substr($data,4));
//displayArray($tel);
break;
case "adr":
$adr[] = getAdr($data);
//displayArray($adr[0]);
break;
case "photo":
$photo = getImg($vcard);
//displayImg($photo);
break;
default:
break;
}
}
?>
<table class="vcard">
<tr class="resume">
<td class="avatar"><?php displayImg($photo); ?></td>
<td class="infos">
<span class="fn"><?php echo $name['firstname'];?> <?php echo $name['familyname']; ?></span><br/>
<?php echo $org['org']; ?><br/>
<?php
foreach($url as $element)
{
echo '<a href="'.stripslashes($element).'">'.stripslashes($element)."</a><br/>";
}
?>
</td>
</tr>
<tr>
<td colspan="2">
<?php
foreach($adr as $element)
{
echo '<span class="label">Adresse : </span><span class="adr" type="home">'.stripslashes($element['adr'])."</span><br/>";
}
?>
</td>
</tr>
<tr rowspan="2">
<td class="tel">
<?php
foreach($tel as $element)
{
if($element['type'] == "WORK")
{
echo '<span class="label">Travail : ';
}
else if($element['type'] == 'HOME')
{
echo '<span class="label">Domicile : ';
}
else if($element['type'] == 'CELL')
{
echo '<span class="label">Portable : ';
}
else if($element['type'] == 'OTHER')
{
echo '<span class="label">Tel : ';
}
echo "</span>".$element['tel']."<br/>";
}
?>
</td>
<td>
<?php
foreach($mail as $element)
{
if($element['type'] == "WORK")
{
echo '<span class="label">Travail : ';
}
else if($element['type'] == "HOME")
{
echo '<span class="label">Perso : ';
}
else if($element['type'] == "OTHER")
{
echo '<span class="label">Mail : ';
}
echo '</span><span class="email">'.$element['mail']."</span><br/>";
}
?>
</td>
</tr>
</table>
<?php
}
}
}
$url = (isset($_GET['url']) && $_GET['url'] != "") ? $_GET['url'] : ((isset($_POST['url']) && $_POST['url'] != "") ? $_POST['url'] : NULL);
parseVCard("./files/".$url);
?>
| 17.236473
| 139
| 0.497965
|
a63630cd75d77773e744bebc6747f8f97b88f40b
| 57
|
sh
|
Shell
|
randomCircuit/graphing/strongScaling30QubitArcus/genPDFs.sh
|
aniabrown/QuEST_Performance_v2.1.0
|
4c566b2a8dba3b4eb2e176e5a93b219f24ad5048
|
[
"MIT"
] | null | null | null |
randomCircuit/graphing/strongScaling30QubitArcus/genPDFs.sh
|
aniabrown/QuEST_Performance_v2.1.0
|
4c566b2a8dba3b4eb2e176e5a93b219f24ad5048
|
[
"MIT"
] | null | null | null |
randomCircuit/graphing/strongScaling30QubitArcus/genPDFs.sh
|
aniabrown/QuEST_Performance_v2.1.0
|
4c566b2a8dba3b4eb2e176e5a93b219f24ad5048
|
[
"MIT"
] | null | null | null |
pdflatex --jobname=arcus_30qubit_strongScaling graph.tex
| 28.5
| 56
| 0.877193
|
3f708e2c44bfae0bd5bb25ece24fd734faeaec19
| 3,519
|
php
|
PHP
|
resources/views/admin/dosen/create.blade.php
|
coderey-tf/webkom
|
e4df42e35e79d5de6798bde2ac5823bd798c0f27
|
[
"MIT"
] | null | null | null |
resources/views/admin/dosen/create.blade.php
|
coderey-tf/webkom
|
e4df42e35e79d5de6798bde2ac5823bd798c0f27
|
[
"MIT"
] | null | null | null |
resources/views/admin/dosen/create.blade.php
|
coderey-tf/webkom
|
e4df42e35e79d5de6798bde2ac5823bd798c0f27
|
[
"MIT"
] | null | null | null |
@extends("admin.layouts.main")
@section('content')
<form method="POST" action="{{ route('admin.dosen.store') }}"
enctype="multipart/form-data"
class="p-3 md:p-10 bg-white rounded shadow-md w-full">
@csrf
<div class="mb-6">
<label class="block text-sm text-gray-700" for="nama">Nama</label>
<input
class="w-full px-5 py-1 text-gray-800 bg-gray-100 rounded outline-none border-2 focus:border-gray-800
@error('nama') border-red-500 @enderror"
id="nama" name="nama" type="text" placeholder="Nama Dosen"
aria-label="nama" value="{{ old('nama') }}">
@error('nama')
<span class="text-xs font-bold text-red-500">{{ $message }}</span>
@enderror
</div>
<div class="mb-6">
<label class="block text-sm text-gray-700" for="matakuliah_id">
Matakuliah <span class="text-xs text-gray-500">(Boleh Kosong)</span>
</label>
<select
class="w-full px-5 py-1 text-gray-800 bg-gray-100 rounded outline-none border-2
focus:border-gray-800 @error('matakuliah_id') border-red-500 @enderror"
name="matakuliah_id[]" id="matakuliah_id" multiple>
<option value=""> -- Pilih Matakuliah -- </option>
@foreach ($listMatakuliah as $matakuliah)
@if (in_array($matakuliah->id, old('matakuliah_id', [])))
<option value="{{ $matakuliah->id }}" selected>
{{ $matakuliah->nama }}
</option>
@else
<option value="{{ $matakuliah->id }}">
{{ $matakuliah->nama }}
</option>
@endif
@endforeach
</select>
@error('matakuliah_id')
<span class="text-xs font-bold text-red-500">{{ $message }}</span>
@enderror
</div>
<div class="mb-6">
<label class="block text-sm text-gray-700" for="matakuliah_id">
NIP <span class="text-xs text-gray-500">(Boleh Kosong)</span>
</label>
<input
class="w-full px-5 py-1 text-gray-800 bg-gray-100 rounded outline-none border-2 focus:border-gray-800
@error('nip') border-red-500 @enderror"
id="nip" name="nip" type="text" placeholder="NIP Dosen" aria-label="NIP"
value="{{ old('nip') }}">
@error('nip')
<span class="text-xs font-bold text-red-500">{{ $message }}</span>
@enderror
</div>
<div class="mb-6">
<label class="block text-sm text-gray-700" for="foto">Foto</label>
<div class="w-24 mb-1">
<div class="aspect-h-4 aspect-w-3 hidden img-container">
<img
class="img-preview border border-gray-700 mb-2 object-center object-cover">
</div>
</div>
<input onchange="previewImg()"
class="img-input w-full px-0 py-1 text-gray-800 bg-gray-100 rounded outline-none border-2 border-gray-200 focus:border-gray-800 @error("
foto") border-red-500 @enderror" id="foto" name="foto" type="file">
@error('foto')
<span class="text-xs font-bold text-red-500">{{ $message }}</span>
@enderror
</div>
<div class="flex gap-3">
<button
class="px-4 py-1 text-white font-light tracking-wider bg-blue-600 hover:bg-blue-500 rounded outline-none"
type="submit">Tambah Data</button>
<a href="{{ route('admin.dosen.index') }}"
class="px-4 py-1 text-white font-light tracking-wider bg-gray-700 hover:bg-gray-600 rounded">Batal</a>
</div>
</form>
@endsection
@section('script')
<script src="{{ asset('js/imagePreview.js') }}"></script>
@endsection
| 38.67033
| 144
| 0.595908
|
46379a4c5005739f29f1acca63122f26630bf608
| 813
|
php
|
PHP
|
app/Http/Controllers/CategoryController.php
|
zilackteam/api.system.music
|
962832732c9a19ea8a5aaf3a94cbdbe009e91f0d
|
[
"MIT"
] | null | null | null |
app/Http/Controllers/CategoryController.php
|
zilackteam/api.system.music
|
962832732c9a19ea8a5aaf3a94cbdbe009e91f0d
|
[
"MIT"
] | null | null | null |
app/Http/Controllers/CategoryController.php
|
zilackteam/api.system.music
|
962832732c9a19ea8a5aaf3a94cbdbe009e91f0d
|
[
"MIT"
] | null | null | null |
<?php
namespace App\Http\Controllers;
use App\Models\Category;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
class CategoryController extends Controller {
public function index(Request $request) {
try {
if ($request->has('type')) {
$categories = Category::query();
$categories->where('type', $request->get('type'));
$categories->orderBy('is_feature', 'desc');
$data = $categories->get();
return $this->responseSuccess($data);
}
} catch (\Exception $e) {
return $this->responseErrorByException($e);
}
}
}
| 26.225806
| 66
| 0.533825
|
c2b1e04f7927b7328ad41b30b773c20f94bb66c9
| 6,012
|
c
|
C
|
openbsd/sys/arch/luna88k/luna88k/locore_c_routines.c
|
MarginC/kame
|
2ef74fe29e4cca9b4a87a1d5041191a9e2e8be30
|
[
"BSD-3-Clause"
] | 91
|
2015-01-05T15:18:31.000Z
|
2022-03-11T16:43:28.000Z
|
openbsd/sys/arch/luna88k/luna88k/locore_c_routines.c
|
MarginC/kame
|
2ef74fe29e4cca9b4a87a1d5041191a9e2e8be30
|
[
"BSD-3-Clause"
] | 1
|
2016-02-25T15:57:55.000Z
|
2016-02-25T16:01:02.000Z
|
openbsd/sys/arch/luna88k/luna88k/locore_c_routines.c
|
MarginC/kame
|
2ef74fe29e4cca9b4a87a1d5041191a9e2e8be30
|
[
"BSD-3-Clause"
] | 21
|
2015-02-07T08:23:07.000Z
|
2021-12-14T06:01:49.000Z
|
/* $OpenBSD: locore_c_routines.c,v 1.3 2004/08/01 17:18:05 miod Exp $ */
/*
* Mach Operating System
* Copyright (c) 1993-1991 Carnegie Mellon University
* Copyright (c) 1991 OMRON Corporation
* All Rights Reserved.
*
* Permission to use, copy, modify and distribute this software and its
* documentation is hereby granted, provided that both the copyright
* notice and this permission notice appear in all copies of the
* software, derivative works or modified versions, and any portions
* thereof, and that both notices appear in supporting documentation.
*
* CARNEGIE MELLON AND OMRON ALLOW FREE USE OF THIS SOFTWARE IN ITS "AS IS"
* CONDITION. CARNEGIE MELLON AND OMRON DISCLAIM ANY LIABILITY OF ANY KIND
* FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
*
* Carnegie Mellon requests users of this software to return to
*
* Software Distribution Coordinator or Software.Distribution@CS.CMU.EDU
* School of Computer Science
* Carnegie Mellon University
* Pittsburgh PA 15213-3890
*
* any improvements or extensions that they make and grant Carnegie the
* rights to redistribute these changes.
*/
#include <sys/param.h>
#include <sys/systm.h>
#include <machine/board.h> /* m188 bit defines */
#include <machine/cmmu.h> /* DMT_VALID */
#include <machine/asm.h> /* END_OF_VECTOR_LIST, etc. */
#include <machine/asm_macro.h> /* enable/disable interrupts */
#include <machine/cpu_number.h> /* cpu_number() */
#include <machine/locore.h>
#include <machine/trap.h>
typedef struct {
unsigned word_one, word_two;
} m88k_exception_vector_area;
extern unsigned int *volatile int_mask_reg[MAX_CPUS]; /* in machdep.c */
extern unsigned master_cpu; /* in cmmu.c */
void setlevel(unsigned int);
void vector_init(m88k_exception_vector_area *, unsigned *);
#define SIGSYS_MAX 501
#define SIGTRAP_MAX 510
#define EMPTY_BR 0xc0000000 /* empty "br" instruction */
#define NO_OP 0xf4005800 /* "or r0, r0, r0" */
#define BRANCH(FROM, TO) \
(EMPTY_BR | ((unsigned)(TO) - (unsigned)(FROM)) >> 2)
#define SET_VECTOR(NUM, VALUE) \
do { \
vector[NUM].word_one = NO_OP; \
vector[NUM].word_two = BRANCH(&vector[NUM].word_two, VALUE); \
} while (0)
/*
* vector_init(vector, vector_init_list)
*
* This routine sets up the m88k vector table for the running processor.
* It is called with a very little stack, and interrupts disabled,
* so don't call any other functions!
* XXX clean this - nivas
*/
void
vector_init(m88k_exception_vector_area *vector, unsigned *vector_init_list)
{
unsigned num;
unsigned vec;
extern void bugtrap(void);
extern void m88110_bugtrap(void);
for (num = 0; (vec = vector_init_list[num]) != END_OF_VECTOR_LIST;
num++) {
if (vec != UNKNOWN_HANDLER)
SET_VECTOR(num, vec);
}
for (; num <= SIGSYS_MAX; num++)
SET_VECTOR(num, sigsys);
for (; num <= SIGTRAP_MAX; num++)
SET_VECTOR(num, sigtrap);
SET_VECTOR(450, syscall_handler);
SET_VECTOR(504, stepbpt);
SET_VECTOR(511, userbpt);
/* GCC will by default produce explicit trap 503 for division by zero */
SET_VECTOR(503, vector_init_list[T_ZERODIV]);
}
unsigned int luna88k_curspl[MAX_CPUS] = {0, 0, 0, 0};
unsigned int int_mask_val[INT_LEVEL] = {
INT_MASK_LV0,
INT_MASK_LV1,
INT_MASK_LV2,
INT_MASK_LV3,
INT_MASK_LV4,
INT_MASK_LV5,
INT_MASK_LV6,
INT_MASK_LV7
};
unsigned int int_set_val[INT_LEVEL] = {
INT_SET_LV0,
INT_SET_LV1,
INT_SET_LV2,
INT_SET_LV3,
INT_SET_LV4,
INT_SET_LV5,
INT_SET_LV6,
INT_SET_LV7
};
/*
* return next safe spl to reenable interrupts.
*/
unsigned int
safe_level(mask, curlevel)
unsigned mask;
unsigned curlevel;
{
int i;
for (i = curlevel; i < 8; i++)
if (!(int_mask_val[i] & mask))
return i;
panic("safe_level: no safe level for mask 0x%08x level %d found",
mask, curlevel);
/* NOTREACHED */
}
void
setlevel(unsigned int level)
{
unsigned int set_value;
int cpu = cpu_number();
set_value = int_set_val[level];
if (cpu != master_cpu)
set_value &= INT_SLAVE_MASK;
#if 0
set_value &= ISR_SOFTINT_EXCEPT_MASK(cpu);
set_value &= ~blocked_interrupts_mask;
#endif
*int_mask_reg[cpu] = set_value;
#if 0
int_mask_shadow[cpu] = set_value;
#endif
luna88k_curspl[cpu] = level;
}
unsigned
getipl(void)
{
unsigned curspl;
m88k_psr_type psr; /* processor status register */
psr = disable_interrupts_return_psr();
curspl = luna88k_curspl[cpu_number()];
set_psr(psr);
return curspl;
}
unsigned
setipl(unsigned level)
{
unsigned curspl;
m88k_psr_type psr; /* processor status register */
#ifdef DEBUG
if (level > 7) {
printf("setipl: invoked with invalid level %x\n", level);
level &= 0x07; /* and pray it will work */
}
#endif
psr = disable_interrupts_return_psr();
curspl = luna88k_curspl[cpu_number()];
setlevel(level);
flush_pipeline();
/* The flush pipeline is required to make sure the above write gets
* through the data pipe and to the hardware; otherwise, the next
* bunch of instructions could execute at the wrong spl protection
*/
set_psr(psr);
return curspl;
}
unsigned
raiseipl(unsigned level)
{
unsigned curspl;
m88k_psr_type psr; /* processor status register */
#ifdef DEBUG
if (level > 7) {
printf("raiseipl: invoked with invalid level %x\n", level);
level &= 0x07; /* and pray it will work */
}
#endif
psr = disable_interrupts_return_psr();
curspl = luna88k_curspl[cpu_number()];
if (curspl < level)
setlevel(level);
flush_pipeline();
/* The flush pipeline is required to make sure the above write gets
* through the data pipe and to the hardware; otherwise, the next
* bunch of instructions could execute at the wrong spl protection
*/
set_psr(psr);
return curspl;
}
/* XXX Utterly bogus */
#if NCPUS > 1
#include <sys/simplelock.h>
void
simple_lock_init(lkp)
struct simplelock *volatile lkp;
{
lkp->lock_data = 0;
}
int
test_and_set(lock)
int *volatile lock;
{
#if 0
int oldlock = *lock;
if (*lock == 0) {
*lock = 1;
return 0;
}
#else
return *lock;
*lock = 1;
return 0;
#endif
}
#endif
| 23.034483
| 75
| 0.715902
|
2e546f7db3faf4d860dbeddb65792446c4623ff2
| 3,344
|
swift
|
Swift
|
Example/Tests/AIUIKit+String.swift
|
adrianilie9/AIUIKit
|
672024f048972153d46abafe10c699d201c13050
|
[
"MIT"
] | null | null | null |
Example/Tests/AIUIKit+String.swift
|
adrianilie9/AIUIKit
|
672024f048972153d46abafe10c699d201c13050
|
[
"MIT"
] | null | null | null |
Example/Tests/AIUIKit+String.swift
|
adrianilie9/AIUIKit
|
672024f048972153d46abafe10c699d201c13050
|
[
"MIT"
] | null | null | null |
import XCTest
@testable import AIUIKit
class AIUIKit_String: XCTestCase {
func testHtmlFiltering() {
XCTAssertTrue(
"Test <strong>bold</strong> string.".htmlTagsFiltered() == "Test bold string."
)
XCTAssertTrue(
"Test <script type=\"text/javascript\">var x = 21;</script> JavaScript.".htmlTagsFiltered() == "Test var x = 21; JavaScript."
)
}
func testTrim() {
XCTAssert(
"The quick brown fox jumps over the lazy dog".trimToLength(length: 5) == "The q"
)
XCTAssert(
"The quick brown fox jumps over the lazy dog".trimToLength(length: 10) == "The quick"
)
}
func testVisible() {
guard let font = UIFont(name: "AppleSDGothicNeo-Regular", size: 20.0) else {
XCTAssert(false, "Font \"AppleSDGothicNeo-Regular\" not available on test target.")
return
}
XCTAssert(
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. In quis tortor sed risus scelerisque eleifend eu nec eros. Proin eu nunc finibus, dapibus justo sagittis, venenatis magna. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Interdum et malesuada fames ac ante ipsum primis in faucibus. Aliquam maximus nulla a purus fermentum tempus. Quisque aliquam sagittis odio et mattis. Aenean nec sollicitudin erat. In tempus justo lorem, a efficitur magna sollicitudin sed. Praesent ac placerat lectus. Nunc vel mauris fermentum, ullamcorper nibh sed, dictum tortor. Mauris ultricies pretium erat, et ultrices odio suscipit sit amet. Nulla eleifend augue id lacus vehicula iaculis. Sed lobortis tellus ac eros elementum, eget porta sem dictum. Vivamus aliquam a tortor eu euismod."
.visible(inSize: CGSize(width: 320.0, height: 120.0), withFont: font)
==
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. In quis tortor sed risus scelerisque eleifend eu nec eros. Proin eu nunc finibus, dapibus justo sagittis, venenatis magn"
)
}
func testHeight() {
guard let font = UIFont(name: "AppleSDGothicNeo-Regular", size: 20.0) else {
XCTAssert(false, "Font \"AppleSDGothicNeo-Regular\" not available on test target.")
return
}
XCTAssert(
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. In quis tortor sed risus scelerisque eleifend eu nec eros. Proin eu nunc finibus, dapibus justo sagittis, venenatis magna. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Interdum et malesuada fames ac ante ipsum primis in faucibus. Aliquam maximus nulla a purus fermentum tempus. Quisque aliquam sagittis odio et mattis. Aenean nec sollicitudin erat. In tempus justo lorem, a efficitur magna sollicitudin sed. Praesent ac placerat lectus. Nunc vel mauris fermentum, ullamcorper nibh sed, dictum tortor. Mauris ultricies pretium erat, et ultrices odio suscipit sit amet. Nulla eleifend augue id lacus vehicula iaculis. Sed lobortis tellus ac eros elementum, eget porta sem dictum. Vivamus aliquam a tortor eu euismod."
.requiredHeightToDisplay(forWidth: 320.0, withFont: font)
==
CGFloat(552.0)
)
}
}
| 61.925926
| 828
| 0.686902
|
84928cd43859211ae4ee36e671e82fb2c07c3754
| 512
|
cs
|
C#
|
srcs/ServerApi/Base/API.cs
|
LeversonCarlos/FriendlyCashFlow
|
d50cabcfe31da4d0f7b31197e5d381b94c6f6fd3
|
[
"MIT"
] | 1
|
2020-03-29T17:41:01.000Z
|
2020-03-29T17:41:01.000Z
|
srcs/ServerApi/Base/API.cs
|
LeversonCarlos/FriendlyCashFlow
|
d50cabcfe31da4d0f7b31197e5d381b94c6f6fd3
|
[
"MIT"
] | 112
|
2020-03-19T11:18:04.000Z
|
2022-02-26T23:09:01.000Z
|
srcs/ServerApi/Base/API.cs
|
LeversonCarlos/FriendlyCashFlow
|
d50cabcfe31da4d0f7b31197e5d381b94c6f6fd3
|
[
"MIT"
] | 1
|
2021-03-15T17:38:03.000Z
|
2021-03-15T17:38:03.000Z
|
using System;
using System.Diagnostics;
using Microsoft.AspNetCore.Mvc;
namespace FriendlyCashFlow.API.Base
{
public partial class BaseController : ControllerBase
{
protected readonly IServiceProvider serviceProvider;
public BaseController(IServiceProvider _serviceProvider)
{
this.serviceProvider = _serviceProvider;
}
[DebuggerStepThrough]
protected T GetService<T>() where T : class
{ return (T)this.serviceProvider.GetService(typeof(T)); }
}
}
| 23.272727
| 63
| 0.716797
|
a036af3d9137eb85cf300e9bbca8ef695369ee46
| 1,968
|
swift
|
Swift
|
Sources/TuistLoader/Models+ManifestMappers/Settings+ManifestMapper.swift
|
freak4pc/tuist
|
a20d44aaa9e9c5ede250f93a3f1e256ef8dad193
|
[
"MIT"
] | null | null | null |
Sources/TuistLoader/Models+ManifestMappers/Settings+ManifestMapper.swift
|
freak4pc/tuist
|
a20d44aaa9e9c5ede250f93a3f1e256ef8dad193
|
[
"MIT"
] | 264
|
2021-04-01T19:50:06.000Z
|
2022-03-28T11:44:05.000Z
|
Sources/TuistLoader/Models+ManifestMappers/Settings+ManifestMapper.swift
|
freak4pc/tuist
|
a20d44aaa9e9c5ede250f93a3f1e256ef8dad193
|
[
"MIT"
] | null | null | null |
import Foundation
import ProjectDescription
import TSCBasic
import TuistCore
import TuistGraph
extension TuistGraph.Settings {
typealias BuildConfigurationTuple = (TuistGraph.BuildConfiguration, TuistGraph.Configuration?)
/// Maps a ProjectDescription.Settings instance into a TuistCore.Settings instance.
/// - Parameters:
/// - manifest: Manifest representation of the settings.
/// - generatorPaths: Generator paths.
static func from(manifest: ProjectDescription.Settings, generatorPaths: GeneratorPaths) throws -> TuistGraph.Settings {
let base = manifest.base.mapValues(TuistGraph.SettingValue.from)
let configurations = try manifest.configurations
.reduce([TuistGraph.BuildConfiguration: TuistGraph.Configuration?]()) { acc, val in
var result = acc
let variant = TuistGraph.BuildConfiguration.from(manifest: val)
result[variant] = try TuistGraph.Configuration.from(manifest: val.configuration, generatorPaths: generatorPaths)
return result
}
let defaultSettings = TuistGraph.DefaultSettings.from(manifest: manifest.defaultSettings)
return TuistGraph.Settings(
base: base,
configurations: configurations,
defaultSettings: defaultSettings
)
}
private static func buildConfigurationTuple(from customConfiguration: CustomConfiguration,
path _: AbsolutePath,
generatorPaths: GeneratorPaths) throws -> BuildConfigurationTuple
{
let buildConfiguration = TuistGraph.BuildConfiguration.from(manifest: customConfiguration)
let configuration = try customConfiguration.configuration.flatMap {
try TuistGraph.Configuration.from(manifest: $0, generatorPaths: generatorPaths)
}
return (buildConfiguration, configuration)
}
}
| 46.857143
| 128
| 0.682927
|
38dcaee166ae8b56d5e588903457ad4242d9df25
| 1,527
|
php
|
PHP
|
src/GoogleDriveStorageProvider.php
|
commnerd/LaravelGoogleDriveStorageAdapter
|
85aede3f46da9b9df5a913b7c64ec9250216a8f1
|
[
"Unlicense"
] | null | null | null |
src/GoogleDriveStorageProvider.php
|
commnerd/LaravelGoogleDriveStorageAdapter
|
85aede3f46da9b9df5a913b7c64ec9250216a8f1
|
[
"Unlicense"
] | null | null | null |
src/GoogleDriveStorageProvider.php
|
commnerd/LaravelGoogleDriveStorageAdapter
|
85aede3f46da9b9df5a913b7c64ec9250216a8f1
|
[
"Unlicense"
] | null | null | null |
<?php
namespace GoogleDriveStorage;
use Illuminate\Support\ServiceProvider;
use Illuminate\Config\Repository as Config;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Route;
class GoogleDriveStorageProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot(Config $config)
{
$this->publishes([
__DIR__.'/../config/storage_google_drive.php' => config_path('storage_google_drive.php'),
], 'config');
$config["filesystems.disks.google_drive"] = include __DIR__."/../configs/storage_google_drive.php";
if($config["filesystems.disks.google_drive.force_default"]) {
$config["filesystems.default"] = "google_drive";
if(is_link(public_path("storage"))) {
unlink(public_path("storage"));
}
}
$client = new GoogleClient;
$service = new GoogleDriveService($client);
$storageAdapter = new GoogleDriveStorageAdapter($service, $config["filesystems.disks.google_drive"]);
Storage::extend('google_drive', function () use ($storageAdapter) {
return $storageAdapter;
});
Route::get('/storage/{path}', function(string $path) {
$data = Storage::get($path);
$finfo = new \finfo(FILEINFO_MIME);
return response($data)
->header("Content-Type", $finfo->buffer($data));
})->where('path', '.*');
}
}
| 30.54
| 109
| 0.617551
|
46eadb703c8a458f192dbb234130f8a2b55bea35
| 140
|
py
|
Python
|
ai/predict/urls.py
|
thdwlsgus0/relay_15
|
b5cb66ca250afd5402b0f19c870fda1852b77a28
|
[
"MIT"
] | 3
|
2020-08-07T05:35:28.000Z
|
2020-08-10T00:48:11.000Z
|
ai/predict/urls.py
|
thdwlsgus0/relay_15
|
b5cb66ca250afd5402b0f19c870fda1852b77a28
|
[
"MIT"
] | null | null | null |
ai/predict/urls.py
|
thdwlsgus0/relay_15
|
b5cb66ca250afd5402b0f19c870fda1852b77a28
|
[
"MIT"
] | 11
|
2020-07-28T00:45:51.000Z
|
2020-11-22T18:34:52.000Z
|
from django.urls import path
from . import views
app_name = 'predict'
urlpatterns = [
path('predict/', views.PredictView.as_view()),
]
| 17.5
| 50
| 0.707143
|
6b1de6573b419e7afb5f5f1dcc1be452a7193069
| 166
|
js
|
JavaScript
|
src/filters/json/json.js
|
fossabot/uniapp-scaffold
|
c47ef8756a9a84bcecf627356c0eebb08eceec9b
|
[
"MIT"
] | 16
|
2019-11-12T13:09:06.000Z
|
2021-09-17T07:37:38.000Z
|
src/filters/json/json.js
|
fossabot/uniapp-scaffold
|
c47ef8756a9a84bcecf627356c0eebb08eceec9b
|
[
"MIT"
] | 7
|
2019-11-13T07:48:41.000Z
|
2022-02-18T14:28:17.000Z
|
src/filters/json/json.js
|
fossabot/uniapp-scaffold
|
c47ef8756a9a84bcecf627356c0eebb08eceec9b
|
[
"MIT"
] | 3
|
2019-11-12T13:34:50.000Z
|
2019-12-26T16:23:09.000Z
|
const name = 'json';
const fn = value => JSON.stringify(value, null, 2);
const filter = {
install(Vue) {
Vue.filter(name, fn);
},
};
export default filter;
| 15.090909
| 51
| 0.620482
|
a76ac6ab7631c4204a2d12d80fb48aee05810557
| 271
|
swift
|
Swift
|
Infra/Sources/Api/Api.swift
|
usk-sample/MultiTargetSPMSample
|
44dcc8cae732c4c750a5433a46c502923da00141
|
[
"MIT"
] | null | null | null |
Infra/Sources/Api/Api.swift
|
usk-sample/MultiTargetSPMSample
|
44dcc8cae732c4c750a5433a46c502923da00141
|
[
"MIT"
] | null | null | null |
Infra/Sources/Api/Api.swift
|
usk-sample/MultiTargetSPMSample
|
44dcc8cae732c4c750a5433a46c502923da00141
|
[
"MIT"
] | null | null | null |
//
// Api.swift
//
//
// Created by Yusuke Hasegawa on 2022/01/12.
//
import Foundation
import Alamofire
public class Api {
public init() {
}
}
extension Api {
public func request() -> Int {
return Int.random(in: 0...100)
}
}
| 11.782609
| 45
| 0.549815
|
a3087a43a04178af14783f841b97ecb4c9a4c43c
| 156
|
ts
|
TypeScript
|
front-end/src/app/models/category.model.ts
|
hoangphuong020193/library
|
87f707891c4121a1c41f2e5238be262493923a71
|
[
"MIT"
] | null | null | null |
front-end/src/app/models/category.model.ts
|
hoangphuong020193/library
|
87f707891c4121a1c41f2e5238be262493923a71
|
[
"MIT"
] | null | null | null |
front-end/src/app/models/category.model.ts
|
hoangphuong020193/library
|
87f707891c4121a1c41f2e5238be262493923a71
|
[
"MIT"
] | 1
|
2018-03-24T11:29:56.000Z
|
2018-03-24T11:29:56.000Z
|
export class Category {
public id: number;
public type: string;
public categoryName: string = 'Danh mục';
public enabled: boolean = true;
}
| 22.285714
| 45
| 0.666667
|
7f4c492c1b22324331e734a6d61b0922c171a18b
| 1,957
|
php
|
PHP
|
console/migrations/m130524_201442_init.php
|
Chernovm/sky-coding-test
|
267ac84d3aad9681a8aa1aeacb2378c1a7c5ccff
|
[
"BSD-3-Clause"
] | null | null | null |
console/migrations/m130524_201442_init.php
|
Chernovm/sky-coding-test
|
267ac84d3aad9681a8aa1aeacb2378c1a7c5ccff
|
[
"BSD-3-Clause"
] | null | null | null |
console/migrations/m130524_201442_init.php
|
Chernovm/sky-coding-test
|
267ac84d3aad9681a8aa1aeacb2378c1a7c5ccff
|
[
"BSD-3-Clause"
] | null | null | null |
<?php
use yii\db\Migration;
class m130524_201442_init extends Migration
{
public function up()
{
$tableOptions = null;
if ($this->db->driverName === 'mysql') {
// http://stackoverflow.com/questions/766809/whats-the-difference-between-utf8-general-ci-and-utf8-unicode-ci
$tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB';
}
$this->createTable('{{%user}}', [
'id' => $this->primaryKey(),
'username' => $this->string()->notNull()->unique(),
'auth_key' => $this->string(32)->notNull(),
'password_hash' => $this->string()->notNull(),
'password_reset_token' => $this->string()->unique(),
'email' => $this->string()->notNull()->unique(),
'status' => $this->smallInteger()->notNull()->defaultValue(10),
'created_at' => $this->integer()->notNull(),
'updated_at' => $this->integer()->notNull(),
], $tableOptions);
// Create sky_user table
$this->createTable('{{%sky_user}}', [
'id' => $this->primaryKey(),
'firstname' => $this->string()->notNull(),
'lastname' => $this->string()->notNull(),
'patronymic' => $this->string()->notNull(),
'email' => $this->string()->notNull()->unique(),
'legal_body' => $this->boolean()->notNull(),
'private_enterpreneur' => $this->boolean()->notNull(),
'tax_number' => $this->string(),
'company_name' => $this->string(),
], $tableOptions);
// Create unique constraint for sky_user's multiple columns
$this->createIndex('idx_unique_full_name',
'{{%sky_user}}',
['firstname', 'lastname', 'patronymic'],
true);
}
public function down()
{
$this->dropTable('{{%user}}');
$this->dropTable('{{%sky_user}}');
}
}
| 35.581818
| 121
| 0.524783
|
e109de1433566e44cf4eb393ba33c69f48ab892b
| 1,806
|
rb
|
Ruby
|
lib/rubocop_challenger/rubocop/todo_reader.rb
|
shunsugai/rubocop_challenger
|
29baac07d894379fb81f6c874b6754705691bd25
|
[
"MIT"
] | 32
|
2018-10-19T08:51:07.000Z
|
2022-03-10T13:08:16.000Z
|
lib/rubocop_challenger/rubocop/todo_reader.rb
|
shunsugai/rubocop_challenger
|
29baac07d894379fb81f6c874b6754705691bd25
|
[
"MIT"
] | 418
|
2018-10-20T16:14:52.000Z
|
2022-03-22T23:31:27.000Z
|
lib/rubocop_challenger/rubocop/todo_reader.rb
|
shunsugai/rubocop_challenger
|
29baac07d894379fb81f6c874b6754705691bd25
|
[
"MIT"
] | 1
|
2019-08-02T03:51:21.000Z
|
2019-08-02T03:51:21.000Z
|
# frozen_string_literal: true
module RubocopChallenger
module Rubocop
# To read `.rubocop_todo.yml` and parse each rules
class TodoReader
def initialize(rubocop_todo_file_path)
@rubocop_todo_file_path = rubocop_todo_file_path
end
# Returns the version of RuboCop used to create the ".rubocop_todo.yml"
#
# @return [Type] the RuboCop version
def version
file_contents =~ /using RuboCop version (\d{1,}\.\d{1,}\.\d{1,})/
Regexp.last_match(1)
end
# @return [Array<Rule>]
# Array of rubocop rule instances which ordered by offense count
def all_rules
@all_rules ||=
file_contents
.split(/\n{2,}/)
.map! { |content| Rule.new(content) }
.reject! { |rule| invalid?(rule) }
.sort!
end
# @return [Array<Rule>]
def auto_correctable_rules
all_rules.select(&:auto_correctable?)
end
# @return [Rule]
def least_occurrence_rule
auto_correctable_rules.first
end
# @return [Rule]
def most_occurrence_rule
auto_correctable_rules.last
end
# @return [Rule]
def any_rule
auto_correctable_rules.sample
end
private
attr_reader :rubocop_todo_file_path
# @return [String] the ".rubocop_todo.yml" contents
def file_contents
@file_contents ||= File.read(rubocop_todo_file_path)
end
# @param rule [Rule] the target rule
# @return [Boolean]
def invalid?(rule)
rule.offense_count.zero? || ignored_rules.include?(rule.title)
end
# @return [Array<String>] Ignored rule titles
def ignored_rules
@ignored_rules ||= ConfigEditor.new.ignored_rules
end
end
end
end
| 25.083333
| 77
| 0.614064
|
c4a82c434e58b321c715c96ac6bd83d5400cd1fe
| 5,802
|
cpp
|
C++
|
sdl2/sdlbird/Sprite.cpp
|
pdpdds/SDLGameProgramming
|
3af68e2133296f3e7bc3d7454d9301141bca2d5a
|
[
"BSD-2-Clause"
] | null | null | null |
sdl2/sdlbird/Sprite.cpp
|
pdpdds/SDLGameProgramming
|
3af68e2133296f3e7bc3d7454d9301141bca2d5a
|
[
"BSD-2-Clause"
] | null | null | null |
sdl2/sdlbird/Sprite.cpp
|
pdpdds/SDLGameProgramming
|
3af68e2133296f3e7bc3d7454d9301141bca2d5a
|
[
"BSD-2-Clause"
] | null | null | null |
/*
* Copyright (c) 2014, Wei Mingzhi <whistler_wmz@users.sf.net>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author and contributors may not be used to endorse
* or promote products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL WASABI SYSTEMS, INC
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "Sprite.h"
CSprite::CSprite(SDL_Renderer *pRenderer, const char *szImageFileName, const char *szTxtFileName)
{
Load(pRenderer, szImageFileName, szTxtFileName);
}
CSprite::~CSprite()
{
if (m_pTexture != NULL)
{
SDL_DestroyTexture(m_pTexture);
}
}
/**
* This hash function has been taken from an Article in Dr Dobbs Journal.
* This is normally a collision-free function, distributing keys evenly.
* Collision can be avoided by comparing the key itself in last resort.
*/
inline unsigned int CalcTag(const char *sz)
{
unsigned int hash = 0;
while (*sz)
{
hash += (unsigned short)*sz;
hash += (hash << 10);
hash ^= (hash >> 6);
sz++;
}
hash += (hash << 3);
hash ^= (hash >> 11);
hash += (hash << 15);
return hash;
}
void CSprite::Draw(SDL_Renderer *pRenderer, const char *szTag, int x, int y)
{
unsigned int uiTag = CalcTag(szTag);
std::map<unsigned int, SpritePart_t>::iterator it = m_mapSpriteParts.find(uiTag);
if (it != m_mapSpriteParts.end())
{
SDL_Rect srcrect, dstrect;
srcrect.x = it->second.X;
srcrect.y = it->second.Y;
srcrect.w = it->second.usWidth;
srcrect.h = it->second.usHeight;
dstrect.x = x;
dstrect.y = y;
dstrect.w = it->second.usWidth;
dstrect.h = it->second.usHeight;
SDL_RenderCopy(pRenderer, m_pTexture, &srcrect, &dstrect);
}
}
void CSprite::DrawEx(SDL_Renderer *pRenderer, const char *szTag, int x, int y, double angle, SDL_RendererFlip flip)
{
unsigned int uiTag = CalcTag(szTag);
std::map<unsigned int, SpritePart_t>::iterator it = m_mapSpriteParts.find(uiTag);
if (it != m_mapSpriteParts.end())
{
SDL_Rect srcrect, dstrect;
srcrect.x = it->second.X;
srcrect.y = it->second.Y;
srcrect.w = it->second.usWidth;
srcrect.h = it->second.usHeight;
dstrect.x = x;
dstrect.y = y;
dstrect.w = it->second.usWidth;
dstrect.h = it->second.usHeight;
SDL_RenderCopyEx(pRenderer, m_pTexture, &srcrect, &dstrect, angle, NULL, flip);
}
}
void CSprite::Load(SDL_Renderer *pRenderer, const char *szImageFileName, const char *szTxtFileName)
{
SDL_Surface *pSurface = SDL_LoadBMP(szImageFileName);
if (pSurface == NULL)
{
fprintf(stderr, "CSprite::Load(): IMG_Load failed: %s\n", SDL_GetError());
return;
}
m_iTextureWidth = pSurface->w;
m_iTextureHeight = pSurface->h;
m_pTexture = SDL_CreateTextureFromSurface(pRenderer, pSurface);
SDL_FreeSurface(pSurface);
if (m_pTexture == NULL)
{
fprintf(stderr, "CSprite::Load(): SDL_CreateTextureFromSurface failed: %s\n", SDL_GetError());
return;
}
// Load txt file
if (!LoadTxt(szTxtFileName))
{
SDL_DestroyTexture(m_pTexture);
m_pTexture = NULL;
fprintf(stderr, "CSprite::Load(): LoadTxte failed\n");
return;
}
}
bool CSprite::LoadTxt(const char *szTxtFileName)
{
SDL_RWops *rwops = SDL_RWFromFile(szTxtFileName, "r");
if (rwops == NULL)
{
return false;
}
char *pBuf = (char *)malloc(SDL_RWsize(rwops) + 1);
if (pBuf == NULL)
{
SDL_RWclose(rwops);
return false;
}
SDL_RWread(rwops, pBuf, 1, SDL_RWsize(rwops));
pBuf[SDL_RWsize(rwops)] = '\0';
SDL_RWclose(rwops);
char *p = pBuf;
while (p != NULL && *p != '\0')
{
char name[256];
int w, h;
float x1, y1, x2, y2;
if (sscanf(p, "%s %d %d %f %f %f %f", name, &w, &h, &x1, &y1, &x2, &y2) != 7)
{
p = strstr(p, "\n");
if (p != NULL)
{
while (*p == '\n')
{
p++;
}
}
continue;
}
p = strstr(p, "\n");
if (p != NULL)
{
while (*p == '\n')
{
p++;
}
}
SpritePart_t spritePart;
spritePart.usWidth = w;
spritePart.usHeight = h;
spritePart.X = (unsigned short)(m_iTextureWidth * x1);
spritePart.Y = (unsigned short)(m_iTextureHeight * y1);
unsigned int uiTag = CalcTag(name);
if (m_mapSpriteParts.find(uiTag) == m_mapSpriteParts.end())
{
m_mapSpriteParts[uiTag] = spritePart;
}
else
{
fprintf(stderr, "CSprite::LoadTxt(): WARNING, duplicate tag: %s %u\n", name, uiTag);
}
}
free(pBuf);
return true;
}
| 25.901786
| 115
| 0.647363
|
5c6249b5600caeb9e72f0f626d60b7dd64ab6bd0
| 10,391
|
js
|
JavaScript
|
warden/static/js/portfolio_compare.js
|
pathtoknowhere/warden
|
3cff5378bf5e47132c3ddf38b9b9caf1085c7e46
|
[
"MIT"
] | 27
|
2021-03-12T06:04:36.000Z
|
2022-03-25T18:42:26.000Z
|
warden/static/js/portfolio_compare.js
|
pathtoknowhere/warden
|
3cff5378bf5e47132c3ddf38b9b9caf1085c7e46
|
[
"MIT"
] | 6
|
2020-10-16T10:34:51.000Z
|
2021-02-07T21:01:13.000Z
|
warden/static/js/portfolio_compare.js
|
pathtoknowhere/warden
|
3cff5378bf5e47132c3ddf38b9b9caf1085c7e46
|
[
"MIT"
] | 5
|
2021-04-07T18:11:28.000Z
|
2022-03-10T15:00:32.000Z
|
$(document).ready(function () {
// Data to pre-fill start and end dates
var now = new Date();
var oneYrAgo = new Date();
oneYrAgo.setYear(now.getFullYear() - 1);
document.getElementById('start_date').valueAsDate = oneYrAgo;
document.getElementById('end_date').valueAsDate = new Date();
$('.change_monitor').on('change', change_refresh);
run_ajax();
});
function change_refresh() {
$('#alerts').html("<div class='small alert alert-info alert-dismissible fade show' role='alert'>Please wait... Refreshing data." +
"</div>")
setTimeout(function () { run_ajax(); }, 1000)
};
function run_ajax() {
// Ajax to get the json:
// portfolio_compare_json?tickers=BTC,ETH,AAPL&start=%272019-05-10%27&end=%272019-05-20%27
tickers = $('#tickers').val()
start_date = $('#start_date').val()
end_date = $('#end_date').val()
$.ajax({
type: "GET",
dataType: 'json',
url: "/portfolio_compare_json?method=chart&tickers=" + tickers + "&start=" + start_date + "&end=" + end_date,
success: function (data) {
$('#alerts').html("")
console.log("ajax request: OK")
handle_ajax_data(data);
},
error: function (xhr, status, error) {
$('#alerts').html("<div class='small alert alert-danger alert-dismissible fade show' role='alert'>An error occured while refreshing data." +
"<button type='button' class='close' data-dismiss='alert' aria-label='Close'><span aria-hidden='true'>×</span></button></div>")
console.log(status);
}
});
};
function handle_ajax_data(data) {
// Var to return message alerts for ticker errors
var failed_message = "";
// Prepare data for chart
// The ajax return functions sends a string that needs to be read as a json
var parsed_data = (jQuery.parseJSON(data.data));
var chart_data_list = [];
var nav_dict = {};
// These are all HighChart inputs - first for NAV, then loop through tickers
nav_dict['name'] = 'Portfolio (base 100)';
nav_dict['yAxis'] = 0;
nav_dict['type'] = 'line';
nav_dict['color'] = '#8CADE1'; // Portfolio line is orange and thicker
nav_dict['lineWidth'] = 5;
nav_dict['turboThreshold'] = 0;
nav_dict['data'] = Object.keys(parsed_data['NAV_norm']).map((key) => [((key * 1)), parsed_data['NAV_norm'][key]]);
chart_data_list.push(nav_dict);
// Looping through Tickers (only ones that downloaded ok)
$.each(data.messages, function (key_x, value) {
if (value == "ok") {
// Prep data for chart
tmp_dict = {};
tmp_dict['name'] = key_x;
tmp_dict['type'] = 'line';
tmp_dict['turboThreshold'] = 0;
// The line below maps in a format that HighCharts can understand. the *1 is necessary for some weird reason.
tmp_dict['data'] = Object.keys(parsed_data[key_x + '_norm']).map((key) => [((key * 1)), parsed_data[key_x + '_norm'][key]]);
tmp_dict['yAxis'] = 0;
chart_data_list.push(tmp_dict);
} else {
failed_message = failed_message + " " + (key_x) + " (" + value + ") ";
}
});
// Return alert with error message for tickers not found
if (failed_message != "") {
failed_message = "Some tickers returned errors: " + failed_message;
$('#alerts').html("<div class='small alert alert-warning alert-dismissible fade show' role='alert'>" + failed_message +
"</div>")
// Hide alert after 4500ms
$("#alerts").fadeTo(4500, 500).slideUp(500, function () {
$("#alerts").slideUp(500);
});
};
// Get data from metadata
meta_data_all = ((data.meta_data));
$('#table_start').html(data.table.meta.start_date);
$('#table_end').html(data.table.meta.end_date);
$('#table_days').html(data.table.meta.number_of_days + " (" + data.table.meta.count_of_points + ")");
// Now, generate the table with meta data for each ticker
// First the Portfolio Data
var html_table = " <tr class='table-success'> \
<td class='text-left'> NAV</td>\
<td class='text-center redgreen'>" + (data.table.NAV.return * 100).toLocaleString('en-US', { style: 'decimal', maximumFractionDigits: 2, minimumFractionDigits: 2 }) + "%</td>\
<td class='text-center'> - </td>\
<td class='text-center'>" + (data.table.NAV.ann_std_dev * 100).toLocaleString('en-US', { style: 'decimal', maximumFractionDigits: 2, minimumFractionDigits: 2 }) + "%</td>\
<td class='text-center redgreen'>" + (data.table.NAV.return / data.table.NAV.ann_std_dev).toLocaleString('en-US', { style: 'decimal', maximumFractionDigits: 2, minimumFractionDigits: 2 }) + "</td>\
<td class='text-center redgreen'>" + (data.table.NAV.avg_return * 100).toLocaleString('en-US', { style: 'decimal', maximumFractionDigits: 2, minimumFractionDigits: 2 }) + "%</td>\
<td class='text-right'>" + (data.table.NAV.start).toLocaleString('en-US', { style: 'decimal', maximumFractionDigits: 2, minimumFractionDigits: 2 }) + "</td>\
<td class='text-right'>" + (data.table.NAV.end).toLocaleString('en-US', { style: 'decimal', maximumFractionDigits: 2, minimumFractionDigits: 2 }) + "</td>\
</tr>";
$.each(data.messages, function (key_x, value) {
console.log(key_x);
if (value == "ok") {
html_table = html_table +
" <tr> \
<td class='text-left'>"+ key_x + "</td>\
<td class='text-center redgreen'>" + (data.table[key_x]['return'] * 100).toLocaleString('en-US', { style: 'decimal', maximumFractionDigits: 2, minimumFractionDigits: 2 }) + "%</td>\
<td class='text-center redgreen'>" + (data.table[key_x]['comp2nav'] * 100).toLocaleString('en-US', { style: 'decimal', maximumFractionDigits: 2, minimumFractionDigits: 2 }) + " %</td>\
<td class='text-center'>" + (data.table[key_x]['ann_std_dev'] * 100).toLocaleString('en-US', { style: 'decimal', maximumFractionDigits: 2, minimumFractionDigits: 2 }) + "%</td>\
<td class='text-center redgreen'>" + (data.table[key_x]['return'] / data.table[key_x]['ann_std_dev']).toLocaleString('en-US', { style: 'decimal', maximumFractionDigits: 2, minimumFractionDigits: 2 }) + "</td>\
<td class='text-center redgreen'>" + (data.table[key_x]['avg_return'] * 100).toLocaleString('en-US', { style: 'decimal', maximumFractionDigits: 2, minimumFractionDigits: 2 }) + "%</td>\
<td class='text-right'>" + (data.table[key_x]['start']).toLocaleString('en-US', { style: 'decimal', maximumFractionDigits: 2, minimumFractionDigits: 2 }) + "</td>\
<td class='text-right'>" + (data.table[key_x]['end']).toLocaleString('en-US', { style: 'decimal', maximumFractionDigits: 2, minimumFractionDigits: 2 }) + "</td>\
</tr>";
};
});
$('#table_body').html(html_table);
// Format Red and Green Numbers (negative / positive)
$("td.redgreen").removeClass('red_negpos');
$("td.redgreen").addClass('green_negpos');
$("td.redgreen:contains('-')").removeClass('green_negpos');
$("td.redgreen:contains('-')").addClass('red_negpos');
// Create Correlation Table
$('#corr_table').html(data.corr_html);
// Format colors depending on value
// Define the ending colour, which is white
xr = 255; // Red value
xg = 255; // Green value
xb = 255; // Blue value
// Define the starting colour for positives
yr = 157; // Red value 243
yg = 188; // Green value 32
yb = 156; // Blue value 117
n = 100; // Declare the number of groups
$('#corr_table').each(function () {
$(this).find('th').each(function () {
$(this).css('background-color', '#c5c7c9');
})
$(this).find('td').each(function () {
var val = parseFloat($(this).text(), 10);
var pos = parseInt((Math.round((val / 1) * 100)).toFixed(0));
red = parseInt((xr + ((pos * (yr - xr)) / (n - 1))).toFixed(0));
green = parseInt((xg + ((pos * (yg - xg)) / (n - 1))).toFixed(0));
blue = parseInt((xb + ((pos * (yb - xb)) / (n - 1))).toFixed(0));
clr = 'rgb(' + red + ',' + green + ',' + blue + ')';
$(this).css({ backgroundColor: clr });
})
})
createChart(chart_data_list);
};
// CHART
function createChart(data) {
console.log(data)
var myChart = Highcharts.stockChart('compchart', {
credits: {
enabled: false
},
navigator: {
enabled: false
},
rangeSelector: {
enabled: false
},
chart: {
zoomType: 'x',
backgroundColor: "#FAFAFA",
},
title: {
text: 'Portfolio NAV compared to other assets'
},
subtitle: {
text: document.ontouchstart === undefined ?
'Click and drag in the plot area to zoom in' : 'Pinch the chart to zoom in'
},
xAxis: {
type: 'datetime'
},
yAxis: {
startOnTick: false,
endOnTick: false
},
legend: {
enabled: true,
align: 'right'
},
plotOptions: {
area: {
fillColor: {
linearGradient: {
x1: 0,
y1: 0,
x2: 0,
y2: 1
},
stops: [
[0, Highcharts.getOptions().colors[0]],
[1, Highcharts.Color(Highcharts.getOptions().colors[0]).setOpacity(0).get('rgba')]
]
},
marker: {
radius: 2
},
lineWidth: 1,
states: {
hover: {
lineWidth: 1
}
},
threshold: null
}
},
series: data
});
};
| 43.116183
| 233
| 0.540275
|
a11b41e52806fb0db21a4616d926854742c4abf0
| 111
|
ts
|
TypeScript
|
packages/libs/design-system/src/atoms/index.ts
|
bootleg-rust/sites
|
0630cab4b4a703e6c99269994e5ab96ca5a0844e
|
[
"MIT"
] | 2
|
2020-08-16T21:43:18.000Z
|
2020-12-22T20:05:31.000Z
|
packages/libs/design-system/src/atoms/index.ts
|
bootleg-rust/sites
|
0630cab4b4a703e6c99269994e5ab96ca5a0844e
|
[
"MIT"
] | 1
|
2020-12-11T12:28:19.000Z
|
2020-12-11T12:28:19.000Z
|
packages/libs/design-system/src/atoms/index.ts
|
bootleg-rust/sites
|
0630cab4b4a703e6c99269994e5ab96ca5a0844e
|
[
"MIT"
] | 1
|
2021-10-05T15:01:57.000Z
|
2021-10-05T15:01:57.000Z
|
export * from "./anchor";
export * from "./forms";
export * from "./headings";
export * from "./text-content";
| 22.2
| 31
| 0.630631
|
db7d828d072de3dcc9ed9e9c9572947932c9c10b
| 4,735
|
php
|
PHP
|
login.php
|
Jedbert/Temple
|
81288d680b220229829052ed7cb649b28bbed958
|
[
"Apache-2.0"
] | null | null | null |
login.php
|
Jedbert/Temple
|
81288d680b220229829052ed7cb649b28bbed958
|
[
"Apache-2.0"
] | null | null | null |
login.php
|
Jedbert/Temple
|
81288d680b220229829052ed7cb649b28bbed958
|
[
"Apache-2.0"
] | null | null | null |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link
href="https://fonts.googleapis.com/css?family=Handlee"
rel="stylesheet">
<title>Login</title>
<style>
h1 {
color: rgb(193, 211, 193);
margin-left: 50px;
}
</style>
<style>
body {
margin: 0;
}
.header {
background-color: #86867c;
padding: 5px;
text-align: center;
}
</style>
</head>
<body>
<div class="header" role="heading">
<p><img src="https://lh3.googleusercontent.com/pw/ACtC-3e18XmqZUul78P-iotO1x4kjez-ssISNBKlmy5Um9fxsAoKg05eWmTbQ5vhunC_K1nYRBqGRvGuGhLierBPD8itmY-LJzmyF0IrnzM3t64x-_ykl4VsWa5b-ptlYw6bMfJfGLLfLOPNqMCxn-F4au-P=w470-h296-no?authuser=0" width="150" height="100" style="float:right" alt="">
<h1><b>DESIGN AND IMPLEMENTATION OF E-LIBRARY FOR NATIONAL OPEN UNIVERSITY OF NIGERIA</b></h1>
</div>
</head>
<body>
<style>
* {
box-sizing: border-box;
}
body {
margin: 0;
}
/* Style the header */
.header {
background-color: #f1f1f1;
padding: 20px;
text-align: center;
}
/* Style the top navigation bar */
.topnav {
overflow: hidden;
background-color: #333;
}
/* Style the topnav links */
.topnav a {
float: left;
display: block;
color: #f2f2f2;
text-align: center;
padding: 14px 16px;
text-decoration: none;
}
/* Change color on hover */
.topnav a:hover {
background-color: #ddd;
color: black;
}
.row:after {
content: "";
display: table;
clear: both;
}
</style>
</head>
<body>
<div class="header" role="heading">
</div>
<div class="topnav">
<a href="index.html">Home</a>
<a href="Member.php">Login</a>
<a href="registration.html">Register</a>
</div>
</style>
<div id="sidebar-left">
<p> Login using your registered details to have full access to NOUN Online Course materials</p>
</div>
<div id="main">
<h1>WELCOME TO NOUN E-LIBRARY</h1>
<div>
<?php
use Phppot\Member;
if (! empty($_POST["login-btn"])) {
require_once __DIR__ . '/Model/Member.php';
$member = new Member();
$loginResult = $member->loginMember();
}
?>
</div>
<html>
<head>
<TITLE>Login</TITLE>
<link href="assets/css/phppot-style.css" type="text/css"
rel="stylesheet" />
<link href="assets/css/user-registration.css" type="text/css"
rel="stylesheet" />
<script src="vendor/jquery/jquery-3.3.1.js" type="text/javascript"></script>
</head>
<body>
<div class="phppot-container">
<div class="sign-up-container">
<div class="login-signup">
<a href="user-registration.php">Sign up</a>
</div>
<div class="signup-align">
<form name="login" action="" method="post"
onsubmit="return loginValidation()">
<div class="signup-heading">Login</div>
<?php if(!empty($loginResult)){?>
<div class="error-msg"><?php echo $loginResult;?></div>
<?php }?>
<div class="row">
<div class="inline-block">
<div class="form-label">
Username<span class="required error" id="username-info"></span>
</div>
<input class="input-box-330" type="text" name="username"
id="username">
</div>
</div>
<div class="row">
<div class="inline-block">
<div class="form-label">
Password<span class="required error" id="login-password-info"></span>
</div>
<input class="input-box-330" type="password"
name="login-password" id="login-password">
</div>
</div>
<div class="row">
<input class="btn" type="submit" name="login-btn"
id="login-btn" value="Login">
</div>
</form>
</div>
</div>
</div>
<script>
function loginValidation() {
var valid = true;
$("#username").removeClass("error-field");
$("#password").removeClass("error-field");
var UserName = $("#username").val();
var Password = $('#login-password').val();
$("#username-info").html("").hide();
if (UserName.trim() == "") {
$("#username-info").html("required.").css("color", "#ee0000").show();
$("#username").addClass("error-field");
valid = false;
}
if (Password.trim() == "") {
$("#login-password-info").html("required.").css("color", "#ee0000").show();
$("#login-password").addClass("error-field");
valid = false;
}
if (valid == false) {
$('.error-field').first().focus();
valid = false;
}
return valid;
}
</script>
<p>NATIONAL OPEN UNIVERSITY IS THE BEST LEARNING INSTITUTE, WORK AND LEARN, AFFORDABLE AND RELIABLE</p>
</body>
</html>
| 24.035533
| 290
| 0.584583
|
387e5ca1cf5bedbdf972c580af2b1048561b4a5e
| 365
|
php
|
PHP
|
app/Models/Statistic.php
|
hiepsieuhp89/loser
|
0fccba6ac40e6763b493c66e41ba2981c647bb4b
|
[
"MIT"
] | null | null | null |
app/Models/Statistic.php
|
hiepsieuhp89/loser
|
0fccba6ac40e6763b493c66e41ba2981c647bb4b
|
[
"MIT"
] | null | null | null |
app/Models/Statistic.php
|
hiepsieuhp89/loser
|
0fccba6ac40e6763b493c66e41ba2981c647bb4b
|
[
"MIT"
] | null | null | null |
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Statistic extends Model
{
use HasFactory;
protected $table = "statistics";
protected $fillable = [
'visits_count',
'docs-count',
"generating_number_count",
"messages_sent_count",
];
}
| 18.25
| 54
| 0.673973
|
3c826ef97523e86de52d6dc38c2c65155b490799
| 3,945
|
dart
|
Dart
|
app/lib/models.dart
|
HansMuller/cocoon
|
439172aae6418c4bdb3bbe7e2ebcfe225f743ca7
|
[
"BSD-3-Clause"
] | 1
|
2021-03-04T06:12:58.000Z
|
2021-03-04T06:12:58.000Z
|
app/lib/models.dart
|
xu-baolin/cocoon
|
9f60997665afeada6792bc4c4c1e01a5244d2699
|
[
"BSD-3-Clause"
] | null | null | null |
app/lib/models.dart
|
xu-baolin/cocoon
|
9f60997665afeada6792bc4c4c1e01a5244d2699
|
[
"BSD-3-Clause"
] | null | null | null |
// Copyright 2016 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:json_annotation/json_annotation.dart';
part 'models.g.dart';
@JsonSerializable(nullable: true)
class GetBenchmarksResult {
const GetBenchmarksResult({this.benchmarks});
factory GetBenchmarksResult.fromJson(Map<String, dynamic> json) => _$GetBenchmarksResultFromJson(json);
@JsonKey(name: 'Benchmarks')
final List<BenchmarkData> benchmarks;
Map<String, dynamic> toJson() => _$GetBenchmarksResultToJson(this);
}
@JsonSerializable(nullable: true)
class BenchmarkData {
const BenchmarkData({this.timeseries, this.values});
factory BenchmarkData.fromJson(Map<String, dynamic> json) => _$BenchmarkDataFromJson(json);
@JsonKey(name: 'Timeseries')
final TimeseriesEntity timeseries;
@JsonKey(name: 'Values')
final List<TimeseriesValue> values;
Map<String, dynamic> toJson() => _$BenchmarkDataToJson(this);
}
@JsonSerializable(nullable: true)
class GetTimeseriesHistoryResult {
const GetTimeseriesHistoryResult({
this.benchmarkData,
this.lastPosition,
});
factory GetTimeseriesHistoryResult.fromJson(Map<String, dynamic> json) => _$GetTimeseriesHistoryResultFromJson(json);
@JsonKey(name: 'BenchmarkData')
final BenchmarkData benchmarkData;
@JsonKey(name: 'LastPosition', fromJson: fromCursor)
final String lastPosition;
Map<String, dynamic> toJson() => _$GetTimeseriesHistoryResultToJson(this);
}
@JsonSerializable(nullable: true)
class TimeseriesEntity {
const TimeseriesEntity({
this.key,
this.timeseries,
});
factory TimeseriesEntity.fromJson(Map<String, dynamic> json) => _$TimeseriesEntityFromJson(json);
@JsonKey(name: 'Key')
final String key;
@JsonKey(name: 'Timeseries')
final Timeseries timeseries;
Map<String, dynamic> toJson() => _$TimeseriesEntityToJson(this);
}
@JsonSerializable(nullable: true)
class Timeseries {
const Timeseries({
this.id,
this.taskName,
this.label,
this.unit,
this.goal,
this.baseline,
this.isArchived,
});
factory Timeseries.fromJson(Map<String, dynamic> json) => _$TimeseriesFromJson(json);
@JsonKey(name: 'ID')
final String id;
@JsonKey(name: 'TaskName')
final String taskName;
@JsonKey(name: 'Label')
final String label;
@JsonKey(name: 'Unit')
final String unit;
@JsonKey(name: 'Goal')
final double goal;
@JsonKey(name: 'Baseline')
final double baseline;
@JsonKey(name: 'Archived')
final bool isArchived;
Map<String, dynamic> toJson() => _$TimeseriesToJson(this);
}
@JsonSerializable(nullable: true)
class BranchList {
const BranchList({
this.branches,
});
factory BranchList.fromJson(Map<String, dynamic> json) => _$BranchListFromJson(json);
@JsonKey(name: 'Branches')
final List<String> branches;
Map<String, dynamic> toJson() => _$BranchListToJson(this);
}
@JsonSerializable(nullable: true)
class TimeseriesValue {
const TimeseriesValue({
this.createTimestamp,
this.revision,
this.value,
this.isDataMissing,
});
factory TimeseriesValue.fromJson(Map<String, dynamic> json) => _$TimeseriesValueFromJson(json);
@JsonKey(name: 'CreateTimestamp')
final int createTimestamp;
@JsonKey(name: 'Revision')
final String revision;
@JsonKey(name: 'Value')
final double value;
@JsonKey(name: 'DataMissing', defaultValue: false)
final bool isDataMissing;
Map<String, dynamic> toJson() => _$TimeseriesValueToJson(this);
}
/// Creates a [DateTime] object from milliseconds.
///
/// Used in a [JsonKey] annotation to deserialize a [DateTime] from an [int].
DateTime fromMilliseconds(int millisecondsSinceEpoch) {
return new DateTime.fromMillisecondsSinceEpoch(millisecondsSinceEpoch);
}
/// Creates a string which represents a Cursor object
String fromCursor(Object value) {
return value?.toString() ?? '';
}
| 24.351852
| 119
| 0.732066
|
bb53b97d6412bd4b1173a8dd3b05d4d86c57ed5e
| 826
|
cs
|
C#
|
prosr.Parser/Models/AstExtensions.cs
|
aserowy/hackathonblazor_prosr_adminui
|
202376b2b3cafc076264274b8af3920f9cda15cb
|
[
"MIT"
] | null | null | null |
prosr.Parser/Models/AstExtensions.cs
|
aserowy/hackathonblazor_prosr_adminui
|
202376b2b3cafc076264274b8af3920f9cda15cb
|
[
"MIT"
] | null | null | null |
prosr.Parser/Models/AstExtensions.cs
|
aserowy/hackathonblazor_prosr_adminui
|
202376b2b3cafc076264274b8af3920f9cda15cb
|
[
"MIT"
] | null | null | null |
using System.Collections.Generic;
namespace prosr.Parser.Models
{
internal static class AstExtensions
{
public static void Pack(this Ast ast)
{
Package? package = null;
var nodes = new List<INode>();
foreach (var node in ast.Nodes)
{
if (node is Package pkg)
{
package = pkg;
nodes.Add(package);
}
else
{
if (package is null)
{
nodes.Add(node);
}
else
{
package.Nodes.Add(node);
}
}
}
ast.Nodes = nodes;
}
}
}
| 22.944444
| 48
| 0.349879
|
88502c38ba1d97e969768a6301e6e58d771af57b
| 4,849
|
cs
|
C#
|
DependencyScannerDotnet.App/GuiLayer/ViewModel/SelectProjectDirectoryViewModel.cs
|
spiegelp/DependencyScannerDotnet
|
3fa5914457bcd0c3b3c339599d02c156734158c9
|
[
"MIT"
] | 1
|
2021-09-21T09:17:35.000Z
|
2021-09-21T09:17:35.000Z
|
DependencyScannerDotnet.App/GuiLayer/ViewModel/SelectProjectDirectoryViewModel.cs
|
spiegelp/DependencyScannerDotnet
|
3fa5914457bcd0c3b3c339599d02c156734158c9
|
[
"MIT"
] | null | null | null |
DependencyScannerDotnet.App/GuiLayer/ViewModel/SelectProjectDirectoryViewModel.cs
|
spiegelp/DependencyScannerDotnet
|
3fa5914457bcd0c3b3c339599d02c156734158c9
|
[
"MIT"
] | null | null | null |
using DependencyScannerDotnet.Core.Model;
using MaterialDesignExtensions.Controls;
using NuniToolbox.Ui.Commands;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
namespace DependencyScannerDotnet.App.GuiLayer.ViewModel
{
public class SelectProjectDirectoryViewModel : ViewModelObject
{
private string m_selectedDirectory;
public bool HasSelectedDirectory
{
get
{
return !string.IsNullOrWhiteSpace(m_selectedDirectory);
}
}
public ICommand OpenScanOptionsCommand { get; init; }
public ICommand ScanCommand { get; init; }
public ScanOptions ScanOptions { get; init; }
public string SelectedDirectory
{
get
{
return m_selectedDirectory;
}
set
{
m_selectedDirectory = value;
OnPropertyChanged();
OnPropertyChanged(nameof(HasSelectedDirectory));
}
}
public ICommand SelectDirectoryCommand { get; init; }
public ICommand SelectImportFileCommand { get; init; }
public SelectProjectDirectoryViewModel(WindowViewModel windowViewModel)
: base(windowViewModel)
{
OpenScanOptionsCommand = new DelegateCommand(OpenScanOptionsHandler);
ScanCommand = new DelegateCommand(ScanHandler);
SelectDirectoryCommand = new DelegateCommand(SelectDirectoryHandler);
SelectImportFileCommand = new DelegateCommand(SelectImportFileHandler);
ScanOptions = new();
#if DEBUG
string solutionDirectory = Path.Combine(new DirectoryInfo(new FileInfo(GetType().Assembly.Location).DirectoryName).FullName, @"..\..\..\..\");
DirectoryInfo directory = new DirectoryInfo(solutionDirectory);
if (directory.Exists)
{
SelectedDirectory = directory.FullName;
}
#endif
}
private void OpenScanOptionsHandler()
{
WindowViewModel.OpenInRightDrawer(new ScanOptionsViewModel(ScanOptions));
}
private async void ScanHandler()
{
if (HasSelectedDirectory)
{
ScanResultViewModel nextViewModel = null;
try
{
IsBusy = true;
nextViewModel = await Task.Run(async () =>
{
ScanResultViewModel viewModel = new(WindowViewModel);
await viewModel.InitDirectoryAsync(SelectedDirectory, ScanOptions).ConfigureAwait(false);
return viewModel;
});
}
finally
{
IsBusy = false;
}
WindowViewModel.CurrentViewModel = nextViewModel;
}
}
private async void SelectDirectoryHandler()
{
OpenDirectoryDialogArguments args = new()
{
Width = 600,
Height = 800,
CurrentDirectory = SelectedDirectory ?? Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)
};
OpenDirectoryDialogResult result = await OpenDirectoryDialog.ShowDialogAsync(WindowViewModel.MainWindowDialogHostName, args);
if (result.Confirmed)
{
SelectedDirectory = result.Directory;
}
}
private async void SelectImportFileHandler()
{
OpenFileDialogArguments args = new()
{
Width = 600,
Height = 800,
CurrentDirectory = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),
Filters = "JSON|*.json"
};
OpenFileDialogResult result = await OpenFileDialog.ShowDialogAsync(WindowViewModel.MainWindowDialogHostName, args);
if (result.Confirmed)
{
ScanResultViewModel nextViewModel = null;
try
{
IsBusy = true;
nextViewModel = await Task.Run(async () =>
{
ScanResultViewModel viewModel = new(WindowViewModel);
await viewModel.InitImportAsync(result.File, ScanOptions).ConfigureAwait(false);
return viewModel;
});
}
finally
{
IsBusy = false;
}
WindowViewModel.CurrentViewModel = nextViewModel;
}
}
}
}
| 30.30625
| 154
| 0.553929
|
dd5fc22073a3f88e57b9210a3853adbd9adc7aa7
| 1,728
|
java
|
Java
|
src/main/java/io/fintechlabs/testframework/condition/as/RedirectBackToClientWithAuthorizationCodeAndIdToken.java
|
hkj123/ob-security-conformance-suite-deprecated-master
|
afa57d7d4d1399a6f869cf3dca08a0464b48a616
|
[
"MIT"
] | null | null | null |
src/main/java/io/fintechlabs/testframework/condition/as/RedirectBackToClientWithAuthorizationCodeAndIdToken.java
|
hkj123/ob-security-conformance-suite-deprecated-master
|
afa57d7d4d1399a6f869cf3dca08a0464b48a616
|
[
"MIT"
] | null | null | null |
src/main/java/io/fintechlabs/testframework/condition/as/RedirectBackToClientWithAuthorizationCodeAndIdToken.java
|
hkj123/ob-security-conformance-suite-deprecated-master
|
afa57d7d4d1399a6f869cf3dca08a0464b48a616
|
[
"MIT"
] | null | null | null |
package io.fintechlabs.testframework.condition.as;
import io.fintechlabs.testframework.condition.AbstractCondition;
import io.fintechlabs.testframework.condition.PostEnvironment;
import io.fintechlabs.testframework.condition.PreEnvironment;
import io.fintechlabs.testframework.logging.TestInstanceEventLog;
import io.fintechlabs.testframework.testmodule.Environment;
import org.springframework.web.util.UriComponentsBuilder;
public class RedirectBackToClientWithAuthorizationCodeAndIdToken extends AbstractCondition {
public RedirectBackToClientWithAuthorizationCodeAndIdToken(String testId, TestInstanceEventLog log, ConditionResult conditionResultOnFailure, String... requirements) {
super(testId, log, conditionResultOnFailure, requirements);
}
@Override
@PreEnvironment(required = "authorization_endpoint_request", strings = {"authorization_code", "id_token"})
@PostEnvironment(strings = "authorization_endpoint_response_redirect")
public Environment evaluate(Environment env) {
String idToken = env.getString("id_token");
String code = env.getString("authorization_code");
String state = env.getString("authorization_endpoint_request", "params.state");
String redirectUri = env.getString("authorization_endpoint_request", "params.redirect_uri");
String params = UriComponentsBuilder.newInstance()
.queryParam("state", state)
.queryParam("code", code)
.queryParam("id_token", idToken)
.toUriString();
if(params.startsWith("?")) {
params = params.substring(1);
}
String redirectTo = redirectUri + "#" + params;
logSuccess("Redirecting back to client", args("uri", redirectTo));
env.putString("authorization_endpoint_response_redirect", redirectTo);
return env;
}
}
| 36
| 168
| 0.798611
|
3b6fc37d6152a5504d3399e310e8493ee5618a9d
| 914
|
lua
|
Lua
|
lua/openfly_shortcut_translator.lua
|
mz299/openfly
|
cdf6fb77d76de1e03ee65ea5519410a4fc36fc74
|
[
"MIT"
] | 37
|
2021-01-09T19:33:56.000Z
|
2022-03-30T02:43:43.000Z
|
lua/openfly_shortcut_translator.lua
|
mz299/openfly
|
cdf6fb77d76de1e03ee65ea5519410a4fc36fc74
|
[
"MIT"
] | 25
|
2020-12-29T02:29:54.000Z
|
2021-11-09T03:50:51.000Z
|
lua/openfly_shortcut_translator.lua
|
mz299/openfly
|
cdf6fb77d76de1e03ee65ea5519410a4fc36fc74
|
[
"MIT"
] | 10
|
2021-01-16T08:36:26.000Z
|
2022-03-24T07:07:20.000Z
|
local common = require("openfly_common")
local labels = {
["Windows"] = {
["oav"] = {"[安装目录]"},
["ocm"] = {"[命令提示符]", "[Windows Terminal]"},
["odn"] = {"[文件管理器]"},
["oec"] = {"[Excel]"},
["oei"] = {"[启用二重简码]", "[关闭]"},
["ogj"] = {"[Rime 用户目录]"},
["oht"] = {"[画图]"},
["ojf"] = {"[简繁切换]"},
["ojs"] = {"[计算器]"},
["owd"] = {"[Word]"},
},
["Darwin"] = {
["oav"] = {"[Rime 程序目录]"},
["ocm"] = {"[终端]"},
["odn"] = {"[访达]"},
["oec"] = {"[Excel]"},
["oei"] = {"[启用二重简码]", "[关闭]"},
["ogj"] = {"[Rime 用户目录]"},
["ojf"] = {"[简繁切换]"},
["ojs"] = {"[计算器]"},
["owd"] = {"[Word]"},
}
}
local function translator(input, seg)
local sys = common.detect_os()
local lbls = labels[sys][input]
if lbls == nil then return end
for i, lbl in pairs(lbls) do
yield(Candidate("shortcut", seg.start, seg._end, lbl, ""))
end
end
return translator
| 23.435897
| 62
| 0.438731
|
8e7709746ce9ef668a43a8ddfbf7e0b505dbfd75
| 10,025
|
js
|
JavaScript
|
src/components/postsform.js
|
edersign/readable
|
d40b34d7d17fae002fdaa3afd0a99b4088e792f8
|
[
"MIT"
] | null | null | null |
src/components/postsform.js
|
edersign/readable
|
d40b34d7d17fae002fdaa3afd0a99b4088e792f8
|
[
"MIT"
] | 1
|
2019-07-13T13:51:13.000Z
|
2019-07-13T13:51:13.000Z
|
src/components/postsform.js
|
edersign/readable
|
d40b34d7d17fae002fdaa3afd0a99b4088e792f8
|
[
"MIT"
] | null | null | null |
import React from 'react';
import styled from 'styled-components';
import PropTypes from 'prop-types';
// import { Link } from 'react-router-dom';
import { formatDate } from '../utils/helpers';
// import uuid from 'uuid';
import Wrap from './wrapper';
import Vote from './vote';
import { connect } from 'react-redux';
import { RIEInput, RIETextArea } from 'riek';
import { fetchEditPost, fetchDeletePost, fetchPost } from '../actions/post';
import { ReactComponent as Calendar } from '../images/calendar.svg';
import { ReactComponent as User } from '../images/user.svg';
import { ReactComponent as Edit } from '../images/edit.svg';
import { ReactComponent as Delete } from '../images/delete.svg';
const selectOptions = [
{ id: 1, text: 'React', value: 'react' },
{ id: 2, text: 'Redux', value: 'redux' },
{ id: 3, text: 'Udacity', value: 'udacity' },
];
class PostsForm extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
id: this.props.post.id,
category: this.props.post.category,
title: this.props.post.title,
author: this.props.post.author,
body: this.props.post.body,
voteScore: this.props.post.voteScore,
commentCount: this.props.post.commentCount,
timestamp: this.props.post.timestamp,
deleted: this.props.post.deleted,
};
}
onVoteUp = (postId) => {
this.setState({ voteScore: this.props.post.voteScore + 1 });
};
onVoteDown = (postId) => {
this.setState({ voteScore: this.props.post.voteScore - 1 });
};
deletePost = () => {
this.setState({ deleted: true });
};
onCategoryChange = (e, result) => {
this.setState({ category: e.target.value });
};
onTitleChange = e => {
this.setState({ title: e.text });
};
onAuthorChange = e => {
this.setState({ author: e.text });
};
onBodyChange = e => {
this.setState({ body: e.textarea });
};
deletePost = postId => {
this.props.fetchDeletePost(postId);
this.props.fetchPost();
this.props.history.push('/');
};
handleSubmit = e => {
e.preventDefault();
const post = {
id: this.state.id,
timestamp: Date.now(),
title: this.state.title,
body: this.state.body,
author: this.state.author,
category: this.state.category,
voteScore: this.state.voteScore,
deleted: this.state.deleted,
commentCount: this.state.commentCount,
};
this.props.fetchEditPost(post.id, post);
};
render() {
return (
<Wrap>
<Article key={this.state.id}>
<EditLabel> Click the text to edit and save to save the entire edit.</EditLabel>
<PostSummary>
<PostTitle>
<InputTitle
value={this.state.title}
change={this.onTitleChange}
propName="text"
/>
</PostTitle>
<PostBody>
<TareaBody
value={this.state.body}
change={this.onBodyChange}
propName="textarea"
/>
</PostBody>
<CategoriesWrap>
<Select
onChange={this.onCategoryChange}
value={this.state.category}
>
{selectOptions.map((option, index) => (
<option value={option.value} key={index}>
{option.text}
</option>
))}
</Select>
</CategoriesWrap>
<PostMeta>
<Timestamp title={formatDate(this.state.timestamp)}>
<IconCalendar /> {formatDate(this.state.timestamp)}
</Timestamp>
<Author>
<IconUser /> By:{' '}
<InputAuthor
value={this.state.author}
change={this.onAuthorChange}
propName="text"
/>
</Author>
<PostEdit>
<PostEditOption onClick={this.handleSubmit}>
<IconEdit />
Save Edit
</PostEditOption>
<PostEditOptionDelete onClick={() => this.deletePost(this.state.id)}>
<IconDelete /> Delete
</PostEditOptionDelete>
</PostEdit>
</PostMeta>
</PostSummary>
<Vote
voteScore={this.state.voteScore}
postId={this.state.id}
onVoteUp={this.onVoteUp}
onVoteDown={this.onVoteDown}
/>
</Article>
</Wrap>
);
}
}
PostsForm.propTypes = {
post: PropTypes.object.isRequired,
};
const mapDispatchToProps = dispatch => ({
fetchEditPost: (postId, post) => dispatch(fetchEditPost(postId, post)),
fetchDeletePost: postId => dispatch(fetchDeletePost(postId)),
fetchPost: () => dispatch(fetchPost()),
});
export default connect(
() => ({}),
mapDispatchToProps,
)(PostsForm);
const Article = styled.article`
position: relative;
margin:40px auto ;
background-color: #fff;
display: flex;
cursor: pointer;
flex: 1 1 auto;
backface-visibility: hidden;
transform: translate3d(0, 0, 0);
filter: none;
box-shadow: none;
transition: all 0.2s ease-out;
border-radius: 3px;
border: 1px solid #e8e8e8;
border-radius: 3px;
box-shadow: 0 0 0 2px #ffeb3b6b;
`;
const EditLabel = styled.p`
position: absolute;
top: -13px;
left: -2px;
padding: 5px 10px;
border-bottom-left-radius: 3px;
background-color: #ffeb3b6b;
color: #866604;
font-size: 12px;
line-height: 1;
font-weight: 400;
letter-spacing: 1px;
text-transform: none;
`;
const PostSummary = styled.div`
display: flex;
justify-content: flex-start;
align-items: flex-start;
width: 80%;
flex-direction: column;
justify-content: flex-start;
margin-right: auto;
`;
const PostMeta = styled.div`
width: calc(100% - 60px);
background: #f8f9fa;
color: #678;
border-top: solid 1px rgba(102, 119, 136, 0.05);
display: flex;
align-items: center;
font-size: 14px;
padding: 20px 30px;
justify-content: space-between;
`;
const Timestamp = styled.div`
display: flex;
flex-direction: row;
align-items: center;
flex: 0 0 auto;
color: rgba(50, 59, 64, 0.8);
font-weight: 500;
text-align: center;
`;
const Author = styled(Timestamp)``;
const IconCalendar = styled(Calendar)`
display: block;
width: 24px;
height: 24px;
margin-right: 10px;
stroke: #999;
`;
const IconUser = styled(User)`
display: block;
width: 24px;
height: 24px;
margin-right: 10px;
stroke: #999;
`;
const PostTitle = styled.h3`
font: 400 48px/68px Helvetica, Arial, sans-serif;
margin: 40px;
width: 90%;
`;
const PostBody = styled.p`
margin: 0 40px 30px 40px;
`;
const CategoriesWrap = styled.div`
margin: 0 40px 20px;
`;
const PostEdit = styled.div`
display: flex;
`;
const PostEditOption = styled.button`
box-sizing: border-box;
cursor: pointer;
display: flex;
background-color: rgba(9, 30, 66, 0.04);
color: rgb(0, 82, 204);
border-radius: 3px;
padding: 8px 20px;
-webkit-text-decoration: none;
text-decoration: none;
transition: all 0.2s ease-out;
justify-content: center;
align-items: center;
flex: 1;
margin: 0 2px 0 0;
&:hover {
background-color: rgba(9, 30, 66, 0.08);
box-shadow: 0 6px 8px rgba(102, 119, 136, 0.03),
0 1px 2px rgba(102, 119, 136, 0.3);
}
`;
const PostEditOptionDelete = styled.div`
box-sizing: border-box;
cursor: pointer;
display: flex;
border-radius: 3px;
padding: 8px 20px;
-webkit-text-decoration: none;
text-decoration: none;
transition: all 0.2s ease-out;
justify-content: center;
align-items: center;
flex: 1;
background: rgba(245, 150, 126, 0.8);
color: #fff;
&:hover {
background: rgba(245, 150, 126, 1);
}
`;
const IconEdit = styled(Edit)`
display: block;
width: 24px;
height: 24px;
margin-right: 10px;
`;
const IconDelete = styled(Delete)`
display: block;
width: 24px;
height: 24px;
margin-right: 10px;
`;
const InputTitle = styled(RIEInput)`
border-style: none;
transition: all 200ms ease;
width: 100%;
box-shadow: 0 0 0 2px transparent;
vertical-align: middle;
&:focus {
transition: all 200ms ease;
box-shadow: 0 0 0 2px #ccc;
border-radius: 2px;
outline: none;
background-color: yellow;
}
`;
const InputAuthor = styled(RIEInput)`
border-style: none;
transition: all 200ms ease;
box-shadow: 0 0 0 2px transparent;
vertical-align: middle;
&:focus {
transition: all 200ms ease;
border-radius: 2px;
outline: none;
background-color: yellow;
box-shadow: 0 0 0 2px #ccc;
}
`;
const TareaBody = styled(RIETextArea)`
border-style: none;
transition: box-shadow 100ms ease;
width: 100%;
display: block;
min-width: 500px;
max-height: 220px;
min-height: 115px;
transition: all 200ms ease;
box-shadow: 0 0 0 2px transparent;
vertical-align: middle;
&:focus {
transition: all 200ms ease;
border-radius: 2px;
outline: none;
background-color: yellow;
box-shadow: 0 0 0 2px #ccc;
}
`;
const Select = styled.select`
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
background-color: rgba(0, 0, 0, 0.07);
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2' stroke-linecap='round' stroke-linejoin='round' aria-hidden='true'%3E%3Cpolyline points='6 9 12 15 18 9'%3E%3C/polyline%3E%3C/svg%3E%0A");
background-position: 98% center;
background-size: 15px;
background-repeat: no-repeat;
border-radius: 2px;
border: none;
padding: 8px 12px;
box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.15);
transition: background-color 100ms ease, box-shadow 100ms ease;
cursor: pointer;
height: 45px;
font-size: 16px;
width: 20rem;
&:focus {
transition: all 200ms ease;
outline: none;
background-color: yellow;
}
`;
| 25.57398
| 317
| 0.609676
|
cec54adf590c4cfcdbb48a0b90333a97983d5143
| 1,893
|
dart
|
Dart
|
lib/screens/splash_screen.dart
|
Dev-Devarsh/banking_neumorphic-UI
|
592f67aa21284acfe7df314e5be5b7683a9d6fd3
|
[
"Apache-2.0"
] | null | null | null |
lib/screens/splash_screen.dart
|
Dev-Devarsh/banking_neumorphic-UI
|
592f67aa21284acfe7df314e5be5b7683a9d6fd3
|
[
"Apache-2.0"
] | null | null | null |
lib/screens/splash_screen.dart
|
Dev-Devarsh/banking_neumorphic-UI
|
592f67aa21284acfe7df314e5be5b7683a9d6fd3
|
[
"Apache-2.0"
] | null | null | null |
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svg/svg.dart';
import 'package:neumorphic_code/animations/animations.dart';
import 'package:neumorphic_code/constant.dart';
import 'package:neumorphic_code/screens/home_screen.dart';
class SplashScreen extends StatefulWidget {
const SplashScreen({Key? key}) : super(key: key);
@override
_SplashScreenState createState() => _SplashScreenState();
}
class _SplashScreenState extends State<SplashScreen> {
double _height = 0;
@override
void initState() {
Timer(const Duration(milliseconds: 450), () {
_height = MediaQuery.of(context).size.height + 100;
setState(() {});
});
Timer(const Duration(milliseconds: 900), () {
Navigator.pushReplacement(
context,
PageTransition(
child: const HomeScreen(),
type: PageTransitionType.scaleDownWithFadeIn,
),
);
});
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Stack(
children: [
Center(
child: SvgPicture.asset(
'assets/icons/app_logo.svg',
key: UniqueKey(),
width: 160,
height: 160,
),
),
Positioned(
left: 0,
right: 0,
bottom: 0,
child: AnimatedContainer(
duration: const Duration(milliseconds: 650),
height: _height,
curve: Curves.fastOutSlowIn,
decoration: const BoxDecoration(
color: Colors.black,
),
),
),
],
),
),
);
}
}
| 25.581081
| 60
| 0.566825
|
5462b6f345166641b9497c1adac7bc4f6da75384
| 10,402
|
ps1
|
PowerShell
|
SCCM/Install-SCCMClient.ps1
|
voleresistor/PSJunkDrawer
|
5c2668b566148edf5385ea28919d2a3d5859efac
|
[
"MIT"
] | null | null | null |
SCCM/Install-SCCMClient.ps1
|
voleresistor/PSJunkDrawer
|
5c2668b566148edf5385ea28919d2a3d5859efac
|
[
"MIT"
] | null | null | null |
SCCM/Install-SCCMClient.ps1
|
voleresistor/PSJunkDrawer
|
5c2668b566148edf5385ea28919d2a3d5859efac
|
[
"MIT"
] | 1
|
2019-01-24T05:39:43.000Z
|
2019-01-24T05:39:43.000Z
|
<#
Product: SCCM
Purpose: Remotely push install SCCM Client on devices SCCM server can't connect to
Version: 1.0 - 02/13/17
Author: Andrew Ogden
Email: andrew.ogden@dxpe.com
#>
function Install-SccmClient
{
<#
.SYNOPSIS
Remotely push install SCCM Client on devices SCCM server can't connect to.
.DESCRIPTION
Remotely push install SCCM Client on devices SCCM server can't connect to.
.PARAMETER ComputerName
An array of computers to push the client to.
.PARAMETER ClientLocation
The path to the folder where ccmsetup.exe is stored.
.PARAMETER InstallString
A string of arguments to pass to ccmsetup.exe.
.PARAMETER LogLocation
The location to write the log file.
.PARAMETER NoWait
Don't wait for ccmsetup to finish installation before exiting. This is ignored for uninstallation.
.PARAMETER Uninstall
Uninstall existing SCCM client before installing the new one.
.EXAMPLE
Install-SccmClient -ComputerName pc001 -Clientlocation C:\temp -InstallString "/mp:cm01.contoso.com"
Install the SCCM client on pc001 using the installer in c:\temp and set a management point of cm01.
.NOTES
General notes
#>
param
(
[Parameter(Mandatory=$true, Position=1)]
[string[]]$ComputerName,
[Parameter(Mandatory=$true, Position=2)]
[string]$ClientLocation,
[Parameter(Mandatory=$true, Position=3)]
[string]$InstallString,
[Parameter(Mandatory=$false, Position=4)]
[string]$LogLocation = "C:\temp\Install-SCCMClient.log",
[Parameter(Mandatory=$false, Position=5)]
[switch]$NoWait,
[Parameter(Mandatory=$false)]
[switch]$Uninstall,
[Parameter(DontShow)]
[string]$ClientInstaller = 'ccmsetup.exe'
)
function Write-LogEntry
{
param
(
[string]$Value,
[string]$LogFile = $LogLocation
)
$Time = Get-Date -UFormat '%D - %T'
Add-Content -Value "[$Time]: $Value" -Path $LogFile
Write-Host $Value
}
function Copy-Installer
{
param
(
[Parameter(Mandatory=$true, Position=1)]
[string]$ComputerName,
[Parameter(Mandatory=$true, Position=2)]
[string]$ClientPath,
[Parameter(Mandatory=$true, Position=3)]
[string]$RemotePath,
[Parameter(Mandatory=$true, Position=4)]
[string]$LogFile
)
#Verify admin share connectivity
Write-LogEntry -LogFile $LogFile -Value "Testing connectivity to the admin share on $ComputerName..."
if (!(Test-Path -Path $RemotePath -ErrorAction SilentlyContinue))
{
Write-LogEntry -LogFile $LogFile -Value "Unable to connect to admin share on $ComputerName"
return 1
}
Write-LogEntry -LogFile $LogFile -Value "Done"
#Copy the installer
try
{
Write-LogEntry -LogFile $LogFile -Value "Copying $ClientPath to $RemotePath"
Copy-Item -Path $ClientPath -Destination $RemotePath -Force
}
catch
{
$ErrorMessage = $_.Exception.Message
Write-LogEntry -LogFile $LogFile -Value "Error: Failed to copy installer"
Write-LogEntry -LogFile $LogFile -Value "Error Message: $ErrorMessage"
return 1
}
Write-LogEntry -LogFile $LogFile -Value "Done"
return 0
}
function Install-Client
{
param
(
[Parameter(Mandatory=$true, Position=1)]
[System.Management.Automation.Runspaces.PSSession]$RemoteSession,
[Parameter(Mandatory=$true, Position=2)]
[string]$ComputerName,
[Parameter(Mandatory=$true, Position=3)]
[string]$RemotePath,
[Parameter(Mandatory=$true, Position=4)]
[string]$ClientPath,
[Parameter(Mandatory=$true, Position=5)]
[string]$RemoteCommand,
[Parameter(Mandatory=$true, Position=6)]
[string]$LogFile
)
Write-LogEntry -LogFile $LogFile -Value "Install target: $ComputerName"
#Run the installer
try
{
Write-LogEntry -LogFile $LogFile -Value "Running command `"$RemoteCommand`" on $ComputerName"
Invoke-Command -Session $RemoteSession -ScriptBlock {Invoke-Expression -Command $($args[0])} -ArgumentList $RemoteCommand
}
catch
{
$ErrorMessage = $_.Exception.Message
Write-LogEntry -LogFile $LogFile -Value "Error: Failed to start $(($ClientPath -split ('\\'))[-1]) on $ComputerName"
Write-LogEntry -LogFile $LogFile -Value "Error Message: $ErrorMessage"
return 1
}
Write-LogEntry -LogFile $LogFile -Value "Done"
#Wait for ccmsetup to complete
if (!($NoWait))
{
Write-LogEntry -LogFile $LogFile -Value "Waiting for $(($ClientPath -split ('\\'))[-1]) to exit..."
$Begin = Get-Date
$i = 0
While (Get-Process -Name 'ccmsetup' -ComputerName $ComputerName -ErrorAction SilentlyContinue)
{
$Span = New-TimeSpan -Start $Begin -End (Get-Date)
Write-Progress -Activity "Waiting for $(($ClientPath -split ('\\'))[-1]) to exit..." -Status "$($a[$i]) $("{0:D2}" -f $($Span.Minutes)):$("{0:D2}" -f $($Span.Seconds))"
$i++
if ($i -gt 3)
{
$i = 0
}
#Mark progress
if (($Span.TotalSeconds % 30) -eq 0)
{
Write-LogEntry -LogFile $LogFile -Value "Mark: $("{0:D2}" -f $($Span.Minutes)):$("{0:D2}" -f $($Span.Seconds))"
}
Start-Sleep -Seconds 1
}
Write-LogEntry -LogFile $LogFile -Value "Done"
}
return 0
}
function Remove-Client
{
param
(
[Parameter(Mandatory=$true, Position=1)]
[System.Management.Automation.Runspaces.PSSession]$RemoteSession,
[Parameter(Mandatory=$true, Position=2)]
[string]$ComputerName,
[Parameter(Mandatory=$false, Position=3)]
[string]$RemotePath,
[Parameter(Mandatory=$true, Position=4)]
[string]$ClientInstaller,
[Parameter(Mandatory=$true, Position=6)]
[string]$LogFile
)
Write-LogEntry -LogFile $LogFile -Value "Uninstall target: $ComputerName"
#Run the installer
try
{
$UninstallStr = "$RemotePath\$ClientInstaller /uninstall"
$RemoteCommand = "Start-Process -FilePath `"$RemotePath\$ClientInstaller`" -ArgumentList '/uninstall'"
Write-LogEntry -LogFile $LogFile -Value "Running command `"$UninstallStr`" on $ComputerName"
Invoke-Command -Session $RemoteSession -ScriptBlock {Invoke-Expression -Command $($args[0])} -ArgumentList $RemoteCommand
}
catch
{
$ErrorMessage = $_.Exception.Message
Write-LogEntry -LogFile $LogFile -Value "Error: Failed to start $UninstallStr on $ComputerName"
Write-LogEntry -LogFile $LogFile -Value "Error Message: $ErrorMessage"
return 1
}
Write-LogEntry -LogFile $LogFile -Value "Done"
#Wait for ccmsetup to complete
Write-LogEntry -LogFile $LogFile -Value "Waiting for $RemotePath to exit..."
$Begin = Get-Date
$i = 0
While (Get-Process -Name 'ccmsetup' -ComputerName $ComputerName -ErrorAction SilentlyContinue)
{
$Span = New-TimeSpan -Start $Begin -End (Get-Date)
Write-Progress -Activity "Waiting for `"$RemotePath\$ClientInstaller`" to exit..." -Status "$($a[$i]) $("{0:D2}" -f $($Span.Minutes)):$("{0:D2}" -f $($Span.Seconds))"
$i++
if ($i -gt 3)
{
$i = 0
}
#Mark progress
if (($Span.TotalSeconds % 30) -eq 0)
{
Write-LogEntry -LogFile $LogFile -Value "Mark: $("{0:D2}" -f $($Span.Minutes)):$("{0:D2}" -f $($Span.Seconds))"
}
Start-Sleep -Seconds 1
}
Write-LogEntry -LogFile $LogFile -Value "Done"
return 0
}
#Startup logging
$a = @('-','\','|','/')
Write-LogEntry -Value "*********************************************************************"
Write-LogEntry -Value "Installing SCCM Client for the following computers:"
foreach ($c in $ComputerName)
{
Write-LogEntry -Value "$c"
}
foreach ($c in $ComputerName)
{
#Attempt to connect using PSRemoting
try
{
$RemoteDomain = (Get-WmiObject -Class Win32_ComputerSystem -ComputerName $c).Domain
$RemotePath = "\\$c.$RemoteDomain\admin$\temp"
$RemoteProgram = "$RemotePath\ccmsetup.exe"
$RemoteCommand = "Start-Process -FilePath $RemoteProgram -ArgumentList '$InstallString'"
Write-LogEntry -Value "Creating PS Session on $c.$RemoteDomain"
$ClientSession = New-PSSession -ComputerName "$c.$RemoteDomain" -ErrorAction SilentlyContinue
$Res = Copy-Installer -ComputerName "$c.$RemoteDomain" -ClientPath "$ClientLocation\$ClientInstaller" -RemotePath $RemotePath -LogFile $LogLocation
if ($Res -ne 0)
{
continue
}
if ($Uninstall)
{
$Res = Remove-Client -RemoteSession $ClientSession -ComputerName "$c.$RemoteDomain" -RemotePath $RemotePath -LogFile $LogLocation -ClientInstaller $ClientInstaller
if ($Res -ne 0)
{
continue
}
}
$Res = Install-Client -RemoteSession $ClientSession -ComputerName "$c.$RemoteDomain" -RemotePath $RemotePath -ClientPath "$ClientLocation\$ClientInstaller" -RemoteCommand $RemoteCommand -LogFile $LogLocation
if ($Res -ne 0)
{
continue
}
}
finally
{
Remove-PSSession -Session $ClientSession
}
}
}
| 34.443709
| 219
| 0.566526
|
b057d25281faed4b5efcc357328d51094ef757b0
| 774
|
py
|
Python
|
setup.py
|
MacFan4000/sopel-channelmgnt
|
d2bc33541b9dd80e1e15c40c945efceaef6f5c5e
|
[
"EFL-2.0"
] | null | null | null |
setup.py
|
MacFan4000/sopel-channelmgnt
|
d2bc33541b9dd80e1e15c40c945efceaef6f5c5e
|
[
"EFL-2.0"
] | 85
|
2020-10-08T13:18:10.000Z
|
2022-03-29T07:18:03.000Z
|
setup.py
|
MacFan4000/sopel-channelmgnt
|
d2bc33541b9dd80e1e15c40c945efceaef6f5c5e
|
[
"EFL-2.0"
] | 2
|
2021-02-26T00:52:33.000Z
|
2022-01-10T17:57:08.000Z
|
"""Set up the package for the plugin."""
from setuptools import find_packages, setup
with open('README.md') as readme_file:
readme = readme_file.read()
with open('requirements.txt') as requirements_file:
requirements = list(requirements_file.readlines())
setup(
name='sopel_plugins.channelmgnt',
version='2.1.2',
description='Channelmgnt plugin for Sopel',
long_description=readme,
long_description_content_type='text/markdown', # This is important!
author='MirahezeBot Contributors',
author_email='staff@mirahezebots.org',
url='https://github.com/MirahezeBots/sopel-channelmgnt',
packages=find_packages('.'),
include_package_data=True,
install_requires=requirements,
license='Eiffel Forum License, version 2',
)
| 30.96
| 72
| 0.73385
|
ca7192796f4affcba074ff4bdbfd8eec90d0e566
| 310
|
lua
|
Lua
|
host/lib/rest/endpoint-status.lua
|
pgrabas/fairyNode
|
b846f068ff48fa326dc0213d3b124fa6623faab4
|
[
"MIT"
] | null | null | null |
host/lib/rest/endpoint-status.lua
|
pgrabas/fairyNode
|
b846f068ff48fa326dc0213d3b124fa6623faab4
|
[
"MIT"
] | null | null | null |
host/lib/rest/endpoint-status.lua
|
pgrabas/fairyNode
|
b846f068ff48fa326dc0213d3b124fa6623faab4
|
[
"MIT"
] | null | null | null |
return function(server)
local rest = require("lib/rest")
server:add_resource("status", {
{
method = "GET",
path = "/modules/graph/text",
produces = "text/plain",
handler = rest.HandlerModule("service-status", "GetModuleGraphText"),
},
})
end
| 23.846154
| 80
| 0.551613
|
e2aad9872c3c2970cfc99c5d732b105f354a25cd
| 2,857
|
py
|
Python
|
forms-flow-api/src/formsflow_api/services/external/keycloak.py
|
andrepestana-aot/forms-flow-ai
|
18a77a713f4af70ba077d3821db96970c0c403ae
|
[
"Apache-2.0"
] | 132
|
2020-04-16T20:26:18.000Z
|
2022-03-30T12:39:50.000Z
|
forms-flow-api/src/formsflow_api/services/external/keycloak.py
|
andrepestana-aot/forms-flow-ai
|
18a77a713f4af70ba077d3821db96970c0c403ae
|
[
"Apache-2.0"
] | 102
|
2020-06-05T21:30:27.000Z
|
2022-03-30T04:53:25.000Z
|
forms-flow-api/src/formsflow_api/services/external/keycloak.py
|
andrepestana-aot/forms-flow-ai
|
18a77a713f4af70ba077d3821db96970c0c403ae
|
[
"Apache-2.0"
] | 91
|
2020-04-15T18:54:51.000Z
|
2022-03-29T04:58:49.000Z
|
"""This exposes the Keycloak Admin APIs"""
import json
import requests
from flask import current_app
from formsflow_api.utils import profiletime
class KeycloakAdminAPIService(object):
"""This class manages all the Keycloak service API calls"""
def __init__(self):
self.session = requests.Session()
username = current_app.config.get("KEYCLOAK_ADMIN_USERNAME")
password = current_app.config.get("KEYCLOAK_ADMIN_PASSWORD")
headers = {"Content-Type": "application/x-www-form-urlencoded"}
payload = {
"client_id": "admin-cli",
"username": username,
"password": password,
"grant_type": "password",
}
token_api = f"{current_app.config.get('KEYCLOAK_URL')}/auth/realms/master/protocol/openid-connect/token"
response = requests.post(token_api, headers=headers, data=payload)
data = json.loads(response.text)
self.session.headers.update(
{
"Authorization": "Bearer " + data["access_token"],
"Content-Type": "application/json",
}
)
self.base_url = f"{current_app.config.get('KEYCLOAK_URL')}/auth/admin/realms/{current_app.config.get('KEYCLOAK_URL_REALM')}"
@profiletime
def get_request(self, url_path):
"""Method to fetch get request of Keycloak Admin APIs
:param url_path: The relative path of the API
"""
url = f"{self.base_url}/{url_path}"
response = self.session.request("GET", url)
response.raise_for_status()
if response.ok:
return response.json()
else:
return None
def get_paginated_request(self, url_path, first, max):
"""Method to fetch GET paginated request of Keycloak Admin APIs
:param url_path: The relative path of the API
:param first: The page_number
:param max: The max number of items per page
"""
url = f"{self.base_url}/{url_path}?first={first}&max={max}"
response = self.session.request("GET", url)
response.raise_for_status()
if response.ok:
return response.json()
else:
return None
@profiletime
def update_request(self, url_path, data=None):
"""Method to fetch get request of Keycloak Admin APIs
:param url_path: The relative path of the API
:param data: The request data object
"""
url = f"{self.base_url}/{url_path}"
try:
response = self.session.request(
"PUT",
url,
data=json.dumps(data),
)
except Exception as e:
raise f"Request to Keycloak Admin APIs failed., {e}"
else:
if response.status_code == 204:
return f"Updated - {url_path}"
| 34.841463
| 132
| 0.60028
|
7ddb81cea76f10e29a661d0dcb11a56732841705
| 11,325
|
swift
|
Swift
|
ViteBusiness/Classes/Business/Trading/Mining/Trading/MiningTradingViewController.swift
|
vitelabs/vite-business-ios
|
76f10d45b32f12f0d1b7a14129585e1b05b8667d
|
[
"MIT"
] | 12
|
2019-03-22T00:37:04.000Z
|
2022-03-08T01:02:28.000Z
|
ViteBusiness/Classes/Business/Trading/Mining/Trading/MiningTradingViewController.swift
|
vitelabs/vite-business-ios
|
76f10d45b32f12f0d1b7a14129585e1b05b8667d
|
[
"MIT"
] | null | null | null |
ViteBusiness/Classes/Business/Trading/Mining/Trading/MiningTradingViewController.swift
|
vitelabs/vite-business-ios
|
76f10d45b32f12f0d1b7a14129585e1b05b8667d
|
[
"MIT"
] | 5
|
2019-06-13T02:43:01.000Z
|
2022-01-08T19:05:27.000Z
|
//
// MiningTradingViewController.swift
// ViteBusiness
//
// Created by Stone on 2020/6/1.
//
import Foundation
class MiningTradingViewController: BaseTableViewController {
var viewModle: MiningTradingListViewModel?
override func viewDidLoad() {
super.viewDidLoad()
setupView()
bind()
}
func setupView() {
tableView.contentInsetAdjustmentBehavior = .never
tableView.tableHeaderView = makeHeaderView()
}
let totalView = MiningColorfulView(leftText: R.string.localizable.miningTradingPageHeaderTotalEarnings(), leftClicked: {
Alert.show(title: R.string.localizable.miningTradingPageHeaderTotalEarningsAlertTitle(), message: R.string.localizable.miningTradingPageHeaderTotalEarningsAlertMessage(), actions: [
(.default(title: R.string.localizable.confirm()), nil)
])
}, rightText: R.string.localizable.miningPageHeaderTotalRealTime()) {
WebHandler.openViteXHomePage()
}
let detailView = DetailView()
let listHeaderView = ListHeaderView()
func makeHeaderView() -> UIStackView {
let view = UIStackView().then {
$0.axis = .vertical
$0.alignment = .fill
$0.distribution = .fill
$0.spacing = 0
}
var height: CGFloat = 20
height += MiningColorfulView.height
height += 6
height += DetailView.height
height += ListHeaderView.height
view.frame = CGRect(x: 0, y: 0, width: 0, height: height)
view.addPlaceholder(height: 20)
view.addArrangedSubview(totalView.padding(horizontal: 12))
view.addPlaceholder(height: 6)
view.addArrangedSubview(detailView.padding(horizontal: 12))
view.addArrangedSubview(listHeaderView.padding(horizontal: 12))
return view
}
func bind() {
HDWalletManager.instance.accountDriver.drive(onNext: {[weak self] (account) in
guard let `self` = self else { return }
if let address = account?.address {
let vm = MiningTradingListViewModel(tableView: self.tableView, address: "vite_836ba5e4d3f75b013bf33f1a19fafdcacc59eb8eb6e66d2b24")
vm.totalViewModelBehaviorRelay.bind { [weak self] in
guard let `self` = self else { return }
self.totalView.valueLabel.text = $0 ?? "--.--"
}.disposed(by: vm.rx.disposeBag)
vm.miningTradingViewModelBehaviorRelay.bind { [weak self] in
guard let `self` = self else { return }
self.detailView.bind(vm: $0)
}.disposed(by: vm.rx.disposeBag)
self.viewModle = vm
} else {
self.totalView.valueLabel.text = "--.--"
self.detailView.bind(vm: nil)
self.viewModle = nil
}
}).disposed(by: rx.disposeBag)
}
}
extension MiningTradingViewController {
class DetailView: UIView {
static let height: CGFloat = 256
let titleLabel = UILabel().then {
$0.textColor = UIColor(netHex: 0x3E4A59, alpha: 0.6)
$0.font = UIFont.systemFont(ofSize: 12, weight: .regular)
$0.text = R.string.localizable.miningTradingPageHeaderTitle()
}
let lineImg = UIImageView(image: R.image.dotted_line()?.tintColor(UIColor(netHex: 0x3E4A59, alpha: 0.3)).resizableImage(withCapInsets: UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0), resizingMode: .tile))
let viteView = ItemView(type: .VITE)
let btcView = ItemView(type: .BTC)
let ethView = ItemView(type: .ETH)
let usdtView = ItemView(type: .USDT)
override init(frame: CGRect) {
super.init(frame: frame)
layer.masksToBounds = true
layer.cornerRadius = 2
backgroundColor = UIColor.gradientColor(style: .leftTop2rightBottom, frame: CGRect(x: 0, y: 0, width: kScreenW - 24, height: type(of: self).height), colors: [
UIColor(netHex: 0xE3F0FF),
UIColor(netHex: 0xF2F8FF),
])
addSubview(titleLabel)
addSubview(lineImg)
addSubview(viteView)
addSubview(btcView)
addSubview(ethView)
addSubview(usdtView)
titleLabel.snp.makeConstraints { (m) in
m.top.left.equalToSuperview().offset(12)
}
lineImg.snp.makeConstraints { (m) in
m.top.equalToSuperview().offset(40)
m.left.right.equalToSuperview().inset(12)
}
snp.makeConstraints { (m) in
m.height.equalTo(type(of: self).height)
}
viteView.snp.makeConstraints { (m) in
m.top.equalTo(lineImg.snp.bottom).offset(12)
m.left.right.equalToSuperview().inset(12)
}
btcView.snp.makeConstraints { (m) in
m.top.equalTo(viteView.snp.bottom).offset(16)
m.left.right.equalToSuperview().inset(12)
}
ethView.snp.makeConstraints { (m) in
m.top.equalTo(btcView.snp.bottom).offset(16)
m.left.right.equalToSuperview().inset(12)
}
usdtView.snp.makeConstraints { (m) in
m.top.equalTo(ethView.snp.bottom).offset(16)
m.left.right.equalToSuperview().inset(12)
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func bind(vm: MiningTradingViewModel?) {
if let vm = vm {
viteView.feeLabel.text = vm.viteFee
viteView.earningsLabel.text = "\(R.string.localizable.miningTradingPageHeaderExpect()) \(vm.viteEarnings) VX"
btcView.feeLabel.text = vm.btcFee
btcView.earningsLabel.text = "\(R.string.localizable.miningTradingPageHeaderExpect()) \(vm.btcEarnings) VX"
ethView.feeLabel.text = vm.ethFee
ethView.earningsLabel.text = "\(R.string.localizable.miningTradingPageHeaderExpect()) \(vm.ethEarnings) VX"
usdtView.feeLabel.text = vm.usdtFee
usdtView.earningsLabel.text = "\(R.string.localizable.miningTradingPageHeaderExpect()) \(vm.usdtEarnings) VX"
} else {
viteView.feeLabel.text = "--.--"
viteView.earningsLabel.text = "\(R.string.localizable.miningTradingPageHeaderExpect()) --.-- VX"
btcView.feeLabel.text = "--.--"
btcView.earningsLabel.text = "\(R.string.localizable.miningTradingPageHeaderExpect()) --.-- VX"
ethView.feeLabel.text = "--.--"
ethView.earningsLabel.text = "\(R.string.localizable.miningTradingPageHeaderExpect()) --.-- VX"
usdtView.feeLabel.text = "--.--"
usdtView.earningsLabel.text = "\(R.string.localizable.miningTradingPageHeaderExpect()) --.-- VX"
}
}
class ItemView: UIView {
enum ItemType: String {
case VITE
case BTC
case ETH
case USDT
var image: UIImage? {
switch self {
case .VITE:
return R.image.icon_mining_trading_vite()
case .BTC:
return R.image.icon_mining_trading_btc()
case .ETH:
return R.image.icon_mining_trading_eth()
case .USDT:
return R.image.icon_mining_trading_usdt()
}
}
var symbol: String { self.rawValue }
}
let iconImageView = UIImageView()
let feeTitleLabel = UILabel().then {
$0.textColor = UIColor(netHex: 0x3E4A59, alpha: 0.6)
$0.font = UIFont.systemFont(ofSize: 12, weight: .regular)
$0.text = R.string.localizable.miningTradingPageHeaderFee()
}
let feeLabel = UILabel().then {
$0.textColor = UIColor(netHex: 0x3E4A59)
$0.font = UIFont.systemFont(ofSize: 12, weight: .semibold)
$0.text = "--.--"
}
let symbolLabel = UILabel().then {
$0.textColor = UIColor(netHex: 0x3E4A59, alpha: 0.6)
$0.font = UIFont.systemFont(ofSize: 12, weight: .regular)
}
let earningsLabel = UILabel().then {
$0.textColor = UIColor(netHex: 0x3E4A59, alpha: 0.45)
$0.font = UIFont.systemFont(ofSize: 12, weight: .regular)
$0.text = "\(R.string.localizable.miningTradingPageHeaderExpect()) --.-- VX"
}
init(type: ItemType) {
super.init(frame: .zero)
iconImageView.image = type.image
symbolLabel.text = type.symbol
addSubview(iconImageView)
addSubview(feeTitleLabel)
addSubview(feeLabel)
addSubview(symbolLabel)
addSubview(earningsLabel)
iconImageView.snp.makeConstraints { (m) in
m.top.left.equalToSuperview()
m.size.equalTo(CGSize(width: 16, height: 16))
}
feeTitleLabel.snp.makeConstraints { (m) in
m.centerY.equalTo(iconImageView)
m.left.equalTo(iconImageView.snp.right).offset(8)
}
symbolLabel.snp.makeConstraints { (m) in
m.centerY.equalTo(iconImageView)
m.right.equalToSuperview().offset(-12)
}
feeLabel.snp.makeConstraints { (m) in
m.centerY.equalTo(iconImageView)
m.right.equalTo(symbolLabel.snp.left).offset(-6)
}
earningsLabel.snp.makeConstraints { (m) in
m.bottom.equalToSuperview()
m.right.equalToSuperview().offset(-12)
}
self.snp.makeConstraints { (m) in
m.height.equalTo(36)
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
}
class ListHeaderView: UIView {
static let height: CGFloat = 40
let titleLabel = UILabel().then {
$0.textColor = UIColor(netHex: 0x3E4A59)
$0.font = UIFont.systemFont(ofSize: 14, weight: .semibold)
$0.text = R.string.localizable.miningPageListTitle()
}
override init(frame: CGRect) {
super.init(frame: .zero)
addSubview(titleLabel)
titleLabel.snp.makeConstraints { (m) in
m.top.equalToSuperview().offset(16)
m.left.right.equalToSuperview()
}
snp.makeConstraints { (m) in
m.height.equalTo(type(of: self).height)
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
}
| 36.298077
| 216
| 0.551258
|
3a12b728618e4c59a959dd0f11d3bdcb0873a2da
| 324
|
lua
|
Lua
|
lua/monarized/colors/whichkey.lua
|
jhchabran/nordbuddy
|
60da87e0d6a8e681a6b64fec9f323e88f360bdda
|
[
"MIT"
] | 11
|
2021-07-14T07:57:09.000Z
|
2021-11-26T11:01:58.000Z
|
lua/monarized/colors/whichkey.lua
|
jhchabran/nordbuddy
|
60da87e0d6a8e681a6b64fec9f323e88f360bdda
|
[
"MIT"
] | 1
|
2021-10-06T19:56:56.000Z
|
2022-02-04T10:47:05.000Z
|
lua/monarized/colors/whichkey.lua
|
jhchabran/nordbuddy
|
60da87e0d6a8e681a6b64fec9f323e88f360bdda
|
[
"MIT"
] | 1
|
2021-07-14T09:41:27.000Z
|
2021-07-14T09:41:27.000Z
|
return function(c, s, cs)
-- 'folke/whick-key-nvim'
return {
{'WhichKey', c.cyan, c.none, s.bold},
{'WhichKeyGroup', c.fg1, c.none, s.bold},
{'WhichKeySeparator', c.fade1},
{'WhichKeyDesc', c.fg1},
{'WhichKeyFloat', c.none, c.bg1},
{'WhichKeyValue', c.fg1},
}
end
| 27
| 49
| 0.530864
|
9981953f2abe3582818765f753ae46ccb7cb2580
| 2,953
|
ps1
|
PowerShell
|
Getting Started/Getting Started 2015 - Section 2 - Creating New Datastores.ps1
|
cmcgowan1225/Powershell
|
252111f29d7017866e1d4efa961d9d35757fb5c0
|
[
"MIT"
] | 30
|
2015-06-03T14:22:40.000Z
|
2020-12-10T15:19:06.000Z
|
Getting Started/Getting Started 2015 - Section 2 - Creating New Datastores.ps1
|
cmcgowan1225/Powershell
|
252111f29d7017866e1d4efa961d9d35757fb5c0
|
[
"MIT"
] | 72
|
2015-05-26T16:35:59.000Z
|
2022-03-10T11:08:33.000Z
|
Getting Started/Getting Started 2015 - Section 2 - Creating New Datastores.ps1
|
cmcgowan1225/Powershell
|
252111f29d7017866e1d4efa961d9d35757fb5c0
|
[
"MIT"
] | 24
|
2015-11-03T03:32:11.000Z
|
2020-05-12T13:46:46.000Z
|
<#
This script is part of a series of scripts that were provided for instructional purposes.
Examples in this document should not be considered complete in part or in whole and used for instructional purposes.
====================================================================
| Disclaimer: |
| This script is written as best effort and provides no warranty |
| expressed or implied. Please contact SolidFire support if you |
| have questions about this script before running or modifying. |
====================================================================
#>
# Using the break in case you accidentally run the entire file
break
# Use PowerCLI for these steps.
# Get User Credentials for vCenter Server
$vcenter = "view-vcenter.vdi.sf.local"
Break
Connect-VIServer -Server $vcenter -User <username> -Password <password>
<#
##############################
Prepare Volume Access Group for dynamic Discovery
##############################
#>
# Get Volumes
$volumes = Get-SFVolume
# Get list of ESXi host software initiator IQNs
# Note: you should make sure you only collect the ESXi hosts you want to add to the Volume Access Group
$IQNs = Get-VMHost | Select name,@{n="IQN";e={$_.ExtensionData.Config.StorageDevice.HostBusAdapter.IscsiName}}
# Add IQNs to Volume Access Group
$vid = (Get-SFVolumeAccessGroup SELab01).VolumeAccessGroupID
$IQNs | %{Add-SFInitiatorToVolumeAccessGroup -VolumeAccessGroupID $vid -Initiators $_.IQN}
# Note: % is PowerShell for forEach
<#
##############################
Adding iSCSI targets
##############################
#>
# Check Target to hosts - Before
Write-Host "Showing iSCSI targets" -ForegroundColor Yellow
Get-VMHost | Get-VMhostHba -Type IScsi | Get-IScsiHbaTarget
# Collects cluster's SVIP dynamically
$SVIP = (Get-SFClusterInfo).Svip
# Add the target
Get-VMhost | Get-VMHostHba -Type IScsi | New-IScsiHbaTarget -Address $SVIP -Port 3260
<#
##############################
Part 2.4.3 - Create Datastores in VMware
##############################
#>
# Check Target to hosts
Write-Host "Showing ISCSI targets post Add" -ForegroundColor Yellow
Get-VMHost | Get-VMhostHba -Type IScsi | Get-IScsiHbaTarget
# Rescan HBAs
Get-VMhost | Get-VMhostStorage -RescanAllHba -RescanVMFs
<#
##############################
Part 2.4.4 - Create Datastores in VMware
##############################
#>
# Create Datastore with a loop that matches the datastore name to the volume name.
$vmhost = Get-VMhost | Select -First 1
foreach($volume in $volumes){
$canonicalname = "naa." + $volume.Scsi_NAA_DeviceID
New-Datastore -VMhost $vmhost -Name $volume.VolumeName -Path $canonicalname -Vmfs -FileSystemVersion 5
}
# Rescan HBAs
Get-VMhost | Get-VMhostStorage -RescanAllHba -RescanVMFs
<# Review the available datastores.
Click on the ESXi Host
Identify the new datastores under Resources frame
or
Click on Configuration tab
Select Storage
#>
| 30.443299
| 116
| 0.650525
|
f73e0f471295aae4e4c7a4e85a47d3dc01d8f8fc
| 2,631
|
lua
|
Lua
|
scripts/globals/weaponskills/death_blossom.lua
|
Endymionls/topaz
|
b1fe7fc4cfbcb30236dd057c808e4883621d4849
|
[
"FTL"
] | null | null | null |
scripts/globals/weaponskills/death_blossom.lua
|
Endymionls/topaz
|
b1fe7fc4cfbcb30236dd057c808e4883621d4849
|
[
"FTL"
] | null | null | null |
scripts/globals/weaponskills/death_blossom.lua
|
Endymionls/topaz
|
b1fe7fc4cfbcb30236dd057c808e4883621d4849
|
[
"FTL"
] | 1
|
2020-05-28T21:35:05.000Z
|
2020-05-28T21:35:05.000Z
|
-----------------------------------
-- Death Blossom
-- Sword weapon skill (RDM main only)
-- Description: Delivers a threefold attack that lowers target's magic evasion. Chance of lowering target's magic evasion varies with TP. Murgleis: Aftermath effect varies with TP.
-- Lowers magic evasion by up to 10.
-- Effect lasts up to 55 seconds.
-- Available only after completing the Unlocking a Myth (Red Mage) quest.
-- Aligned with the Breeze Gorget, Thunder Gorget, Aqua Gorget & Snow Gorget.
-- Aligned with the Breeze Belt, Thunder Belt, Aqua Belt & Snow Belt.
-- Modifiers: STR:30% MND:50%
-- 100%TP 200%TP 300%TP
-- 4 4 4 new
-- 1.125 1.125 1.125 old
-----------------------------------
require("scripts/globals/aftermath")
require("scripts/globals/settings")
require("scripts/globals/status")
require("scripts/globals/weaponskills")
-----------------------------------
function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar)
local params = {}
params.numHits = 3
-- ftp damage mods (for Damage Varies with TP lines are calculated in the function
params.ftp100 = 1.125 params.ftp200 = 1.125 params.ftp300 = 1.125
-- wscs are in % so 0.2=20%
params.str_wsc = 0.3 params.dex_wsc = 0.0 params.vit_wsc = 0.0 params.agi_wsc = 0.0 params.int_wsc = 0.0
params.mnd_wsc = 0.5 params.chr_wsc = 0.0
-- critical mods, again in % (ONLY USE FOR critICAL HIT VARIES WITH TP)
params.crit100 = 0.0 params.crit200 = 0.0 params.crit300 = 0.0
params.canCrit = false
-- accuracy mods (ONLY USE FOR accURACY VARIES WITH TP) , should be the acc at those %s NOT the penalty values. Leave 0 if acc doesnt vary with tp.
params.acc100 = 0.0 params.acc200 = 0.0 params.acc300 = 0.0
-- attack multiplier (only some WSes use this, this varies the actual ratio value, see Tachi: Kasha) 1 is default.
params.atk100 = 1; params.atk200 = 1; params.atk300 = 1
if USE_ADOULIN_WEAPON_SKILL_CHANGES then
params.ftp100 = 4.0 params.ftp200 = 4.0 params.ftp300 = 4.0
end
-- Apply aftermath
tpz.aftermath.addStatusEffect(player, tp, tpz.slot.MAIN, tpz.aftermath.type.MYTHIC)
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, params, tp, action, primary, taChar)
if damage > 0 then
local duration = tp / 1000 * 20 - 5
if not target:hasStatusEffect(tpz.effect.MAGIC_EVASION_DOWN) then
target:addStatusEffect(tpz.effect.MAGIC_EVASION_DOWN, 10, 0, duration)
end
end
return tpHits, extraHits, criticalHit, damage
end
| 49.641509
| 180
| 0.665906
|
e0057f3ee0876a956169827b85f41d40dfdb7327
| 4,757
|
php
|
PHP
|
src/applications/slowvote/controller/PhabricatorSlowvoteCreateController.php
|
Two9A/phabricator
|
52fad54fb11d582e830ab61b4a0cd21b47592b9e
|
[
"Apache-2.0"
] | 1
|
2017-07-02T10:36:23.000Z
|
2017-07-02T10:36:23.000Z
|
src/applications/slowvote/controller/PhabricatorSlowvoteCreateController.php
|
kuk0/phabricator
|
62e039b74871542522a498373ee44d9f5074f0f9
|
[
"Apache-2.0"
] | null | null | null |
src/applications/slowvote/controller/PhabricatorSlowvoteCreateController.php
|
kuk0/phabricator
|
62e039b74871542522a498373ee44d9f5074f0f9
|
[
"Apache-2.0"
] | null | null | null |
<?php
/*
* Copyright 2012 Facebook, 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.
*/
/**
* @group slowvote
*/
final class PhabricatorSlowvoteCreateController
extends PhabricatorSlowvoteController {
public function processRequest() {
$request = $this->getRequest();
$user = $request->getUser();
$poll = new PhabricatorSlowvotePoll();
$poll->setAuthorPHID($user->getPHID());
$e_question = true;
$e_response = true;
$errors = array();
$responses = $request->getArr('response');
if ($request->isFormPost()) {
$poll->setQuestion($request->getStr('question'));
$poll->setResponseVisibility($request->getInt('response_visibility'));
$poll->setShuffle($request->getBool('shuffle', false));
$poll->setMethod($request->getInt('method'));
if (!strlen($poll->getQuestion())) {
$e_question = 'Required';
$errors[] = 'You must ask a poll question.';
} else {
$e_question = null;
}
$responses = array_filter($responses);
if (empty($responses)) {
$errors[] = 'You must offer at least one response.';
$e_response = 'Required';
} else {
$e_response = null;
}
if (empty($errors)) {
$poll->save();
foreach ($responses as $response) {
$option = new PhabricatorSlowvoteOption();
$option->setName($response);
$option->setPollID($poll->getID());
$option->save();
}
return id(new AphrontRedirectResponse())
->setURI('/V'.$poll->getID());
}
}
$error_view = null;
if ($errors) {
$error_view = new AphrontErrorView();
$error_view->setTitle('Form Errors');
$error_view->setErrors($errors);
}
$form = id(new AphrontFormView())
->setUser($user)
->appendChild(
'<p class="aphront-form-instructions">Resolve issues and build '.
'consensus through protracted deliberation.</p>')
->appendChild(
id(new AphrontFormTextControl())
->setLabel('Question')
->setName('question')
->setValue($poll->getQuestion())
->setError($e_question));
for ($ii = 0; $ii < 10; $ii++) {
$n = ($ii + 1);
$response = id(new AphrontFormTextControl())
->setLabel("Response {$n}")
->setName('response[]')
->setValue(idx($responses, $ii, ''));
if ($ii == 0) {
$response->setError($e_response);
}
$form->appendChild($response);
}
$poll_type_options = array(
PhabricatorSlowvotePoll::METHOD_PLURALITY => 'Plurality (Single Choice)',
PhabricatorSlowvotePoll::METHOD_APPROVAL => 'Approval (Multiple Choice)',
);
$response_type_options = array(
PhabricatorSlowvotePoll::RESPONSES_VISIBLE
=> 'Allow anyone to see the responses',
PhabricatorSlowvotePoll::RESPONSES_VOTERS
=> 'Require a vote to see the responses',
PhabricatorSlowvotePoll::RESPONSES_OWNER
=> 'Only I can see the responses',
);
$form
->appendChild(
id(new AphrontFormSelectControl())
->setLabel('Vote Type')
->setName('method')
->setValue($poll->getMethod())
->setOptions($poll_type_options))
->appendChild(
id(new AphrontFormSelectControl())
->setLabel('Responses')
->setName('response_visibility')
->setValue($poll->getResponseVisibility())
->setOptions($response_type_options))
->appendChild(
id(new AphrontFormCheckboxControl())
->setLabel('Shuffle')
->addCheckbox(
'shuffle',
1,
'Show choices in random order',
$poll->getShuffle()))
->appendChild(
id(new AphrontFormSubmitControl())
->setValue('Create Slowvote')
->addCancelButton('/vote/'));
$panel = new AphrontPanelView();
$panel->setWidth(AphrontPanelView::WIDTH_FORM);
$panel->setHeader('Create Slowvote');
$panel->appendChild($form);
return $this->buildStandardPageResponse(
array(
$error_view,
$panel,
),
array(
'title' => 'Create Slowvote',
));
}
}
| 29.006098
| 80
| 0.595543
|
df4d572016b9ec2d303707e3a5a32f67643f0675
| 806
|
cs
|
C#
|
MockWebApi/Middleware/GenericRouteTransformer.cs
|
mnemonic-bit/MockWebApi
|
60d3d32068e99a73c929868e04ca6f62998d7e3b
|
[
"MIT"
] | 1
|
2021-08-18T14:54:05.000Z
|
2021-08-18T14:54:05.000Z
|
MockWebApi/Middleware/GenericRouteTransformer.cs
|
mnemonic-bit/MockWebApi
|
60d3d32068e99a73c929868e04ca6f62998d7e3b
|
[
"MIT"
] | null | null | null |
MockWebApi/Middleware/GenericRouteTransformer.cs
|
mnemonic-bit/MockWebApi
|
60d3d32068e99a73c929868e04ca6f62998d7e3b
|
[
"MIT"
] | null | null | null |
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Routing;
using Microsoft.AspNetCore.Routing;
using System.Threading.Tasks;
namespace MockWebApi.Middleware
{
public class GenericRouteTransformer : DynamicRouteValueTransformer
{
public GenericRouteTransformer()
{
}
public override ValueTask<RouteValueDictionary> TransformAsync(HttpContext httpContext, RouteValueDictionary values)
{
if (!values.ContainsKey("some-key"))
{
return new ValueTask<RouteValueDictionary>(Task.FromResult(values));
}
values["controller"] = "WeatherForecast";
values["action"] = "Get";
return new ValueTask<RouteValueDictionary>(Task.FromResult(values));
}
}
}
| 27.793103
| 124
| 0.658809
|
dbd6953ba975015982b9dd45a26783b02c90519e
| 2,415
|
php
|
PHP
|
app/Http/Controllers/ProfileController.php
|
rinaldycodes/sayur-agus
|
806a417176e951e06bd29033f94eb2dbc6baeacf
|
[
"MIT"
] | null | null | null |
app/Http/Controllers/ProfileController.php
|
rinaldycodes/sayur-agus
|
806a417176e951e06bd29033f94eb2dbc6baeacf
|
[
"MIT"
] | null | null | null |
app/Http/Controllers/ProfileController.php
|
rinaldycodes/sayur-agus
|
806a417176e951e06bd29033f94eb2dbc6baeacf
|
[
"MIT"
] | null | null | null |
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Profile;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Hash;
use File;
use Illuminate\Support\Facades\Storage;
class ProfileController extends Controller
{
public function index()
{
$user = User::findOrFail(Auth::user()->id);
return view('profile.index', compact(
'user'
));
}
public function create()
{
//
}
public function store(Request $request)
{
//
}
public function show($id)
{
//
}
public function edit($id)
{
$user = User::findOrFail(Auth::user()->id);
return view('profile.edit', compact('user'));
}
public function update(Request $request, $id)
{
$request->validate([
'photo' => 'required|mimes:jpg,jpeg,png',
'name' => 'required',
],);
$user = User::find(Auth::user()->id);
$user->name = $request->name;
$user->save();
$profile = Profile::where('user_id', Auth::user()->id)->first();
$profile->user_id = Auth::user()->id;
Storage::disk('public')->delete($profile->photo);
$profile->photo = $request->file('photo')->store('images', 'public');
$profile->address = $request->address;
$profile->no_telp = $request->no_telp;
$profile->save();
return redirect('/profile');
}
public function destroy($id)
{
//
}
public function changePassword() {
return view('profile.change-password');
}
public function changePasswordProcess(Request $request , $id) {
$msg = [
'password.required' => "Password tidak boleh kosong",
'new_password.required' => "New Password tidak boleh kosong",
];
$request->validate([
'password' => 'required',
'new_password' => 'required|min:3',
], $msg);
if(Hash::check($request->password, Auth::user()->password)) {
$hashed = Hash::make($request->new_password);
$user = User::find(Auth::user()->id);
$user->password = $hashed;
$user->update();
return back()->with('message', 'Successfuly changed!');
}
return back()->with('message', 'Current Password does not match');
}
}
| 24.15
| 77
| 0.540787
|
c6c25c3f8a726090e9fc7b33b297c3e314db1069
| 1,249
|
rs
|
Rust
|
src/api/schema/metrics/sink/mod.rs
|
parampavar/vector
|
83bd797ff6a05fb3246a2442a701db3a85e323b5
|
[
"Apache-2.0"
] | null | null | null |
src/api/schema/metrics/sink/mod.rs
|
parampavar/vector
|
83bd797ff6a05fb3246a2442a701db3a85e323b5
|
[
"Apache-2.0"
] | null | null | null |
src/api/schema/metrics/sink/mod.rs
|
parampavar/vector
|
83bd797ff6a05fb3246a2442a701db3a85e323b5
|
[
"Apache-2.0"
] | null | null | null |
mod generic;
use async_graphql::Interface;
use super::{
EventsInTotal, EventsOutTotal, ProcessedBytesTotal, ProcessedEventsTotal, ReceivedEventsTotal,
SentEventsTotal,
};
use crate::event::Metric;
#[derive(Debug, Clone, Interface)]
#[graphql(
field(name = "processed_events_total", type = "Option<ProcessedEventsTotal>"),
field(name = "processed_bytes_total", type = "Option<ProcessedBytesTotal>"),
field(name = "received_events_total", type = "Option<ReceivedEventsTotal>"),
field(
name = "events_in_total",
type = "Option<EventsInTotal>",
deprecation = "Use received_events_total instead"
),
field(name = "sent_events_total", type = "Option<SentEventsTotal>"),
field(
name = "events_out_total",
type = "Option<EventsOutTotal>",
deprecation = "Use sent_events_total instead"
)
)]
pub enum SinkMetrics {
GenericSinkMetrics(generic::GenericSinkMetrics),
}
pub trait IntoSinkMetrics {
fn into_sink_metrics(self, component_type: &str) -> SinkMetrics;
}
impl IntoSinkMetrics for Vec<Metric> {
fn into_sink_metrics(self, _component_type: &str) -> SinkMetrics {
SinkMetrics::GenericSinkMetrics(generic::GenericSinkMetrics::new(self))
}
}
| 30.463415
| 98
| 0.703763
|
a4705a5fb50139761c3f07fa46f819d15ac0f8fc
| 199
|
php
|
PHP
|
resources/views/admin/channels/create.blade.php
|
pkboom/council
|
b86bfe96145e85c8a23968c3f5e47a6cb445f48b
|
[
"MIT"
] | null | null | null |
resources/views/admin/channels/create.blade.php
|
pkboom/council
|
b86bfe96145e85c8a23968c3f5e47a6cb445f48b
|
[
"MIT"
] | 8
|
2018-03-24T01:42:04.000Z
|
2018-04-12T18:06:56.000Z
|
resources/views/admin/channels/create.blade.php
|
pkboom/council
|
b86bfe96145e85c8a23968c3f5e47a6cb445f48b
|
[
"MIT"
] | 1
|
2018-03-26T06:50:44.000Z
|
2018-03-26T06:50:44.000Z
|
@extends('admin.layout.app')
@section('administration-content')
<form action="{{ route('admin.channels.store') }}" method="post">
@include('admin.channels._form')
</form>
@endsection
| 28.428571
| 69
| 0.658291
|
d8bc4d0fe92bcba95996580d281aa481c5ac1c73
| 9,850
|
kt
|
Kotlin
|
src/test/kotlin/de/debuglevel/pdfformfiller/form/FormClientTests.kt
|
debuglevel/pdfformfiller-microservice
|
1533a19f85d1c9358883b2d7ff52199fa6e540b6
|
[
"Unlicense"
] | 2
|
2021-02-23T21:54:34.000Z
|
2022-01-15T18:30:29.000Z
|
src/test/kotlin/de/debuglevel/pdfformfiller/form/FormClientTests.kt
|
debuglevel/pdfformfiller-microservice
|
1533a19f85d1c9358883b2d7ff52199fa6e540b6
|
[
"Unlicense"
] | 13
|
2020-09-04T16:27:31.000Z
|
2022-01-15T18:25:08.000Z
|
src/test/kotlin/de/debuglevel/pdfformfiller/form/FormClientTests.kt
|
debuglevel/pdfformfiller-microservice
|
1533a19f85d1c9358883b2d7ff52199fa6e540b6
|
[
"Unlicense"
] | null | null | null |
package de.debuglevel.pdfformfiller.form
import de.debuglevel.pdfformfiller.PdfUtils
import de.debuglevel.pdfformfiller.pdf.TestDataProvider
import de.debuglevel.pdfformfiller.withResponseOnException
import io.micronaut.http.BasicAuth
import io.micronaut.http.HttpStatus
import io.micronaut.http.MediaType
import io.micronaut.test.annotation.MicronautTest
import org.assertj.core.api.Assertions
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.TestInstance
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.MethodSource
import java.time.LocalDateTime
import java.time.temporal.ChronoUnit
import java.util.*
import javax.inject.Inject
import kotlin.io.path.ExperimentalPathApi
import kotlin.io.path.readBytes
@ExperimentalPathApi
@MicronautTest
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class FormClientTests {
fun formProvider() = TestDataProvider.formProvider()
fun filledFormProvider() = TestDataProvider.filledFormProvider()
private val basicAuth = BasicAuth("username", "password")
@Inject
lateinit var formClient: FormClient
@Test
fun `get form`() {
// Arrange
val minimalPdfBytes = PdfUtils.getMinimalPdf().toByteArray()
val addFormRequest = AddFormRequest(
pdfBase64 = Base64.getEncoder().encodeToString(minimalPdfBytes)
)
val addFormResponse = formClient.postOne(addFormRequest).body()!!
// Act
val httpResponse = formClient.getOne(addFormResponse.id)
// Assert
assertThat(httpResponse.status).isEqualTo(HttpStatus.OK)
assertThat(httpResponse.contentType.get()).isEqualTo(MediaType.APPLICATION_JSON_TYPE)
assertThat(httpResponse.contentLength).isGreaterThan(0)
val getFormResponse = httpResponse.body.get()
assertThat(getFormResponse.id).isNotNull
assertThat(Base64.getDecoder().decode(getFormResponse.pdfBase64)).isEqualTo(minimalPdfBytes)
assertThat(getFormResponse.createdOn).isNotNull
assertThat(getFormResponse.lastModifiedOn).isNotNull
}
@Test
fun `get form with an unknown id`() {
// Arrange
val unknownId = UUID.randomUUID()
// Act
val httpResponse = formClient.getOne(unknownId)
// Assert
assertThat(httpResponse.status).isEqualTo(HttpStatus.NOT_FOUND)
}
@Test
fun `get all forms`() {
// Arrange
formClient.deleteAll(basicAuth)
for (iteration in 1..10) {
// Arrange
val minimalPdfBytes = PdfUtils.getMinimalPdf().toByteArray()
val addFormRequest = AddFormRequest(
pdfBase64 = Base64.getEncoder().encodeToString(minimalPdfBytes)
)
val addFormResponse = formClient.postOne(addFormRequest).body()!!
// Act
val httpResponse = formClient.getList(basicAuth)
// Assert
assertThat(httpResponse.status).isEqualTo(HttpStatus.OK)
assertThat(httpResponse.contentType.get()).isEqualTo(MediaType.APPLICATION_JSON_TYPE)
assertThat(httpResponse.contentLength).isGreaterThan(0)
val getFormResponses = httpResponse.body.get()
assertThat(getFormResponses.size).isEqualTo(iteration)
assertThat(getFormResponses).allSatisfy { assertThat(it.id).isNotNull() }
assertThat(getFormResponses).allSatisfy { assertThat(it.createdOn).isNotNull() }
assertThat(getFormResponses).allSatisfy { assertThat(it.lastModifiedOn).isNotNull() }
}
}
@Test
fun `add form`() {
// Arrange
// Act
val minimalPdfBytes = PdfUtils.getMinimalPdf().toByteArray()
val addFormRequest = AddFormRequest(
pdfBase64 = Base64.getEncoder().encodeToString(minimalPdfBytes)
)
val httpResponse = formClient.postOne(addFormRequest)
val addFormResponse = httpResponse.body()!!
// Assert
assertThat(httpResponse.status).isEqualTo(HttpStatus.CREATED)
assertThat(httpResponse.contentType.get()).isEqualTo(MediaType.APPLICATION_JSON_TYPE)
assertThat(httpResponse.contentLength).isGreaterThan(0)
assertThat(httpResponse.header("Location")).contains(addFormResponse.id.toString())
val getFormResponse = formClient.getOne(addFormResponse.id).body.get()
assertThat(addFormResponse.id).isNotNull
assertThat(getFormResponse.id).isEqualTo(addFormResponse.id)
assertThat(Base64.getDecoder().decode(getFormResponse.pdfBase64)).isEqualTo(minimalPdfBytes)
assertThat(getFormResponse.createdOn).isCloseTo(LocalDateTime.now(), Assertions.within(2, ChronoUnit.SECONDS))
assertThat(getFormResponse.lastModifiedOn).isCloseTo(
LocalDateTime.now(),
Assertions.within(2, ChronoUnit.SECONDS)
)
}
@Test
fun `add invalid form`() {
// Arrange
// Act
val bytes = "foobar".toByteArray()
val addFormRequest = AddFormRequest(
pdfBase64 = Base64.getEncoder().encodeToString(bytes)
)
val httpResponse = withResponseOnException { formClient.postOne(addFormRequest) }
// Assert
assertThat(httpResponse.status).isEqualTo(HttpStatus.BAD_REQUEST)
}
@Test
fun `delete form`() {
// Arrange
formClient.deleteAll(basicAuth)
val minimalPdfBytes = PdfUtils.getMinimalPdf().toByteArray()
val addFormRequest = AddFormRequest(
pdfBase64 = Base64.getEncoder().encodeToString(minimalPdfBytes)
)
val addFormResponse = formClient.postOne(addFormRequest).body()!!
// Act
val httpResponse = formClient.deleteOne(addFormResponse.id)
// Assert
assertThat(httpResponse.status).isEqualTo(HttpStatus.NO_CONTENT)
assertThat(httpResponse.contentLength).isEqualTo(-1)
val getFormResponses = formClient.getList(basicAuth).body.get()
assertThat(getFormResponses.size).isEqualTo(0)
}
@Test
fun `delete form with unknown id`() {
// Arrange
val unknownId = UUID.randomUUID()
// Act
val httpResponse = formClient.deleteOne(unknownId)
// Assert
assertThat(httpResponse.status).isEqualTo(HttpStatus.NOT_FOUND)
}
@Test
fun `delete all forms`() {
// Arrange
formClient.deleteAll(basicAuth)
for (iteration in 1..10) {
val minimalPdfBytes = PdfUtils.getMinimalPdf().toByteArray()
val addFormRequest = AddFormRequest(
pdfBase64 = Base64.getEncoder().encodeToString(minimalPdfBytes)
)
val addFormResponse = formClient.postOne(addFormRequest).body()!!
}
// Act
val httpResponse = formClient.deleteAll(basicAuth)
// Assert
assertThat(httpResponse.status).isEqualTo(HttpStatus.NO_CONTENT)
assertThat(httpResponse.contentLength).isEqualTo(-1)
val getFormResponses = formClient.getList(basicAuth).body.get()
assertThat(getFormResponses.size).isEqualTo(0)
}
@ParameterizedTest
@MethodSource("filledFormProvider")
fun `get fields and values`(testFilledForm: TestDataProvider.TestFilledForm) {
// Arrange
val bytes = testFilledForm.pdfPath.readBytes()
val addFormRequest = AddFormRequest(
pdfBase64 = Base64.getEncoder().encodeToString(bytes)
)
val addFormResponse = formClient.postOne(addFormRequest).body()!!
// Act
val httpResponse = formClient.getOne(addFormResponse.id)
// Assert
assertThat(httpResponse.status).isEqualTo(HttpStatus.OK)
assertThat(httpResponse.contentType.get()).isEqualTo(MediaType.APPLICATION_JSON_TYPE)
assertThat(httpResponse.contentLength).isGreaterThan(0)
val getFormResponse = httpResponse.body.get()
assertThat(getFormResponse.id).isNotNull
assertThat(Base64.getDecoder().decode(getFormResponse.pdfBase64)).isEqualTo(bytes)
assertThat(getFormResponse.values).containsExactlyInAnyOrderEntriesOf(testFilledForm.expectedFieldValues)
assertThat(getFormResponse.createdOn).isNotNull
assertThat(getFormResponse.lastModifiedOn).isNotNull
}
// @Test
// fun `update form`() {
// // Arrange
// val minimalPdfBytes = PdfUtils.getMinimalPdf().toByteArray()
// val form = Form(id = null, pdf = minimalPdfBytes)
// val addedForm = service.add(form)
//
// val retrievedForm = service.get(addedForm.id!!)
//
// // Act
// val updatedPdfBytes = minimalPdfBytes.plus("updated".toByteArray())
// retrievedForm.pdf = updatedPdfBytes
// val updatedForm = service.update(retrievedForm.id!!, retrievedForm)
//
// // Assert
// val retrieved2Form = service.get(addedForm.id!!)
// setOf(updatedForm, retrieved2Form).forEach {
// assertThat(it.id).isNotNull
// assertThat(it.pdf).isEqualTo(updatedPdfBytes)
// assertThat(it.createdOn).isCloseTo(LocalDateTime.now(), Assertions.within(2, ChronoUnit.SECONDS))
// assertThat(it.lastModifiedOn).isCloseTo(LocalDateTime.now(), Assertions.within(2, ChronoUnit.SECONDS))
// assertThat(it.lastModifiedOn).isAfter(retrievedForm.createdOn)
// }
// }
// @Test
// fun `update form with unknown id`() {
// // Arrange
// val unknownId = UUID.randomUUID()
//
// val form = Form(
// id = unknownId,
// pdf = PdfUtils.getMinimalPdf().toByteArray(),
// )
//
// // Act
// val exception = assertThrows<FormService.FormNotFoundException> { service.update(unknownId, form) }
// }
}
| 37.030075
| 118
| 0.677665
|
38d1cb51c0b3db7bd90c47ec50d1963d7b70863d
| 2,170
|
php
|
PHP
|
Services/NativeAjax/AbstractWPAjaxController.php
|
ProklUng/wp.symfony.router.bundle
|
b66d8fbdad57b3f2abd92d8a1dc9f5198fae1841
|
[
"MIT"
] | 1
|
2021-04-26T14:46:21.000Z
|
2021-04-26T14:46:21.000Z
|
Services/NativeAjax/AbstractWPAjaxController.php
|
ProklUng/wp.symfony.router.bundle
|
b66d8fbdad57b3f2abd92d8a1dc9f5198fae1841
|
[
"MIT"
] | null | null | null |
Services/NativeAjax/AbstractWPAjaxController.php
|
ProklUng/wp.symfony.router.bundle
|
b66d8fbdad57b3f2abd92d8a1dc9f5198fae1841
|
[
"MIT"
] | null | null | null |
<?php
namespace Prokl\WpSymfonyRouterBundle\Services\NativeAjax;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* Class AbstractWPAjaxController
* @package Prokl\WpSymfonyRouterBundle\Services\NativeAjax
*/
class AbstractWPAjaxController extends AbstractController
{
/**
* @var Request $request Request.
*/
protected $request;
/**
* AbstractWPAjaxController constructor.
*
* @param Request|null $request Request.
*/
public function __construct(?Request $request = null)
{
$this->request = $request;
if ($request === null) {
$this->request = Request::createFromGlobals();
}
$action = $this->request->query->get('action');
$uri = $this->request->server->get('SCRIPT_NAME', '');
// Игонорировать /wp-admin/admin.php. Иначе вызывает ложные срабатывания
// И ошибки.
if ($action && strpos($uri, '/wp-admin/') === false) {
$routeData = WpAjaxInitializer::route($action);
$this->request->attributes->set('methods', $routeData->getMethods());
$this->request->attributes->set('requirements', $routeData->getRequirements());
$this->request->attributes->set('defaults', $routeData->getDefaults());
$this->request->attributes->set('options', $routeData->getOptions());
}
}
/**
* Валидный тип запроса?
*
* @param string $message Сообщение.
* @param integer $statusCode HTTP status code.
*
* @return void
*/
protected function checkTypeRequest(string $message = '', int $statusCode = 400) : void
{
$methods = $this->request->attributes->get('methods');
if (!$methods) {
return;
}
$requestMethod = $this->request->getMethod();
if (!in_array($requestMethod, $methods, true)) {
$response = new Response(
$message,
$statusCode
);
$response->send();
wp_die();
}
}
}
| 28.933333
| 91
| 0.591705
|
e001780f2de89804c55fd0be2fbd97aa86f646b6
| 1,075
|
php
|
PHP
|
app/Services/Api/Json/ResponseMacro/EventResponseMacro.php
|
ssahlasAPEM/APEM
|
1b9d03bbc5558e20fc8f810372bad9c3ff84558f
|
[
"MIT"
] | null | null | null |
app/Services/Api/Json/ResponseMacro/EventResponseMacro.php
|
ssahlasAPEM/APEM
|
1b9d03bbc5558e20fc8f810372bad9c3ff84558f
|
[
"MIT"
] | null | null | null |
app/Services/Api/Json/ResponseMacro/EventResponseMacro.php
|
ssahlasAPEM/APEM
|
1b9d03bbc5558e20fc8f810372bad9c3ff84558f
|
[
"MIT"
] | null | null | null |
<?php namespace app\Services\Api\Json\ResponseMacro;
/**
* Created by Curious Minds Media.
* User: Andrew Engstrom (andrew@curiousm.com)
* Date: 8/13/16
* Time: 3:29 PM
*/
use app\Core\Event\Model\Event;
use Illuminate\Support\Facades\URL;
/**
* Class FieldResponseMacro
* @package app\Services\Api\Json\ResponseMacro
*/
class EventResponseMacro extends AbstractResponseMacro
{
/**
* @return string
*/
public function responseType()
{
return 'event';
}
public function targetClass()
{
return Event::class;
}
/**
* @param $serviceResponse
*
* @return \stdClass
*/
protected function relationships($serviceResponse)
{
$relationships = new \stdClass();
$relationships->opportunity = new \stdClass();
$relationships->opportunity->links = new \stdClass();
$relationships->opportunity->links->related = URL::to('/') . "/api/v1/opportunities/" . $serviceResponse->getOpportunityId();
return $relationships;
}
}
| 21.938776
| 133
| 0.619535
|
8311176af67cb663999cec055f2a94280f6a61ff
| 3,850
|
ts
|
TypeScript
|
src/lib/tree/LiteralCommandNode.ts
|
mat-1/brigadier
|
7f85e218521ce3dbb859299c8ebe74c4d4ee3d0f
|
[
"MIT"
] | 8
|
2019-09-24T10:04:03.000Z
|
2022-03-11T02:49:19.000Z
|
src/lib/tree/LiteralCommandNode.ts
|
mat-1/brigadier
|
7f85e218521ce3dbb859299c8ebe74c4d4ee3d0f
|
[
"MIT"
] | 2
|
2020-05-05T17:11:34.000Z
|
2020-05-05T17:40:48.000Z
|
src/lib/tree/LiteralCommandNode.ts
|
mat-1/brigadier
|
7f85e218521ce3dbb859299c8ebe74c4d4ee3d0f
|
[
"MIT"
] | 6
|
2020-05-06T14:49:00.000Z
|
2021-05-05T23:29:09.000Z
|
import Command from "../Command"
import CommandNode from "./CommandNode"
import Predicate from "../Predicate"
import RedirectModifier from "../RedirectModifier"
import StringReader from "../StringReader"
import LiteralArgumentBuilder from "../builder/LiteralArgumentBuilder"
import CommandContext from "../context/CommandContext"
import CommandContextBuilder from "../context/CommandContextBuilder"
import StringRange from "../context/StringRange"
import CommandSyntaxException from "../exceptions/CommandSyntaxException"
import Suggestions from "../suggestion/Suggestions"
import SuggestionsBuilder from "../suggestion/SuggestionsBuilder"
export default class LiteralCommandNode<S> extends CommandNode<S> {
private literal: string;
public constructor(literal: string, command: Command<S>, requirement: Predicate<S>, redirect: CommandNode<S>, modifier: RedirectModifier<S>, forks: boolean) {
super(command, requirement, redirect, modifier, forks);
this.literal = literal;
}
public getNodeType(): string {
return "literal"
}
public getLiteral(): string {
return this.literal;
}
public getName(): string {
return this.literal;
}
public parse(reader: StringReader, contextBuilder: CommandContextBuilder<S>) {
let start = reader.getCursor();
let end = this.__parse(reader);
if (end > -1) {
contextBuilder.withNode(this, StringRange.between(start, end));
return;
}
throw CommandSyntaxException.BUILT_IN_EXCEPTIONS.literalIncorrect().createWithContext(reader, this.literal);
}
private __parse(reader: StringReader): number {
let start = reader.getCursor();
if (reader.canRead(this.literal.length)) {
let end = start + this.literal.length;
if (reader.getString().substring(start, end) === this.literal) {
reader.setCursor(end);
if (!reader.canRead() || reader.peek() == ' ') {
return end;
}
else {
reader.setCursor(start);
}
}
}
return -1;
}
public listSuggestions(context: CommandContext<S>, builder: SuggestionsBuilder): Promise<Suggestions> {
if (this.literal.toLowerCase().startsWith(builder.getRemaining().toLowerCase())) {
return builder.suggest(this.literal).buildPromise();
}
else {
return Suggestions.empty();
}
}
public isValidInput(input: string): boolean {
return this.__parse(new StringReader(input)) > -1;
}
public equals(o: object): boolean {
if (this === o) return true;
if (!(o instanceof LiteralCommandNode)) return false;
if (!(this.literal === o.literal)) return false;
return super.equals(o);
}
public getUsageText(): string {
return this.literal;
}
public createBuilder(): LiteralArgumentBuilder<S> {
let builder: LiteralArgumentBuilder<S> = LiteralArgumentBuilder.literal(this.literal);
builder.requires(this.getRequirement());
builder.forward(this.getRedirect(), this.getRedirectModifier(), this.isFork());
if (this.getCommand() != null)
builder.executes(this.getCommand());
return builder;
}
public getSortedKey(): string {
return this.literal;
}
public getExamples(): Iterable<string> {
return [ this.literal ];
}
public toString(): string {
return "<literal " + this.literal + ">";
}
}
| 34.375
| 163
| 0.595325
|
e7153685c437fb29fb1be4569140b5d3294e0b5f
| 947
|
php
|
PHP
|
tests/Fixtures/Taxonomies/Basic_Hierarchical_Taxonomy.php
|
Pink-Crab/pc_registerables
|
0e94fe50bd326d1838128864fe86bf11ce603e2e
|
[
"MIT"
] | 1
|
2021-12-11T14:49:28.000Z
|
2021-12-11T14:49:28.000Z
|
tests/Fixtures/Taxonomies/Basic_Hierarchical_Taxonomy.php
|
Pink-Crab/pc_registerables
|
0e94fe50bd326d1838128864fe86bf11ce603e2e
|
[
"MIT"
] | 12
|
2021-05-08T10:42:58.000Z
|
2022-01-20T14:15:05.000Z
|
tests/Fixtures/Taxonomies/Basic_Hierarchical_Taxonomy.php
|
Pink-Crab/pc_registerables
|
0e94fe50bd326d1838128864fe86bf11ce603e2e
|
[
"MIT"
] | null | null | null |
<?php
declare(strict_types=1);
/**
* Basic simple, Hierarchical taxonomy.
*
* @since 0.2.0
* @author Glynn Quelch <glynn.quelch@gmail.com>
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @package PinkCrab\Registerables
*/
namespace PinkCrab\Registerables\Tests\Fixtures\Taxonomies;
use PinkCrab\Registerables\Taxonomy;
class Basic_Hierarchical_Taxonomy extends Taxonomy {
public $slug = 'basic_hier_tax';
public $singular = 'Basic Hier Taxonomy';
public $plural = 'Basic Hier Taxonomies';
public $description = 'The Basic Hier Taxonomy.';
public $hierarchical = true;
public $object_type = array( 'basic_cpt', 'page' );
public $public = false;
public $show_ui = false;
public $show_in_menu = false;
public $show_admin_column = false;
public $show_tagcloud = false;
public $show_in_quick_edit = false;
}
| 30.548387
| 76
| 0.671595
|
d814f8b76e0adf2b7874b62b43d406194bf204d4
| 1,053
|
swift
|
Swift
|
mac/Bagel/Workers/BagelController/Common/BagelExtensions.swift
|
ThangaAyyanar/Bagel
|
2b1fdc5788a685000af443cb94c5c9989aa9f139
|
[
"Apache-2.0"
] | 4,036
|
2017-06-06T07:59:32.000Z
|
2022-03-30T15:58:56.000Z
|
mac/Bagel/Workers/BagelController/Common/BagelExtensions.swift
|
mran3/Bagel
|
5cc29babbb9161cc5fe9c7777254e5d5afbe2f02
|
[
"Apache-2.0"
] | 60
|
2018-11-07T12:47:06.000Z
|
2022-02-23T15:30:12.000Z
|
mac/Bagel/Workers/BagelController/Common/BagelExtensions.swift
|
mran3/Bagel
|
5cc29babbb9161cc5fe9c7777254e5d5afbe2f02
|
[
"Apache-2.0"
] | 309
|
2018-11-07T12:01:59.000Z
|
2022-03-24T08:36:04.000Z
|
//
// BagelExtensions.swift
// Bagel
//
// Created by Yagiz Gurgul on 21.10.2018.
// Copyright © 2018 Yagiz Lab. All rights reserved.
//
import Cocoa
extension String {
var base64Data: Data? {
return Data(base64Encoded: self, options: .ignoreUnknownCharacters)
}
}
extension URL {
func toKeyValueArray() -> [KeyValue] {
var array = [KeyValue]()
if let queryItems = URLComponents(url: self, resolvingAgainstBaseURL: false)?.queryItems {
for queryItem in queryItems {
array.append(KeyValue(key: queryItem.name, value: queryItem.value))
}
}
return array
}
}
extension Dictionary where Key == String, Value == String {
func toKeyValueArray() -> [KeyValue] {
var array = [KeyValue]()
for key in self.keys {
array.append(KeyValue(key: key, value: self[key]))
}
return array
}
}
| 20.647059
| 98
| 0.532764
|
b00b2ce13b72f7b45c0aeb5900744ebe59160bfc
| 1,482
|
py
|
Python
|
students/models.py
|
wjarczak/WSB-CRUD
|
fe866bf848cb06e9b747ab649ef6f821e06b613e
|
[
"MIT"
] | null | null | null |
students/models.py
|
wjarczak/WSB-CRUD
|
fe866bf848cb06e9b747ab649ef6f821e06b613e
|
[
"MIT"
] | null | null | null |
students/models.py
|
wjarczak/WSB-CRUD
|
fe866bf848cb06e9b747ab649ef6f821e06b613e
|
[
"MIT"
] | null | null | null |
from django.db import models
from django.core.validators import MinValueValidator, MaxValueValidator
class Representative(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
class Student(models.Model): # If required delete blank=True
DEPARTMENTS = (
('CS','Computer Science'),
('ACC','Accounting'),
('GF','Games&Fun'),
)
first_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=20)
identityNumber = models.CharField(max_length=10, blank=True) # Can be changed to Float
address = models.CharField(max_length=200, blank=True)
department = models.CharField(max_length=3, choices=DEPARTMENTS)
average_grade = models.FloatField(blank=True, null=True, validators=[MinValueValidator(0), MaxValueValidator(5)])
representative = models.ForeignKey(Representative, blank=True, null=True, on_delete=models.CASCADE)
def __str__(self):
if self.identityNumber:
return f"{self.first_name} ({self.identityNumber})"
return self.first_name
def get_fields(self):
return [(field.verbose_name, field.value_from_object(self))
if field.verbose_name != 'representative'
else
(field.verbose_name,
Representative.objects.get(pk=field.value_from_object(self)).name)
for field in self.__class__._meta.fields[1:]
]
| 36.146341
| 117
| 0.672065
|
8ed0ef7b578520da013f30d1bc518c9f93a670e2
| 988
|
js
|
JavaScript
|
lib/services/base-service.js
|
garrylachman/node-my-public-ip
|
b4fb58a9137def5477a439be0f5f0f2bfab4efa4
|
[
"MIT"
] | null | null | null |
lib/services/base-service.js
|
garrylachman/node-my-public-ip
|
b4fb58a9137def5477a439be0f5f0f2bfab4efa4
|
[
"MIT"
] | null | null | null |
lib/services/base-service.js
|
garrylachman/node-my-public-ip
|
b4fb58a9137def5477a439be0f5f0f2bfab4efa4
|
[
"MIT"
] | null | null | null |
const needle = require('needle');
const response = require('../response');
module.exports = class BaseService {
get methods() {
return {
'POST': 'post',
'GET': 'get',
};
}
get defaults() {
return {
'method': this.methods.POST,
'url': void 0,
};
}
constructor(options = {}) {
if (new.target == BaseService) {
throw new TypeError("Cannot construct Abstract directly");
}
this.options = Object.assign(this.defaults, options);
this.response = new response();
}
run() {
return new Promise((resolve, reject) => {
this.send()
.then((data) => {
try {
resolve(this.parse(data));
} catch (e) {
reject(e);
}
})
.catch((err) => reject(err));
});
}
send() {
return new Promise((resolve, reject) => {
needle[this.options.method](this.options.url, {
timeout: 10*1000
},
(err, res, body) => {
if (err) {
reject(err);
} else {
resolve(body);
}
});
});
}
parse(data) {
}
}
| 17.963636
| 61
| 0.548583
|
1b6d355014de24ee483552ed89817deb456371d9
| 9,374
|
rb
|
Ruby
|
bot/navigation.rb
|
telegraph-ai/bot
|
d28f45ae9263e9d3952d01a678893591f22c85f7
|
[
"Apache-2.0"
] | null | null | null |
bot/navigation.rb
|
telegraph-ai/bot
|
d28f45ae9263e9d3952d01a678893591f22c85f7
|
[
"Apache-2.0"
] | null | null | null |
bot/navigation.rb
|
telegraph-ai/bot
|
d28f45ae9263e9d3952d01a678893591f22c85f7
|
[
"Apache-2.0"
] | null | null | null |
# encoding: utf-8
=begin
LaPrimaire.org Bot helps french citizens participate to LaPrimaire.org
Copyright 2016 Telegraph-ai
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.
=end
module Bot
class Navigation
class << self
attr_accessor :nav
end
# loads all screens
def self.load_addons
Dir[File.expand_path('../../bot/addons/*.rb', __FILE__)].sort.each do |f|
require f
end
end
def initialize
@users = Bot::Users.new()
@web = Bot::Web.new()
@geo = Bot::Geo.new()
@candidates = Bot::Candidates.new()
@answers = {}
@keyboards = {}
@screens=Bot.screens
@screens.each do |k,v|
v.each do |k1,v1|
if (!v1[:kbd].nil?) then
@keyboards[self.path([k,k1])]=[]
end
if (!v1[:answer].nil?) then
@answers[v1[:answer]]={} if @answers[v1[:answer]].nil?
raise "Conflict of answers detected in add-on \"#{k}\" : \"#{v1[:answer]}\"" if not @answers[v1[:answer]][k].nil?
@answers[v1[:answer]][k]=k1
end
end
end
@keyboards.each do |k,v|
t=nil
n1,n2=self.nodes(k).map &:to_sym
size=@screens[n1][n2][:kbd].length
@screens[n1][n2][:kbd].each_with_index do |u,i|
m1,m2=self.nodes(u).map &:to_sym
item=@screens[m1][m2][:answer]
@keyboards[k].push(item)
end
@answers.freeze
@screens.freeze
@keyboards.freeze
end
end
def path(nodes)
nodes.join('/') unless nodes.nil?
end
def nodes(path)
path.split('/',2).map &:to_sym unless path.nil?
end
def context(path)
path.split('/',2)[0] unless path.nil?
end
def to_callback(path)
path.split('/',2).join('_') unless path.nil?
end
def get(msg,update_id)
res,options=nil
user=@users.open_user_session(msg.from,msg.date)
# we check that this message has not already been answered (i.e. telegram sending a msg we already processed)
return nil,nil if @users.already_answered(user[:id],update_id) and not DEBUG
session=user['session']
Bot.log.info "user read session : #{user}"
if user['bot_upgrade'].to_i==1 and not update_id==-1 then
Bot.log.warn "Bot upgrade detected"
update_id=-1
msg.text='api/bot_upgrade'
end
if update_id==-1 then # msg comes from api and not from telegram
api_cb,api_payload=msg.text.split("\n",2).each {|x| x.strip!}
raise "no callback given" if api_cb.nil?
@users.next_answer(user[:id],'free_text',1,api_cb)
session=@users.update_session(user[:id],{'api_payload'=>api_payload}) if !api_payload.nil?
end
input=session['expected_input']
session['current']="home/welcome" if RESET_WORDS.include?(msg.text)
if (input=='answer' or RESET_WORDS.include?(msg.text)) then # we expect the user to have used the proposed keyboard to answer
screen=self.find_by_answer(msg.text,self.context(session['current']))
if not screen.nil? then
res,options=get_screen(screen,user,msg)
user['session']=@users.get_session(user[:id])
current=user['session']['current']
screen=self.find_by_name(current) if screen[:id]!=current and !current.nil?
jump_to=screen[:jump_to]
while !jump_to.nil? do
next_screen=find_by_name(jump_to)
a,b=get_screen(next_screen,user,msg)
user['session']=@users.get_session(user[:id])
res="" unless res
res+=a unless a.nil?
options.merge!(b) unless b.nil?
jump_to=next_screen[:jump_to]
end
else
if not user['settings']['actions']['first_help_given'] and not IGNORE_CONTEXT.include?(self.context(user['session']['current'])) then
screen=self.find_by_name("help/first_help")
else
res,options=self.dont_understand(user,msg)
end
end
else # we expect the user to have answered by typing text manually
callback=self.to_callback(session['callback'].to_s)
if input=='free_text' and self.respond_to?(callback) then
if session['expected_input_size']>0 then
input_size=session['expected_input_size']-1
buffer= msg.text.nil? ? session['buffer'] : session['buffer']+msg.text
session=@users.update_session(user[:id],{'buffer'=>buffer})
screen=self.find_by_name(session['callback'])
session_update={'expected_input_size'=>input_size}
session_update['callback']=nil if input_size==0
session=@users.update_session(user[:id],session_update)
user['session']=session
res,options=self.method(callback).call(msg,user,screen) if input_size==0
screen=self.find_by_name(session['current']) if session['current']
jump_to=screen[:jump_to]
while !jump_to.nil? do
next_screen=find_by_name(jump_to)
user['session']=@users.get_session(user[:id])
a,b=get_screen(next_screen,user,msg)
res+=a unless a.nil?
options.merge!(b) unless b.nil?
user['session']=@users.get_session(user[:id])
current=user['session']['current']
next_screen=self.find_by_name(current) if next_screen[:id]!=current and !current.nil?
jump_to=next_screen[:jump_to]
end
end
end
end
res,options=self.dont_understand(user,msg) if res.nil? # something is fishy
Bot.log.info "user save session : #{@users.get_session(user[:id])}"
@users.close_user_session(user[:id])
return res,options
end
def dont_understand(user,msg,reset=false)
# dedicated method to not affect user session
Bot.log.info "dont_understand: #{msg}"
if not user['settings']['actions']['first_help_given'] then
screen=self.find_by_name("help/first_help")
res,options=self.format_answer(screen,user)
callback=self.to_callback(screen[:callback].to_s)
self.method(callback).call(msg,user,screen) if self.respond_to?(callback)
else
screen=self.find_by_name("system/dont_understand")
res,options=self.format_answer(screen,user)
end
return res,options
end
def get_screen(screen,user,msg)
Bot.log.info "get_screen: #{screen}"
res,options=nil
return nil,nil if screen.nil?
callback=self.to_callback(screen[:callback].to_s) unless screen[:callback].nil?
previous=caller_locations(1,1)[0].label
session_update={ 'current'=>screen[:id] }
unless IGNORE_CONTEXT.include?(self.context(screen[:id])) then
session_update['previous_screen']=screen
backup_session=user['session'].clone
backup_session.delete('previous_session')
backup_session.delete('previous_screen')
session_update['previous_session']=backup_session
end
@users.update_session(user[:id],session_update)
if !callback.nil? && previous!=callback && self.respond_to?(callback)
res,options=self.method(callback).call(msg,user,screen.clone)
else
res,options=self.format_answer(screen.clone,user)
end
return res,options
end
def find_by_name(name)
Bot.log.info "find_by_name: #{name}"
n1,n2=self.nodes(name)
begin
screen=@screens[n1][n2]
if screen then
screen[:id]=name
screen=screen.clone
end
rescue
screen=nil
end
return screen
end
def find_by_answer(answer,ctx=nil)
Bot.log.info "find_by_answer: #{answer} context: #{ctx}"
tmp=@answers[answer]
return nil if tmp.nil?
if tmp.length==1
ctx,screen_id=tmp.flatten
else
screen_id=tmp[ctx.to_sym]
end
Bot.log.error("find_by_answer: screen for #{answer} not found") if screen_id.nil?
screen=@screens[ctx.to_sym][screen_id]
if screen then
screen[:id]=self.path([ctx,screen_id])
screen=screen.clone
end
return screen
end
def format_answer(screen,user)
Bot.log.info "format_answer: #{screen[:id]}"
res=screen[:text] % {firstname: user['firstname'],lastname: user['lastname'],id: user[:id],username: user['username']} unless screen.nil? or screen[:text].nil?
options={}
kbd=@keyboards[screen[:id]].clone if @keyboards[screen[:id]]
if screen[:kbd_del] then
screen[:kbd_del].each do |k|
n1,n2=self.nodes(k)
kbd.delete(@screens[n1][n2][:answer])
end
end
screen[:kbd_add].each { |k| kbd.unshift(k) } if screen[:kbd_add]
if not kbd.nil? then
if kbd.length>1 and not screen[:kbd_vertical] then # display keyboard on several rows
newkbd=[]
row=[]
kbd.each_with_index do |r,i|
idx=i+1
row.push(r)
if (idx%2)==0 then
newkbd.push(row)
row=[]
end
end
newkbd.push(row) if row
kbd=newkbd
end
options[:kbd]=Telegram::Bot::Types::ReplyKeyboardMarkup.new(
keyboard:kbd,
resize_keyboard:screen[:kbd_options][:resize_keyboard],
one_time_keyboard:screen[:kbd_options][:one_time_keyboard],
selective:screen[:kbd_options][:selective]
)
end
options[:disable_web_page_preview]=true if screen[:disable_web_page_preview]
options[:groupsend]=true if screen[:groupsend]
options[:parse_mode]=screen[:parse_mode] if screen[:parse_mode]
options[:keep_kbd]=true if screen[:keep_kbd]
return res,options
end
end
end
| 33.719424
| 162
| 0.679966
|
e2963406c5a4d72c9dfa6f3977161553d5b9972e
| 786
|
js
|
JavaScript
|
src/input/dragActionManager.js
|
bildepunkt/spritewerk
|
b815ba922e9771ec5fe603cd8a935d40f63a1b63
|
[
"0BSD"
] | 2
|
2016-09-29T22:24:50.000Z
|
2017-09-04T18:11:49.000Z
|
src/input/dragActionManager.js
|
bildepunkt/spritewerk
|
b815ba922e9771ec5fe603cd8a935d40f63a1b63
|
[
"0BSD"
] | null | null | null |
src/input/dragActionManager.js
|
bildepunkt/spritewerk
|
b815ba922e9771ec5fe603cd8a935d40f63a1b63
|
[
"0BSD"
] | null | null | null |
/**
* Handles actions to take on targets to drag
* @module dragActionManager
*/
export default {
dragee: null,
offset: {
x: 0,
y: 0
},
handle (event) {
switch (event.type) {
case "dragstart":
if (event.target && event.target.draggable) {
this.dragee = event.target;
this.offset.x = event.x - this.dragee.x;
this.offset.y = event.y - this.dragee.y;
}
break;
case "drag":
if (this.dragee) {
this.dragee.x = event.x - this.offset.x;
this.dragee.y = event.y - this.offset.y;
}
break;
case "dragend":
this.dragee = null;
break;
}
}
};
| 23.818182
| 57
| 0.452926
|
02a53a62b1405396c37f4ef32977b172e8bb6076
| 1,573
|
cpp
|
C++
|
adopt_lock/adopt_lock.cpp
|
giorgiozoppi/cppconcurrency
|
7c19f780f5649cd048467a013e42948e5ba2efd5
|
[
"MIT"
] | null | null | null |
adopt_lock/adopt_lock.cpp
|
giorgiozoppi/cppconcurrency
|
7c19f780f5649cd048467a013e42948e5ba2efd5
|
[
"MIT"
] | null | null | null |
adopt_lock/adopt_lock.cpp
|
giorgiozoppi/cppconcurrency
|
7c19f780f5649cd048467a013e42948e5ba2efd5
|
[
"MIT"
] | null | null | null |
#include <mutex>
#include <thread>
#include <iostream>
class BankAccount {
public:
explicit BankAccount(int balance): balance(balance) {}
int getBalance() { return balance; }
friend void transfer(BankAccount* fromAcc, BankAccount* toAcc, int amount);
private:
int balance;
std::mutex m;
};
void transfer(BankAccount* fromAcc, BankAccount* toAcc, int amount) {
// first two mutexes are locked
std::lock(fromAcc->m, toAcc->m);
// two lock_guard instances are constructed, one for each mutex
// std::adopt_lock parameter specifies that mutexes are already
// locked, and they should just adopt the ownership of the existing
// lock on the mutex rather than attempt to lock the mutex in the
// constructor.
std::lock_guard<std::mutex> lock1(fromAcc->m, std::adopt_lock);
std::lock_guard<std::mutex> lock2(toAcc->m, std::adopt_lock);
fromAcc->balance -= amount;
toAcc->balance += amount;
}
int main() {
BankAccount person1(100);
BankAccount person2(200);
std::cout << "Balance person1: " << person1.getBalance() << std::endl;
std::cout << "Balance person2: " << person2.getBalance() << std::endl;
std::thread t1(transfer, &person1, &person2, 50);
std::thread t2(transfer, &person2, &person1, 20);
if (t1.joinable()) t1.join();
if (t2.joinable()) t2.join();
std::cout << "Balance person1 after transfer: " <<
person1.getBalance() << std::endl;
std::cout << "Balance person2 after transfer: " <<
person2.getBalance() << std::endl;
return 0;
}
| 30.843137
| 79
| 0.656707
|
da7af2c1f9e8b0de4eecd12129f0c4289414e8c2
| 1,385
|
php
|
PHP
|
90 - TesslerToys/tables.php
|
wmeints/Tessler
|
c6cf7ea28dca983512033eac5c2b2a9526a1ba98
|
[
"Apache-2.0"
] | null | null | null |
90 - TesslerToys/tables.php
|
wmeints/Tessler
|
c6cf7ea28dca983512033eac5c2b2a9526a1ba98
|
[
"Apache-2.0"
] | null | null | null |
90 - TesslerToys/tables.php
|
wmeints/Tessler
|
c6cf7ea28dca983512033eac5c2b2a9526a1ba98
|
[
"Apache-2.0"
] | null | null | null |
<?php include('shared/_header.php'); ?>
<h1>Tables</h1>
<p>Tables are somewhat tricky to select, since they can contain multiple rows. The trick is to have one column, or a set of columns, that uniquely identify the row.</p>
<h4>Tables</h4>
<table id="products" class="table">
<tr>
<th style="width: 40px;">Id</th>
<th>Name</th>
<th style="width: 100px;">Price</th>
<th style="width: 100px;">In stock</th>
</tr>
<tr>
<td>1</td>
<td>Space scooter</td>
<td>40,00</td>
<td>14</td>
</tr>
<tr>
<td>2</td>
<td>Lego technic truck</td>
<td>55,00</td>
<td>23</td>
</tr>
<tr>
<td>3</td>
<td>Cars puzzel</td>
<td>10,99</td>
<td>12</td>
</tr>
<tr>
<td>4</td>
<td>Pokemon X 3DS</td>
<td>49,99</td>
<td>17</td>
</tr>
</table>
<h4>Empty table</h4>
<table id="empty-table" class="table">
<thead>
<tr>
<th style="width: 40px;">Id</th>
<th>Name</th>
<th style="width: 100px;">Price</th>
<th style="width: 100px;">In stock</th>
</tr>
</thead>
</table>
<h4>One element</h4>
<table id="one-element" class="table">
<thead>
<tr>
<th style="width: 40px;">Id</th>
<th>Name</th>
<th style="width: 100px;">Price</th>
<th style="width: 100px;">In stock</th>
</tr>
</thead>
<tbody>
<tr>
<td>40</td>
<td>First element</td>
<td>100,20</td>
<td>Yes</td>
</tr>
</tbody>
</table>
<?php include('shared/_footer.php'); ?>
| 19.236111
| 168
| 0.576895
|
1b78ee0a219f7087b6d59aa4143640a4d6cd43fa
| 446
|
lua
|
Lua
|
Task/Sorting-algorithms-Cocktail-sort/Lua/sorting-algorithms-cocktail-sort-1.lua
|
LaudateCorpus1/RosettaCodeData
|
9ad63ea473a958506c041077f1d810c0c7c8c18d
|
[
"Info-ZIP"
] | 1
|
2018-11-09T22:08:38.000Z
|
2018-11-09T22:08:38.000Z
|
Task/Sorting-algorithms-Cocktail-sort/Lua/sorting-algorithms-cocktail-sort-1.lua
|
seanwallawalla-forks/RosettaCodeData
|
9ad63ea473a958506c041077f1d810c0c7c8c18d
|
[
"Info-ZIP"
] | null | null | null |
Task/Sorting-algorithms-Cocktail-sort/Lua/sorting-algorithms-cocktail-sort-1.lua
|
seanwallawalla-forks/RosettaCodeData
|
9ad63ea473a958506c041077f1d810c0c7c8c18d
|
[
"Info-ZIP"
] | 1
|
2018-11-09T22:08:40.000Z
|
2018-11-09T22:08:40.000Z
|
function cocktailSort( A )
local swapped
repeat
swapped = false
for i = 1, #A - 1 do
if A[ i ] > A[ i+1 ] then
A[ i ], A[ i+1 ] = A[ i+1 ] ,A[i]
swapped=true
end
end
if swapped == false then
break -- repeatd loop;
end
for i = #A - 1,1,-1 do
if A[ i ] > A[ i+1 ] then
A[ i ], A[ i+1 ] = A[ i+1 ] , A[ i ]
swapped=true
end
end
until swapped==false
end
| 18.583333
| 45
| 0.455157
|
f622a2d64454d726a5561d310bfe9e66cbfc56c8
| 289
|
hpp
|
C++
|
engine/src/Resources/ImageData.hpp
|
aleksigron/graphics-toolkit
|
f8e60c57316a72dff9de07512e9771deb3799208
|
[
"MIT"
] | 14
|
2017-10-17T16:20:20.000Z
|
2021-12-21T14:49:00.000Z
|
engine/src/Resources/ImageData.hpp
|
aleksigron/graphics-toolkit
|
f8e60c57316a72dff9de07512e9771deb3799208
|
[
"MIT"
] | null | null | null |
engine/src/Resources/ImageData.hpp
|
aleksigron/graphics-toolkit
|
f8e60c57316a72dff9de07512e9771deb3799208
|
[
"MIT"
] | 1
|
2019-05-12T13:50:23.000Z
|
2019-05-12T13:50:23.000Z
|
#pragma once
#include <cstddef>
#include "Math/Vec2.hpp"
struct ImageData
{
unsigned char* imageData;
size_t imageDataSize;
Vec2i imageSize;
unsigned int pixelFormat;
unsigned int componentDataType;
size_t compressedSize;
bool compressed;
ImageData();
};
| 13.761905
| 33
| 0.705882
|
42136bb730e44a80211a4a6164d8e457226b2f8d
| 1,166
|
lua
|
Lua
|
2_beacons.lua
|
salahzar/minetest-beacons
|
a4621b07dfa3a048b772f9db379f2767e6511fb1
|
[
"WTFPL",
"Unlicense"
] | null | null | null |
2_beacons.lua
|
salahzar/minetest-beacons
|
a4621b07dfa3a048b772f9db379f2767e6511fb1
|
[
"WTFPL",
"Unlicense"
] | null | null | null |
2_beacons.lua
|
salahzar/minetest-beacons
|
a4621b07dfa3a048b772f9db379f2767e6511fb1
|
[
"WTFPL",
"Unlicense"
] | null | null | null |
-- Mantiene la contabilita' dei "Fari" utilizzati.
-- si usa cosi':
-- v = Beacons.new()
-- e poi si puo' fare
-- v:add(pos) per aggiungere un faro
-- v:del(pos) per rimuovere un faro
-- v:exists(pos) per vedere se c'era gia'
-- v:list() per elencare i fari
Beacons = {}
Beacons.__index = Beacons
function Beacons.new()
local self = setmetatable({}, Beacons)
self.table = {}
return self
end
function Beacons.add(self, pos)
local k = pos2str(pos)
if(self.table[k] == 1) then return end
info("genero il faro alle coordinate "..k)
self.table[k]=1
end
function Beacons.del(self, pos)
local k = pos2str(pos)
self.table[k] = nil
info("distruggo il faro alle coordinate "..k)
end
function Beacons.exists(self,pos)
local k = pos2str(pos)
return self.table[k] == 1
end
function Beacons.list(self)
local ret = ""
for k,v in pairs(self.table) do
-- shows only key,values where v is 1
if(v==1) then
ret = ret .. k .. "\n"
end
end
return ret
end
function Beacons.count(self)
local count = 0
for k,v in pairs(self.table) do
if(v==1) then count = count + 1 end
end
return count
end
beacons = Beacons.new()
| 20.45614
| 50
| 0.654374
|
3f7e6de8517b3f04a9e2005948f007519880ee52
| 2,653
|
php
|
PHP
|
vendor/google/apiclient-services/src/Google/Service/Cloudbilling/Sku.php
|
almcnicoll/event_gcal
|
2d4287e599ba2f619c40d13422f94e81659853db
|
[
"MIT"
] | null | null | null |
vendor/google/apiclient-services/src/Google/Service/Cloudbilling/Sku.php
|
almcnicoll/event_gcal
|
2d4287e599ba2f619c40d13422f94e81659853db
|
[
"MIT"
] | null | null | null |
vendor/google/apiclient-services/src/Google/Service/Cloudbilling/Sku.php
|
almcnicoll/event_gcal
|
2d4287e599ba2f619c40d13422f94e81659853db
|
[
"MIT"
] | null | null | null |
<?php
/*
* Copyright 2014 Google 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.
*/
class Google_Service_Cloudbilling_Sku extends Google_Collection
{
protected $collection_key = 'serviceRegions';
protected $categoryType = 'Google_Service_Cloudbilling_Category';
protected $categoryDataType = '';
public $description;
public $name;
protected $pricingInfoType = 'Google_Service_Cloudbilling_PricingInfo';
protected $pricingInfoDataType = 'array';
public $serviceProviderName;
public $serviceRegions;
public $skuId;
/**
* @param Google_Service_Cloudbilling_Category
*/
public function setCategory(Google_Service_Cloudbilling_Category $category)
{
$this->category = $category;
}
/**
* @return Google_Service_Cloudbilling_Category
*/
public function getCategory()
{
return $this->category;
}
public function setDescription($description)
{
$this->description = $description;
}
public function getDescription()
{
return $this->description;
}
public function setName($name)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
/**
* @param Google_Service_Cloudbilling_PricingInfo
*/
public function setPricingInfo($pricingInfo)
{
$this->pricingInfo = $pricingInfo;
}
/**
* @return Google_Service_Cloudbilling_PricingInfo
*/
public function getPricingInfo()
{
return $this->pricingInfo;
}
public function setServiceProviderName($serviceProviderName)
{
$this->serviceProviderName = $serviceProviderName;
}
public function getServiceProviderName()
{
return $this->serviceProviderName;
}
public function setServiceRegions($serviceRegions)
{
$this->serviceRegions = $serviceRegions;
}
public function getServiceRegions()
{
return $this->serviceRegions;
}
public function setSkuId($skuId)
{
$this->skuId = $skuId;
}
public function getSkuId()
{
return $this->skuId;
}
}
| 26.53
| 80
| 0.669054
|
7acfa9088087e28db90d63c93606b23460fdc8df
| 2,030
|
cs
|
C#
|
LoginViewModel.cs
|
bruchano/ServerClientChatApp
|
01b2aeaadee295a55389d92ce7c00c1ff9ee81ae
|
[
"MIT"
] | 2
|
2021-06-29T15:42:13.000Z
|
2021-06-29T15:42:53.000Z
|
LoginViewModel.cs
|
bruchano/ServerClientChatApp
|
01b2aeaadee295a55389d92ce7c00c1ff9ee81ae
|
[
"MIT"
] | null | null | null |
LoginViewModel.cs
|
bruchano/ServerClientChatApp
|
01b2aeaadee295a55389d92ce7c00c1ff9ee81ae
|
[
"MIT"
] | null | null | null |
using Pie.Commands;
using Pie.Commands.ViewCommand;
using Pie.EntityFramework.Services.IAuthenticationService;
using Pie.EntityFramework.Services.UserStateHandlers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Input;
namespace Pie.ViewModels
{
public class LoginViewModel : BaseViewModel
{
private readonly IUserStateHandler _userStateHandler;
public ViewCommands viewCommands { get; private set; }
public ICommand UsernameGotFocusCommand { get; private set; }
public ICommand PasswordGotFocusCommand { get; private set; }
public ICommand LoginCommand { get; private set; }
private string _tbUsername;
public string TbUsername
{
get
{
return _tbUsername;
}
set
{
_tbUsername = value;
OnPropertyChanged(nameof(TbUsername));
}
}
public LoginViewModel(WindowViewModel m, IUserStateHandler userStateHandler, ViewCommands viewCommands)
{
windowViewModel = m;
_userStateHandler = userStateHandler;
this.viewCommands = viewCommands;
UsernameGotFocusCommand = new VoidCommand(UsernameGotFocus);
PasswordGotFocusCommand = new PasswordBoxGotFocusCommand(PasswordGotFocus);
LoginCommand = new LoginCommand(this);
}
public void UsernameGotFocus()
{
if (TbUsername == "username") TbUsername = "";
}
public void PasswordGotFocus(PasswordBox passwordBox)
{
if (passwordBox.Password == "******") passwordBox.Password = "";
}
public async Task Login(string username, string password)
{
await _userStateHandler.Login(username, password);
}
}
}
| 31.230769
| 112
| 0.617734
|
12d9b5b5ddd45e7387480edf592a6309c4e5e50d
| 304
|
cs
|
C#
|
KFC.Red.Server/KFC.Red.ServiceLayer/Dashboard/Interface/IUADashboardService.cs
|
cf2080/CECS491_DBate
|
f06a961e1b8e25416e1a34c9a7a0631d16f225b9
|
[
"MIT"
] | 1
|
2019-06-01T00:36:27.000Z
|
2019-06-01T00:36:27.000Z
|
KFC.Red.Server/KFC.Red.ServiceLayer/Dashboard/Interface/IUADashboardService.cs
|
cf2080/CECS491_DBate
|
f06a961e1b8e25416e1a34c9a7a0631d16f225b9
|
[
"MIT"
] | null | null | null |
KFC.Red.Server/KFC.Red.ServiceLayer/Dashboard/Interface/IUADashboardService.cs
|
cf2080/CECS491_DBate
|
f06a961e1b8e25416e1a34c9a7a0631d16f225b9
|
[
"MIT"
] | 2
|
2018-12-04T21:09:52.000Z
|
2018-12-11T08:32:52.000Z
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KFC.Red.ServiceLayer.Dashboard.Interface
{
public interface IUADashboardService
{
List<int> GetMonthLabels();
List<int> CountSuccessfulLogin();
}
}
| 20.266667
| 50
| 0.730263
|
275e787d7ee0204ad710d7d962afe2322d1b986f
| 736
|
swift
|
Swift
|
Analytics/Event/Web/WebEvent.swift
|
arusu0629/RoyaleApp
|
930041acb184c92efe615197a6fa8747528ff7c8
|
[
"MIT"
] | null | null | null |
Analytics/Event/Web/WebEvent.swift
|
arusu0629/RoyaleApp
|
930041acb184c92efe615197a6fa8747528ff7c8
|
[
"MIT"
] | 4
|
2020-10-06T13:59:24.000Z
|
2021-01-06T14:26:36.000Z
|
Analytics/Event/Web/WebEvent.swift
|
arusu0629/RoyaleApp
|
930041acb184c92efe615197a6fa8747528ff7c8
|
[
"MIT"
] | null | null | null |
//
// WebEvent.swift
// Analytics
//
// Created by nakandakari on 2020/10/02.
// Copyright © 2020 nakandakari. All rights reserved.
//
import Domain
import Foundation
public enum WebEvent {
case display
case selectWebTab(tab: WebViewTab)
}
extension WebEvent: AnalyticsEvent {
public var name: String {
switch self {
case .display:
return "web_display"
case .selectWebTab:
return "web_select_web_tab"
}
}
public var properties: [AnyHashable : Any] {
switch self {
case .display:
return [:]
case .selectWebTab(let tab):
return [AnalyticsManager.EventProperty.webViewTab.key: tab.label]
}
}
}
| 19.891892
| 77
| 0.60462
|
c669bc6df2bd78d71b3acc03b5582f7a159da43e
| 2,533
|
py
|
Python
|
views.py
|
M4ndU/inhun_kakao_api
|
aad27fac240c56f9d97ffa833328fbeff51aa80b
|
[
"MIT"
] | null | null | null |
views.py
|
M4ndU/inhun_kakao_api
|
aad27fac240c56f9d97ffa833328fbeff51aa80b
|
[
"MIT"
] | null | null | null |
views.py
|
M4ndU/inhun_kakao_api
|
aad27fac240c56f9d97ffa833328fbeff51aa80b
|
[
"MIT"
] | null | null | null |
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse
import datetime , json
import sys
sys.path.insert(0, "/home/mandu/project/discord_bot/")
#sys.path.insert(0, "inhun_discord_bot 경로")
from scrapture import *
from datematch import *
#api info
api_info = ""
api_info += '[인헌고 알리미 정보]\n'
api_info += '급식을 알려드립니다.\n'
api_info += '2017년 11월 2일 V1.0.0\n'
api_info += '개발자 : \n'
api_info += '자율동아리\n'
api_info += '후원'
def lunch(l_date):
l_date = lunch_match(l_date)
if (l_date != 0):
ll_diet = ""
ll_diet = get_diet(l_date)
else:
ll_diet = "급식 정보가 없습니다."
return ll_diet
def dinner(d_date):
d_date = dinner_match(d_date)
if (d_date != 0):
dd_diet = ""
dd_diet = get_diet(d_date)
else:
dd_diet = ":("
return dd_diet
def keyboard(request):
return JsonResponse({
'type':'buttons',
'buttons':['오늘 급식','내일 급식','API 정보']
})
@csrf_exempt
def answer(request):
json_str = ((request.body).decode('utf-8'))
received_json_data = json.loads(json_str)
datacontent = received_json_data['content']
#date
dt1 = datetime.datetime.today()
dt2 = datetime.datetime.today() + datetime.timedelta(days=1)
local_date1 = dt1.strftime("%m%d")
local_date2 = dt2.strftime("%m%d")
print(datacontent)
if datacontent == '오늘 급식':
meal_date = int(local_date1)
l_l = lunch(meal_date)
d_d = dinner(meal_date)
return JsonResponse({
'message': {
'text': l_l + "\n\n" + d_d
},
'keyboard': {
'type':'buttons',
'buttons':['오늘 급식','내일 급식','API 정보']
}
})
elif datacontent == '내일 급식':
meal_date = int(local_date2)
l_l = lunch(meal_date)
d_d = dinner(meal_date)
return JsonResponse({
'message': {
'text': l_l + "\n\n" + d_d
},
'keyboard': {
'type':'buttons',
'buttons':['오늘 급식','내일 급식','API 정보']
}
})
elif datacontent == 'API 정보':
return JsonResponse({
'message': {
'text': api_info
},
'keyboard': {
'type':'buttons',
'buttons':['오늘 급식','내일 급식','API 정보']
}
})
| 25.079208
| 64
| 0.511646
|
cdc15bea3e3ed966b0aae4a79a294e92f50cd806
| 689
|
cs
|
C#
|
Tailviewer.Core/Filters/NoFilter.cs
|
fhmcn/Tailviewer
|
d73081c68c2042589e925dece024e4410d9e0e2d
|
[
"MIT"
] | null | null | null |
Tailviewer.Core/Filters/NoFilter.cs
|
fhmcn/Tailviewer
|
d73081c68c2042589e925dece024e4410d9e0e2d
|
[
"MIT"
] | null | null | null |
Tailviewer.Core/Filters/NoFilter.cs
|
fhmcn/Tailviewer
|
d73081c68c2042589e925dece024e4410d9e0e2d
|
[
"MIT"
] | null | null | null |
using System.Collections.Generic;
using Tailviewer.BusinessLogic.LogFiles;
namespace Tailviewer.Core.Filters
{
/// <summary>
/// An <see cref="ILogLineFilter" /> implementation that passes every log line.
/// </summary>
public sealed class NoFilter
: ILogEntryFilter
{
/// <inheritdoc />
public bool PassesFilter(LogLine logLine)
{
return true;
}
/// <inheritdoc />
public List<LogLineMatch> Match(LogLine line)
{
return new List<LogLineMatch>();
}
/// <inheritdoc />
public bool PassesFilter(IEnumerable<LogLine> logEntry)
{
return true;
}
/// <inheritdoc />
public void Match(LogLine line, List<LogLineMatch> matches)
{
}
}
}
| 19.138889
| 84
| 0.67344
|
e22cd89e13d20fb620ab9fa99f2593ed96d508cb
| 214
|
py
|
Python
|
Chapter 01/Chap01_Example1.70.py
|
bpbpublications/Programming-Techniques-using-Python
|
49b785f37e95a3aad1d36cef51e219ac56e5e9f0
|
[
"MIT"
] | null | null | null |
Chapter 01/Chap01_Example1.70.py
|
bpbpublications/Programming-Techniques-using-Python
|
49b785f37e95a3aad1d36cef51e219ac56e5e9f0
|
[
"MIT"
] | null | null | null |
Chapter 01/Chap01_Example1.70.py
|
bpbpublications/Programming-Techniques-using-Python
|
49b785f37e95a3aad1d36cef51e219ac56e5e9f0
|
[
"MIT"
] | null | null | null |
#less than operator
print(4<10) # --- L1
print(10<4) # --- L2
print(4<4.0) # --- L3
print(4.0<4) # --- L4
print('python'<'Python') #--- L5
print('python'<'python') # --- L6
print('Python'<'python') #--- L7
| 23.777778
| 34
| 0.528037
|
46d35155d1068e4dc1513e9ec98438081ea0710e
| 23,636
|
py
|
Python
|
mob_suite/mob_typer.py
|
dfornika/mob-suite
|
40ec14b7322d4d0ad8506a65b77e28275b826fe0
|
[
"Apache-2.0"
] | 43
|
2018-05-08T03:01:50.000Z
|
2022-03-31T16:07:58.000Z
|
mob_suite/mob_typer.py
|
dfornika/mob-suite
|
40ec14b7322d4d0ad8506a65b77e28275b826fe0
|
[
"Apache-2.0"
] | 93
|
2018-05-08T07:50:58.000Z
|
2022-03-31T15:37:13.000Z
|
mob_suite/mob_typer.py
|
dfornika/mob-suite
|
40ec14b7322d4d0ad8506a65b77e28275b826fe0
|
[
"Apache-2.0"
] | 20
|
2018-05-08T11:16:16.000Z
|
2022-02-08T16:58:41.000Z
|
#!/usr/bin/env python3
import logging
import os, re, shutil, sys, tempfile
from argparse import (ArgumentParser, FileType)
from mob_suite.version import __version__
import mob_suite.mob_init
from collections import OrderedDict
from operator import itemgetter
from mob_suite.blast import BlastRunner
from mob_suite.wrappers import mash
from mob_suite.utils import fix_fasta_header, \
calcFastaStats, \
verify_init, \
check_dependencies, \
read_sequence_info, \
writeReport, \
sort_biomarkers, \
ETE3_db_status_check, \
calc_md5, \
GC, \
read_fasta_dict, \
identify_biomarkers, \
parseMash, \
determine_mpf_type, \
hostrange, \
dict_from_alt_key_list, \
read_file_to_dict
from mob_suite.constants import ETE3DBTAXAFILE, \
MOB_TYPER_REPORT_HEADER, \
MOB_CLUSTER_INFO_HEADER, \
default_database_dir, \
ETE3_LOCK_FILE, \
LIT_PLASMID_TAXONOMY_HEADER
def init_console_logger(lvl=2):
root = logging.getLogger()
LOG_FORMAT = '%(asctime)s %(name)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'
logging_levels = [logging.ERROR, logging.WARN, logging.INFO, logging.DEBUG]
report_lvl = logging_levels[lvl]
root.setLevel(report_lvl) # set root logger level
logging.basicConfig(format=LOG_FORMAT, level=report_lvl)
return logging.getLogger(__name__)
def parse_args():
"Parse the input arguments, use '-h' for help"
parser = ArgumentParser(
description="MOB-Typer: Plasmid typing and mobility prediction: {}".format(
__version__))
parser.add_argument('-i', '--infile', type=str, required=True, help='Input assembly fasta file to process')
parser.add_argument('-o', '--out_file', type=str, required=True, help='Output file to write results')
parser.add_argument('-a', '--analysis_dir', type=str, required=False, help='Analysis directory')
parser.add_argument('-n', '--num_threads', type=int, required=False, help='Number of threads to be used', default=1)
parser.add_argument('-s', '--sample_id', type=str, required=False, help='Sample Prefix for reports')
parser.add_argument('-f', '--force', required=False, help='Overwrite existing directory',
action='store_true')
parser.add_argument('-x', '--multi', required=False, help='Treat each sequence as an independant plasmid',
action='store_true')
parser.add_argument('--min_rep_evalue', type=str, required=False,
help='Minimum evalue threshold for replicon blastn',
default=0.00001)
parser.add_argument('--min_mob_evalue', type=str, required=False,
help='Minimum evalue threshold for relaxase tblastn',
default=0.00001)
parser.add_argument('--min_con_evalue', type=str, required=False, help='Minimum evalue threshold for contig blastn',
default=0.00001)
parser.add_argument('--min_length', type=str, required=False, help='Minimum length of contigs to classify',
default=1000)
parser.add_argument('--min_rep_ident', type=int, required=False, help='Minimum sequence identity for replicons',
default=80)
parser.add_argument('--min_mob_ident', type=int, required=False, help='Minimum sequence identity for relaxases',
default=80)
parser.add_argument('--min_con_ident', type=int, required=False, help='Minimum sequence identity for contigs',
default=80)
parser.add_argument('--min_rep_cov', type=int, required=False,
help='Minimum percentage coverage of replicon query by input assembly',
default=80)
parser.add_argument('--min_mob_cov', type=int, required=False,
help='Minimum percentage coverage of relaxase query by input assembly',
default=80)
parser.add_argument('--min_con_cov', type=int, required=False,
help='Minimum percentage coverage of assembly contig by the plasmid reference database to be considered',
default=70)
parser.add_argument('--min_overlap', type=int, required=False,
help='Minimum overlap of fragments',
default=10)
parser.add_argument('-k', '--keep_tmp', required=False, help='Do not delete temporary file directory',
action='store_true')
parser.add_argument('--debug', required=False, help='Show debug information', action='store_true')
parser.add_argument('--plasmid_mash_db', type=str, required=False,
help='Companion Mash database of reference database',
default=os.path.join(default_database_dir,
'ncbi_plasmid_full_seqs.fas.msh'))
parser.add_argument('-m', '--plasmid_meta', type=str, required=False,
help='MOB-cluster plasmid cluster formatted file matched to the reference plasmid db',
default=os.path.join(default_database_dir,
'clusters.txt'))
parser.add_argument('--plasmid_db_type', type=str, required=False, help='Blast database type of reference database',
default='blastn')
parser.add_argument('--plasmid_replicons', type=str, required=False, help='Fasta of plasmid replicons',
default=os.path.join(default_database_dir,
'rep.dna.fas'))
parser.add_argument('--repetitive_mask', type=str, required=False, help='Fasta of known repetitive elements',
default=os.path.join(default_database_dir,
'repetitive.dna.fas'))
parser.add_argument('--plasmid_mob', type=str, required=False, help='Fasta of plasmid relaxases',
default=os.path.join(default_database_dir,
'mob.proteins.faa'))
parser.add_argument('--plasmid_mpf', type=str, required=False, help='Fasta of known plasmid mate-pair proteins',
default=os.path.join(default_database_dir,
'mpf.proteins.faa'))
parser.add_argument('--plasmid_orit', type=str, required=False, help='Fasta of known plasmid oriT dna sequences',
default=os.path.join(default_database_dir,
'orit.fas'))
parser.add_argument('-d', '--database_directory',
default=default_database_dir,
required=False,
help='Directory you want to use for your databases. If the databases are not already '
'downloaded, they will be downloaded automatically. Defaults to {}'.format(
default_database_dir))
parser.add_argument('--primary_cluster_dist', type=int, required=False,
help='Mash distance for assigning primary cluster id 0 - 1', default=0.06)
parser.add_argument('--secondary_cluster_dist', type=int, required=False,
help='Mash distance for assigning primary cluster id 0 - 1',
default=0.025)
parser.add_argument('-V', '--version', action='version', version="%(prog)s " + __version__)
return parser.parse_args()
def initMOBTyperReportTemplate(header):
data = {}
for i in header:
data[i] = '-'
return data
def main():
args = parse_args()
if args.debug:
logger = init_console_logger(3)
else:
logger = init_console_logger(2)
logger.info('Running Mob-typer version {}'.format(__version__))
logger.info('Processing fasta file {}'.format(args.infile))
if not os.path.isfile(args.infile):
logger.info('Error, fasta file does not exist {}'.format(args.infile))
sys.exit()
if not args.analysis_dir:
tmp_dir = tempfile.TemporaryDirectory(dir=tempfile.gettempdir()).name
else:
tmp_dir = args.analysis_dir
if not os.path.isdir(tmp_dir):
os.mkdir(tmp_dir, 0o755)
if not isinstance(args.num_threads, int):
logger.info('Error number of threads must be an integer, you specified "{}"'.format(args.num_threads))
database_dir = os.path.abspath(args.database_directory)
if args.sample_id is None:
sample_id = re.sub(r"\.(fasta|fa|fas){1,1}", "", os.path.basename(args.infile))
else:
sample_id = args.sample_id
# Script arguments
input_fasta = args.infile
report_file = args.out_file
num_threads = int(args.num_threads)
keep_tmp = args.keep_tmp
if args.multi:
multi = True
else:
multi = False
if not (args.primary_cluster_dist >= 0 and args.primary_cluster_dist <= 1):
logging.error('Error distance thresholds must be between 0 - 1: {}'.format(args.primary_cluster_dist))
sys.exit()
else:
primary_distance = float(args.primary_cluster_dist)
if not (args.secondary_cluster_dist >= 0 and args.secondary_cluster_dist <= 1):
logging.error('Error distance thresholds must be between 0 - 1: {}'.format(args.secondary_cluster_dist))
sys.exit()
else:
secondary_distance = float(args.secondary_cluster_dist)
if database_dir == default_database_dir:
mob_ref = args.plasmid_mob
mash_db = args.plasmid_mash_db
replicon_ref = args.plasmid_replicons
plasmid_meta = args.plasmid_meta
mpf_ref = args.plasmid_mpf
plasmid_orit = args.plasmid_orit
verify_init(logger, database_dir)
else:
mob_ref = os.path.join(database_dir, 'mob.proteins.faa')
mash_db = os.path.join(database_dir, 'ncbi_plasmid_full_seqs.fas.msh')
replicon_ref = os.path.join(database_dir, 'rep.dna.fas')
plasmid_meta = os.path.join(database_dir, 'clusters.txt')
mpf_ref = os.path.join(database_dir, 'mpf.proteins.faa')
plasmid_orit = os.path.join(database_dir, 'orit.fas')
LIT_PLASMID_TAXONOMY_FILE = os.path.join(database_dir, "host_range_literature_plasmidDB.txt")
NCBI_PLASMID_TAXONOMY_FILE = plasmid_meta
fixed_fasta = os.path.join(tmp_dir, 'fixed.input.fasta')
replicon_blast_results = os.path.join(tmp_dir, 'replicon_blast_results.txt')
mob_blast_results = os.path.join(tmp_dir, 'mobtyper_blast_results.txt')
mpf_blast_results = os.path.join(tmp_dir, 'mpf_blast_results.txt')
orit_blast_results = os.path.join(tmp_dir, 'orit_blast_results.txt')
repetitive_blast_results = os.path.join(tmp_dir, 'repetitive_blast_results.txt')
if os.path.isfile(mob_blast_results):
os.remove(mob_blast_results)
if os.path.isfile(mpf_blast_results):
os.remove(mpf_blast_results)
if os.path.isfile(orit_blast_results):
os.remove(orit_blast_results)
if os.path.isfile(replicon_blast_results):
os.remove(replicon_blast_results)
# Input numeric params
min_rep_ident = float(args.min_rep_ident)
min_mob_ident = float(args.min_mob_ident)
min_ori_ident = float(args.min_rep_ident)
min_mpf_ident = float(args.min_mob_ident)
idents = {'min_rep_ident': min_rep_ident, 'min_mob_ident': min_mob_ident, 'min_ori_ident': min_ori_ident}
for param in idents:
value = float(idents[param])
if value < 60:
logger.error("Error: {} is too low, please specify an integer between 70 - 100".format(param))
sys.exit(-1)
if value > 100:
logger.error("Error: {} is too high, please specify an integer between 70 - 100".format(param))
sys.exit(-1)
min_rep_cov = float(args.min_rep_cov)
min_mob_cov = float(args.min_mob_cov)
min_ori_cov = float(args.min_rep_cov)
min_mpf_cov = float(args.min_mob_cov)
covs = {'min_rep_cov': min_rep_cov, 'min_mob_cov': min_mob_cov, 'min_con_cov': min_ori_cov,
'min_rpp_cov': min_ori_cov}
for param in covs:
value = float(covs[param])
if value < 60:
logger.error("Error: {} is too low, please specify an integer between 50 - 100".format(param))
sys.exit(-1)
if value > 100:
logger.error("Error: {} is too high, please specify an integer between 50 - 100".format(param))
sys.exit(-1)
min_rep_evalue = float(args.min_rep_evalue)
min_mob_evalue = float(args.min_mob_evalue)
min_ori_evalue = float(args.min_rep_evalue)
min_mpf_evalue = float(args.min_mob_evalue)
evalues = {'min_rep_evalue': min_rep_evalue, 'min_mob_evalue': min_mob_evalue, 'min_con_evalue': min_ori_evalue}
for param in evalues:
value = float(evalues[param])
if value > 1:
logger.error("Error: {} is too high, please specify an float evalue between 0 to 1".format(param))
sys.exit(-1)
check_dependencies(logger)
needed_dbs = [replicon_ref, mob_ref, mash_db, mpf_ref]
for db in needed_dbs:
if (not os.path.isfile(db)):
logger.info('Warning! Needed database missing "{}"'.format(db))
mob_suite.mob_init.main()
if not os.path.isdir(tmp_dir):
os.mkdir(tmp_dir, 0o755)
# Test that ETE3 db is ok and lock process check
dbstatus = ETE3_db_status_check(1, ETE3_LOCK_FILE, ETE3DBTAXAFILE, logging)
if dbstatus == False:
logging.error("Exiting due to lock file not removed: {}".format(ETE3_LOCK_FILE))
sys.exit(-1)
# Get cluster information
reference_sequence_meta = read_sequence_info(plasmid_meta, MOB_CLUSTER_INFO_HEADER)
# initilize master record tracking
fix_fasta_header(input_fasta, fixed_fasta)
contig_seqs = read_fasta_dict(fixed_fasta)
contig_info = {}
for id in contig_seqs:
seq = contig_seqs[id]
contig_info[id] = {}
for feature in MOB_TYPER_REPORT_HEADER:
contig_info[id][feature] = ''
contig_info[id]['md5'] = calc_md5(seq)
contig_info[id]['gc'] = GC(seq)
contig_info[id]['size'] = len(seq)
contig_info[id]['contig_id'] = id
contig_info[id]['sample_id'] = sample_id
# Makeblastdb
blast_runner = BlastRunner(fixed_fasta, tmp_dir)
build_success = blast_runner.makeblastdb(fixed_fasta, 'nucl', logging=logging)
if build_success == False:
logging.error("Could not build blast database, check error messages..cannot continue")
sys.exit()
# run individual marker blasts
contig_info = identify_biomarkers(contig_info, fixed_fasta, tmp_dir, 25, logging, \
replicon_ref, min_rep_ident, min_rep_cov, min_rep_evalue, replicon_blast_results, \
mob_ref, min_mob_ident, min_mob_cov, min_mob_evalue, mob_blast_results, \
mpf_ref, min_mpf_ident, min_mpf_cov, min_mpf_evalue, mpf_blast_results, \
None, None, None, None, \
plasmid_orit, orit_blast_results, repetitive_blast_results, \
num_threads=1)
m = mash()
mobtyper_results = []
mash_input_fasta = fixed_fasta + '.msh'
ncbi = dict_from_alt_key_list(
read_file_to_dict(NCBI_PLASMID_TAXONOMY_FILE, MOB_CLUSTER_INFO_HEADER, separater="\t"),
"sample_id")
lit = dict_from_alt_key_list(
read_file_to_dict(LIT_PLASMID_TAXONOMY_FILE, LIT_PLASMID_TAXONOMY_HEADER, separater="\t"), "sample_id")
if multi:
m.mashsketch(input_fasta=fixed_fasta, output_path=mash_input_fasta, sketch_ind=True, num_threads=num_threads)
mash_results = parseMash(
m.run_mash(reference_db=mash_db, input_fasta=mash_input_fasta, table=False, num_threads=num_threads))
for seq_id in mash_results:
record = {}
for field in MOB_TYPER_REPORT_HEADER:
if field in contig_info[seq_id]:
record[field] = contig_info[seq_id][field]
else:
record[field] = ''
record['sample_id'] = seq_id
record['num_contigs'] = 1
distances = OrderedDict(sorted(mash_results[seq_id].items(), key=itemgetter(1), reverse=False))
for mash_neighbor_id in distances:
dist = distances[mash_neighbor_id]
if mash_neighbor_id not in reference_sequence_meta:
continue
else:
record['mash_nearest_neighbor'] = mash_neighbor_id
record['mash_neighbor_distance'] = dist
record['primary_cluster_id'] = reference_sequence_meta[mash_neighbor_id]['primary_cluster_id']
record['secondary_cluster_id'] = reference_sequence_meta[mash_neighbor_id]['secondary_cluster_id']
record['mash_neighbor_identification'] = reference_sequence_meta[mash_neighbor_id]['organism']
break
mobtyper_results.append(record)
else:
m.mashsketch(input_fasta=fixed_fasta, output_path=mash_input_fasta, sketch_ind=False, num_threads=num_threads)
mash_results = parseMash(
m.run_mash(reference_db=mash_db, input_fasta=mash_input_fasta, table=False, num_threads=num_threads))
record = {}
for field in MOB_TYPER_REPORT_HEADER:
record[field] = ''
record['sample_id'] = sample_id
fastaSeqStats = calcFastaStats(fixed_fasta)
record['md5'] = fastaSeqStats['md5']
record['total_length'] = fastaSeqStats['size']
record['num_contigs'] = fastaSeqStats['num_seq']
record['gc'] = fastaSeqStats['gc_content']
record['mash_nearest_neighbor'] = '-'
record['mash_neighbor_distance'] = 1
record['primary_cluster_id'] = '-'
record['secondary_cluster_id'] = '-'
record['mash_neighbor_identification'] = '-'
for seq_id in mash_results:
distances = OrderedDict(sorted(mash_results[seq_id].items(), key=itemgetter(1), reverse=False))
mash_neighbor_id = next(iter(distances))
dist = distances[mash_neighbor_id]
if mash_neighbor_id not in reference_sequence_meta:
continue
record['mash_nearest_neighbor'] = mash_neighbor_id
record['mash_neighbor_distance'] = dist
record['primary_cluster_id'] = reference_sequence_meta[mash_neighbor_id]['primary_cluster_id']
record['secondary_cluster_id'] = reference_sequence_meta[mash_neighbor_id]['secondary_cluster_id']
record['mash_neighbor_identification'] = reference_sequence_meta[mash_neighbor_id]['organism']
record['rep_type(s)'] = []
record['rep_type_accession(s)'] = []
record['relaxase_type(s)'] = []
record['relaxase_type_accession(s)'] = []
record['mpf_type'] = []
record['mpf_type_accession(s)'] = []
record['orit_type(s)'] = []
record['orit_accession(s)'] = []
for seq_id in contig_info:
record['rep_type(s)'].append(contig_info[seq_id]['rep_type(s)'])
record['rep_type_accession(s)'].append(contig_info[seq_id]['rep_type_accession(s)'])
record['relaxase_type(s)'].append(contig_info[seq_id]['relaxase_type(s)'])
record['relaxase_type_accession(s)'].append(contig_info[seq_id]['relaxase_type_accession(s)'])
record['mpf_type'].append(contig_info[seq_id]['mpf_type'])
record['mpf_type_accession(s)'].append(contig_info[seq_id]['mpf_type_accession(s)'])
record['orit_type(s)'].append(contig_info[seq_id]['orit_type(s)'])
record['orit_accession(s)'].append(contig_info[seq_id]['orit_accession(s)'])
for field in record:
tmp = []
if record[field] == None:
continue
if isinstance(record[field], list):
length = len(record[field])
for i in range(0, length):
tmp += record[field][i].split(',')
elif isinstance(record[field], str) and len(record[field]) > 0:
tmp += record[field].split(',')
if len(tmp) > 0:
record[field] = []
for d in tmp:
if len(d) > 0:
record[field].append(d)
mobtyper_results.append(record)
for i in range(0, len(mobtyper_results)):
record = mobtyper_results[i]
bio_markers = sort_biomarkers({0: {'types': record['rep_type(s)'], 'acs': record['rep_type_accession(s)']},
1: {'types': record['relaxase_type(s)'],
'acs': record['relaxase_type_accession(s)']},
2: {'types': record['mpf_type'], 'acs': record['mpf_type_accession(s)']},
3: {'types': record['orit_type(s)'], 'acs': record['orit_accession(s)']}, })
record['rep_type(s)'] = bio_markers[0]['types']
record['rep_type_accession(s)'] = bio_markers[0]['acs']
record['relaxase_type(s)'] = bio_markers[1]['types']
record['relaxase_type_accession(s)'] = bio_markers[1]['acs']
record['mpf_type'] = bio_markers[2]['types']
record['mpf_type_accession(s)'] = bio_markers[2]['acs']
record['orit_type(s)'] = bio_markers[3]['types']
record['orit_accession(s)'] = bio_markers[3]['acs']
if (isinstance(record['mash_neighbor_distance'],float) or isinstance(record['mash_neighbor_distance'],int)) and record['mash_neighbor_distance'] <= primary_distance:
mob_cluster_id = record['primary_cluster_id']
else:
mob_cluster_id = None
#Patches that sometimes results are concatonated into strings if contigs are merged into a single results
if isinstance(record['rep_type(s)'],list):
record['rep_type(s)'] = ",".join(record['rep_type(s)'])
if isinstance(record['relaxase_type_accession(s)'], list):
record['relaxase_type_accession(s)'] = ",".join(record['relaxase_type_accession(s)'])
host_range = hostrange(record['rep_type(s)'].split(','), record['relaxase_type_accession(s)'].split(','), mob_cluster_id, ncbi, lit)
for field in host_range:
record[field] = host_range[field]
if isinstance(record['mpf_type'], list):
record['mpf_type'] = determine_mpf_type(record['mpf_type'])
elif isinstance(record['mpf_type'], str):
record['mpf_type'] = determine_mpf_type(record['mpf_type'].split(','))
for field in record:
if isinstance(record[field], list):
record[field] = ",".join(record[field])
record['predicted_mobility'] = 'non-mobilizable'
if len(record['relaxase_type(s)']) > 0 and len(record['mpf_type']):
record['predicted_mobility'] = 'conjugative'
elif len(record['relaxase_type(s)']) > 0 or len(record['orit_type(s)']) > 0:
record['predicted_mobility'] = 'mobilizable'
mobtyper_results[i] = record
writeReport(mobtyper_results, MOB_TYPER_REPORT_HEADER, report_file)
if not keep_tmp:
shutil.rmtree(tmp_dir)
logger.info("MOB-typer completed and results written to {}".format(report_file))
# call main function
if __name__ == '__main__':
main()
| 44.935361
| 173
| 0.631621
|
bffbc1b53ec9d3504f13ba71c0ff3af1a1204a93
| 3,101
|
ps1
|
PowerShell
|
src/PS/AreaIteration/Set-TfsIteration.ps1
|
GitHubShark39/tfscmdlets.redvulture.github.io
|
f24d86edbac0470ab30dbba8e15e0cb837e61758
|
[
"MIT"
] | null | null | null |
src/PS/AreaIteration/Set-TfsIteration.ps1
|
GitHubShark39/tfscmdlets.redvulture.github.io
|
f24d86edbac0470ab30dbba8e15e0cb837e61758
|
[
"MIT"
] | null | null | null |
src/PS/AreaIteration/Set-TfsIteration.ps1
|
GitHubShark39/tfscmdlets.redvulture.github.io
|
f24d86edbac0470ab30dbba8e15e0cb837e61758
|
[
"MIT"
] | null | null | null |
<#
.SYNOPSIS
Modifies the name, position and/or the dates of a Work Item Iteration.
.PARAMETER Iteration
${HelpParam_Iteration}
.PARAMETER NewName
Specifies the new name of the iteration. Enter only a name, not a path and name. If you enter a path that is different from the path that is specified in the Iteration parameter, Rename-TfsIteration generates an error. To rename and move an item, use the Move-TfsIteration cmdlet.
.PARAMETER MoveBy
Reorders an iteration by moving it either up or down inside its parent. A positive value moves an iteration down, whereas a negative one moves it up.
.PARAMETER StartDate
Sets the start date of the iteration. To clear the start date, set it to $null. Note that when clearing a date, both must be cleared at the same time (i.e. setting both StartDate and FinishDate to $null)
.PARAMETER FinishDate
Sets the finish date of the iteration. To clear the finish date, set it to $null. Note that when clearing a date, both must be cleared at the same time (i.e. setting both StartDate and FinishDate to $null)
.PARAMETER Project
${HelpParam_Project}
.PARAMETER Collection
${HelpParam_Collection}
.INPUTS
Microsoft.TeamFoundation.WorkItemTracking.Client.Project
System.String
#>
Function Set-TfsIteration
{
[CmdletBinding()]
[OutputType([Microsoft.TeamFoundation.Server.NodeInfo])]
Param
(
[Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true)]
[Alias("Path")]
[ValidateScript({($_ -is [string]) -or ($_ -is [Microsoft.TeamFoundation.Server.NodeInfo])})]
[object]
$Iteration = '\**',
[Parameter()]
[string]
$NewName,
[Parameter()]
[int]
$MoveBy,
[Parameter()]
[Nullable[DateTime]]
$StartDate,
[Parameter()]
[Nullable[DateTime]]
$FinishDate,
[Parameter()]
[object]
$Project,
[Parameter()]
[object]
$Collection
)
Process
{
$node = Get-TfsIteration -Iteration $Iteration -Project $Project -Collection $Collection
if (-not $node)
{
throw "Invalid or non-existent iteration $Iteration"
}
$cssService = _GetCssService -Project $Project -Collection $Collection
$cssService4 = _GetCssService -Project $Project -Collection $Collection -Version 4
if ($NewName)
{
$cssService.RenameNode($node.Uri, $NewName)
}
if ($MoveBy)
{
$cssService.ReorderNode($node.Uri, $MoveBy)
}
if ($StartDate -or $FinishDate)
{
if (-not $PSBoundParameters.ContainsKey("StartDate"))
{
$StartDate = $node.StartDate
}
if (-not $PSBoundParameters.ContainsKey("FinishDate"))
{
$FinishDate = $node.FinishDate
}
[void]$cssService4.SetIterationDates($node.Uri, $StartDate, $FinishDate)
}
return $cssService.GetNode($node.Uri)
}
}
| 28.981308
| 284
| 0.624315
|
a37eac083afdc1b2c6c5328d85f1c2ef4456ec0b
| 658
|
java
|
Java
|
simhash-knn/src/main/java/fr/ujm/tse/lt2c/satin/simhash/knn/datastructure/LongDistanceDocumentIterator.java
|
csearch/simhashdb
|
18405752b7da171c60f6f8a1072bf3be333b3f67
|
[
"Apache-2.0"
] | 1
|
2018-05-31T11:35:06.000Z
|
2018-05-31T11:35:06.000Z
|
simhash-knn/src/main/java/fr/ujm/tse/lt2c/satin/simhash/knn/datastructure/LongDistanceDocumentIterator.java
|
csearch/simhashdb
|
18405752b7da171c60f6f8a1072bf3be333b3f67
|
[
"Apache-2.0"
] | null | null | null |
simhash-knn/src/main/java/fr/ujm/tse/lt2c/satin/simhash/knn/datastructure/LongDistanceDocumentIterator.java
|
csearch/simhashdb
|
18405752b7da171c60f6f8a1072bf3be333b3f67
|
[
"Apache-2.0"
] | null | null | null |
/**
*
*/
package fr.ujm.tse.lt2c.satin.simhash.knn.datastructure;
/**
* Homemade quick'n'dirty primitive iterator to save useless boxing operations
*
* @author Julien
*
*/
public interface LongDistanceDocumentIterator {
/**
*
* @return a {@link Long} containing the distance on its 32 most significant
* digits and the document id on its 32 last. <br>
* -1 when no more data
*/
public long getNextLong();
/**
* Useful hint for sampling
*
* @return the total number of elements
*/
public int elements();
/**
*
* @return the index of the first document in the global DB
*/
public int getStartIndex();
}
| 18.8
| 78
| 0.655015
|
7f36c2c800194748ec6a7770d22f17243469efe4
| 1,985
|
cs
|
C#
|
FlowJS.NetCore/Utilities/ProxyAdvancedExtensions.cs
|
ruisilva450/FlowJs-NetCore
|
2806c8b025222c7e5be738dce1991f2e881308fd
|
[
"MIT"
] | 2
|
2019-12-13T15:01:05.000Z
|
2020-10-02T00:02:12.000Z
|
FlowJS.NetCore/Utilities/ProxyAdvancedExtensions.cs
|
ruisilva450/FlowJs-NetCore
|
2806c8b025222c7e5be738dce1991f2e881308fd
|
[
"MIT"
] | 1
|
2021-07-30T09:11:05.000Z
|
2021-07-30T09:11:05.000Z
|
FlowJS.NetCore/Utilities/ProxyAdvancedExtensions.cs
|
ruisilva450/FlowJs-NetCore
|
2806c8b025222c7e5be738dce1991f2e881308fd
|
[
"MIT"
] | 1
|
2021-10-05T01:14:48.000Z
|
2021-10-05T01:14:48.000Z
|
using Microsoft.AspNetCore.Http;
using System;
using System.Linq;
using System.Net.Http;
namespace ngFlowSample.Core.Utilities
{
public static class RequestTranscriptHelpers
{
public static HttpRequestMessage ToHttpRequestMessage(this HttpRequest req)
=> new HttpRequestMessage()
.SetMethod(req)
.SetAbsoluteUri(req)
.SetHeaders(req)
.SetContent(req)
.SetContentType(req);
private static HttpRequestMessage SetAbsoluteUri(this HttpRequestMessage msg, HttpRequest req)
=> msg.Set(m => m.RequestUri = new UriBuilder
{
Scheme = req.Scheme,
Host = req.Host.Host,
Port = req.Host.Port.Value,
Path = req.PathBase.Add(req.Path),
Query = req.QueryString.ToString()
}.Uri);
private static HttpRequestMessage SetMethod(this HttpRequestMessage msg, HttpRequest req)
=> msg.Set(m => m.Method = new HttpMethod(req.Method));
private static HttpRequestMessage SetHeaders(this HttpRequestMessage msg, HttpRequest req)
=> req.Headers.Aggregate(msg, (acc, h) => acc.Set(m => m.Headers.TryAddWithoutValidation(h.Key, h.Value.AsEnumerable())));
private static HttpRequestMessage SetContent(this HttpRequestMessage msg, HttpRequest req)
=> msg.Set(m => m.Content = new StreamContent(req.Body));
private static HttpRequestMessage SetContentType(this HttpRequestMessage msg, HttpRequest req)
=> msg.Set(m => m.Content.Headers.Add("Content-Type", req.ContentType), applyIf: req.Headers.ContainsKey("Content-Type"));
private static HttpRequestMessage Set(this HttpRequestMessage msg, Action<HttpRequestMessage> config, bool applyIf = true)
{
if (applyIf)
{
config.Invoke(msg);
}
return msg;
}
}
}
| 38.921569
| 134
| 0.623174
|
06ccf9f7cb581f5955912285d5c0ab1e54b412c9
| 4,203
|
py
|
Python
|
finetuna/offline_learner/fmax_learner.py
|
ulissigroup/al-mlp
|
59847d6a9a92fb81f11f5e37044752332e1a95c8
|
[
"MIT"
] | null | null | null |
finetuna/offline_learner/fmax_learner.py
|
ulissigroup/al-mlp
|
59847d6a9a92fb81f11f5e37044752332e1a95c8
|
[
"MIT"
] | null | null | null |
finetuna/offline_learner/fmax_learner.py
|
ulissigroup/al-mlp
|
59847d6a9a92fb81f11f5e37044752332e1a95c8
|
[
"MIT"
] | null | null | null |
from finetuna.offline_learner.offline_learner import OfflineActiveLearner
from finetuna.utils import compute_with_calc, write_to_db
import numpy as np
import ase
import random
from ase.io.trajectory import TrajectoryWriter
__author__ = "Joseph Musielewicz"
__email__ = "al.mlp.package@gmail.com"
class FmaxLearner(OfflineActiveLearner):
"""
Replaces termination criteria with a max force in the constructor and the check_terminate method
"""
def __init__(
self,
learner_params,
training_data,
ml_potential,
parent_calc,
base_calc,
mongo_db=None,
):
super().__init__(
learner_params,
training_data,
ml_potential,
parent_calc,
base_calc,
mongo_db=mongo_db,
)
self.max_evA = learner_params["max_evA"]
def check_terminate(self):
"""
Termination function.
"""
final_point_image = [self.sample_candidates[-1]]
final_point_evA = compute_with_calc(final_point_image, self.delta_sub_calc)
self.final_point_force = final_point_evA[0].info["parent fmax"]
self.training_data += final_point_evA
self.parent_calls += 1
random.seed(self.query_seeds[self.iterations - 1] + 1)
if self.iterations == 0:
writer = TrajectoryWriter("final_images.traj", mode="w")
writer.write(final_point_image[0])
else:
writer = TrajectoryWriter("final_images.traj", mode="a")
writer.write(final_point_image[0])
if self.iterations >= self.max_iterations:
return True
else:
if self.iterations > 0 and self.final_point_force <= self.max_evA:
return True
return False
def query_func(self):
"""
Random query strategy.
"""
# queries_db = ase.db.connect("queried_images.db")
if len(self.sample_candidates) <= self.samples_to_retrain:
print(
"Number of sample candidates is less than or equal to the requested samples to retrain, defaulting to all samples but the initial and final"
)
query_idx = [*range(1, len(self.sample_candidates) - 1)]
if query_idx == []:
query_idx = [
0
] # EDGE CASE WHEN samples = 2 (need a better way to do it)
else:
query_idx = random.sample(
range(1, len(self.sample_candidates) - 1),
self.samples_to_retrain - 1,
)
queried_images = [self.sample_candidates[idx] for idx in query_idx]
if self.iterations == 1:
writer = TrajectoryWriter("queried_images.traj", mode="w")
for i in queried_images:
writer.write(i)
else:
writer = TrajectoryWriter("queried_images.traj", mode="a")
for i in queried_images:
writer.write(i)
self.parent_calls += len(queried_images)
return queried_images, query_idx
class ForceQueryLearner(FmaxLearner):
"""
Terminates based on max force.
Guarantees the query of the image with the lowest ML fmax.
"""
def query_func(self):
"""
Queries the minimum fmax image + random
"""
fmaxes = [
np.max(np.abs(image.get_forces())) for image in self.sample_candidates[1:]
]
min_index = np.argmin(fmaxes) + 1
idxs = set(range(1, len(self.sample_candidates)))
idxs.remove(min_index)
queries_db = ase.db.connect("queried_images.db")
query_idx = random.sample(idxs, self.samples_to_retrain - 1)
queried_images = [self.sample_candidates[idx] for idx in query_idx]
min_force_image = self.sample_candidates[min_index]
queried_images += min_force_image
min_image_parent = compute_with_calc([min_force_image], self.parent_calc)[0]
self.final_point_force = np.sqrt(
(min_image_parent.get_forces() ** 2).sum(axis=1).max()
)
write_to_db(queries_db, queried_images)
return queried_images, query_idx
| 34.170732
| 156
| 0.61123
|
ae885a716ff96d529dfa78b339356179ddff4d8c
| 11,210
|
cs
|
C#
|
iOS/SampleBrowser/Samples/ImageEditor/ImageEditorCustomization.cs
|
raver99/SFTreeView_Binding_Issue
|
7facbedff89d9ae7fac33ef6976e7474f5c7fabb
|
[
"FTL",
"Info-ZIP"
] | 269
|
2018-08-06T15:40:41.000Z
|
2022-03-31T14:08:06.000Z
|
iOS/SampleBrowser/Samples/ImageEditor/ImageEditorCustomization.cs
|
davchezt/xamarin-demos
|
62b123f2419ae9415b307eed863fb9897f375726
|
[
"FTL",
"Info-ZIP"
] | 40
|
2018-09-21T20:12:09.000Z
|
2022-02-17T04:53:35.000Z
|
iOS/SampleBrowser/Samples/ImageEditor/ImageEditorCustomization.cs
|
davchezt/xamarin-demos
|
62b123f2419ae9415b307eed863fb9897f375726
|
[
"FTL",
"Info-ZIP"
] | 205
|
2018-08-07T06:03:08.000Z
|
2022-03-30T05:55:02.000Z
|
#region Copyright Syncfusion Inc. 2001-2021.
// Copyright Syncfusion Inc. 2001-2021. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using System;
using Syncfusion.SfImageEditor.iOS;
using Foundation;
using UIKit;
using CoreGraphics;
using System.Drawing;
using Photos;
using System.IO;
namespace SampleBrowser
{
public class ImageEditorCustomization : SampleView
{
bool isReset, isUndo, isRedo, isRect, isText, isPath;
UIView RightView;
UIView overView;
UIView topView;
SfImageEditor sfImageEditor;
Object settings;
UITextField textView;
UIViewController presentController;
public ImageEditorCustomization()
{
}
public override void LayoutSubviews()
{
isReset=isUndo=isRedo=isRect=isText=isPath = false;
base.LayoutSubviews();
presentController = GetVisibleViewController();
UIView mainView = new UIView();
mainView.Frame = new CGRect(0, 0, Frame.Width, Frame.Height);
mainView.BackgroundColor = UIColor.Clear;
sfImageEditor = new SfImageEditor(new CGRect(mainView.Frame.X, mainView.Frame.Y, mainView.Frame.Width, mainView.Frame.Height));
sfImageEditor.Image = UIImage.FromBundle("Images/ImageEditor/Customize.jpg");
sfImageEditor.BackgroundColor = UIColor.Black;
sfImageEditor.ToolBarSettings.IsVisible = false;
//settings = new Object();
sfImageEditor.ItemSelected += (object sender, ItemSelectedEventArgs e) =>
{
RightView.Alpha = 1;
settings = e.Settings;
};
mainView.AddSubview(sfImageEditor);
/*--------------------------------------------------*/
//TopView
topView = new UIView();
topView.Frame = new CGRect(0, 15, Frame.Width, 25);
topView.Alpha = 0;
UIButton reset = new UIButton(new CGRect(0, 0, Frame.Width / 6, 25));
reset.BackgroundColor = UIColor.Clear;
reset.SetImage(UIImage.FromBundle("Images/ImageEditor/reset_customization.png"), UIControlState.Normal);
reset.ImageView.ContentMode = UIViewContentMode.ScaleAspectFit;
reset.TouchUpInside += Reset_TouchUpInside;
topView.AddSubview(reset);
UIButton redo = new UIButton(new CGRect(Frame.Width / 6, 0, Frame.Width / 6, 25));
redo.BackgroundColor = UIColor.Clear;
redo.SetImage(UIImage.FromBundle("Images/ImageEditor/redo_customization.png"), UIControlState.Normal);
redo.ImageView.ContentMode = UIViewContentMode.ScaleAspectFit;
redo.TouchUpInside += Redo_TouchUpInside;
redo.Alpha = 0;
topView.AddSubview(redo);
UIButton undo = new UIButton(new CGRect(2 * (Frame.Width / 6), 0, Frame.Width / 6, 25));
undo.BackgroundColor = UIColor.Clear;
undo.SetImage(UIImage.FromBundle("Images/ImageEditor/undo_customization.png"), UIControlState.Normal);
undo.ImageView.ContentMode = UIViewContentMode.ScaleAspectFit;
undo.TouchUpInside += Undo_TouchUpInside;
topView.AddSubview(undo);
UIButton rect = new UIButton(new CGRect(3 * (Frame.Width / 6), 0, Frame.Width / 6, 25));
rect.BackgroundColor = UIColor.Clear;
rect.SetImage(UIImage.FromBundle("Images/ImageEditor/rect_customization.png"), UIControlState.Normal);
rect.ImageView.ContentMode = UIViewContentMode.ScaleAspectFit;
rect.TouchUpInside += Rect_TouchUpInside;
topView.AddSubview(rect);
UIButton text = new UIButton(new CGRect(4 * (Frame.Width / 6), 0, Frame.Width / 6, 25));
text.BackgroundColor = UIColor.Clear;
text.SetImage(UIImage.FromBundle("Images/ImageEditor/text_customization.png"), UIControlState.Normal);
text.ImageView.ContentMode = UIViewContentMode.ScaleAspectFit;
text.TouchUpInside += Text_TouchUpInside;
topView.AddSubview(text);
UIButton path = new UIButton(new CGRect(5 * (Frame.Width / 6), 0, Frame.Width / 6, 25));
path.SetImage(UIImage.FromBundle("Images/ImageEditor/pen_customization.png"), UIControlState.Normal);
path.ImageView.ContentMode = UIViewContentMode.ScaleAspectFit;
path.TouchUpInside += Path_TouchUpInside;
topView.AddSubview(path);
/*----------------------------------------------------------*/
//BottomView
UIView bottomView = new UIView();
bottomView.Frame = new CGRect(10, Frame.Height - 50, Frame.Width, 30);
bottomView.BackgroundColor = UIColor.Clear;
textView = new UITextField(new CGRect(20, 0, Frame.Width - 100, 30));
textView.Layer.CornerRadius = 10.0f;
textView.Layer.BorderColor = UIColor.White.CGColor;
textView.Layer.BorderWidth = 2;
textView.TextColor = UIColor.White;
textView.Placeholder = "Enter a Caption";
textView.Enabled = true;
textView.ResignFirstResponder();
textView.MultipleTouchEnabled = true;
bottomView.AddSubview(textView);
UIButton share = new UIButton(new CGRect(Frame.Width - 70, 0, 50, 30));
share.BackgroundColor = UIColor.Clear;
share.SetImage(UIImage.FromBundle("Images/ImageEditor/share_customization.png"), UIControlState.Normal);
share.ImageView.ContentMode = UIViewContentMode.ScaleAspectFit;
share.TouchUpInside += Share_TouchUpInside;
bottomView.AddSubview(share);
/*--------------------------------------------------*/
//RightView
RightView = new UIView();
RightView.Frame = new CGRect(Frame.Width - 50, 20, 30, Frame.Height );
RightView.BackgroundColor = UIColor.Clear;
//Color Collection
UIColor[] array = new UIColor[10]{ UIColor.FromRGB(68,114,196)
,UIColor.FromRGB(237,125,49)
,UIColor.FromRGB(255,192,0)
,UIColor.FromRGB(112,173,71)
,UIColor.FromRGB(91,155,213)
,UIColor.FromRGB(193,193,193)
,UIColor.FromRGB(111,111,226)
,UIColor.FromRGB(226,105,174)
,UIColor.FromRGB(158,72,14)
,UIColor.FromRGB(153,115,0)
};
int y = (int)(this.Frame.Height / 2)-175;
for (int i = 0; i < 10; i++)
{
UIButton colorButton = new UIButton();
colorButton.Frame = new CGRect(3, y + 5, 25, 25);
colorButton.Layer.CornerRadius = 10;
y = y + 30;
colorButton.BackgroundColor = array[i];
colorButton.TouchUpInside += ColorButton_TouchUpInside;
RightView.Add(colorButton);
}
mainView.AddSubview(RightView);
mainView.AddSubview(topView);
mainView.AddSubview(bottomView);
RightView.Alpha = 0;
overView = new UIView();
overView.Frame = new CGRect(0, 0, Frame.Width, Frame.Height);
overView.BackgroundColor = UIColor.Clear;
overView.Alpha = 1f;
UITapGestureRecognizer tapped = new UITapGestureRecognizer(TapCarrierLabel);
overView.AddGestureRecognizer(tapped);
AddSubview(mainView);
AddSubview(overView);
}
public void TapCarrierLabel(UITapGestureRecognizer uitgr)
{
overView.Alpha = 0;
topView.Alpha = 1;
}
void Path_TouchUpInside(object sender, EventArgs e)
{
sfImageEditor.AddShape(ShapeType.Path, new PenSettings());
settings = null;
isPath = true;
isReset = false;
isUndo = false;
isRedo = false;
isRect = false;
isText = false;
RightView.Alpha = 1;
}
void Text_TouchUpInside(object sender, EventArgs e)
{
settings = null;
isPath = false;
isReset = false;
isUndo = false;
isRedo = false;
isRect = false;
isText = true;
RightView.Alpha = 1;
sfImageEditor.AddText("Text", new TextSettings());
}
void Rect_TouchUpInside(object sender, EventArgs e)
{
settings = null;
isPath = false;
isReset = false;
isUndo = false;
isRedo = false;
isRect = true;
isText = false;
RightView.Alpha = 1;
sfImageEditor.AddShape(ShapeType.Rectangle, new PenSettings());
}
void Redo_TouchUpInside(object sender, EventArgs e)
{
isPath = false;
isReset = false;
isUndo = false;
isRedo = true;
isRect = false;
isText = false;
RightView.Alpha = 0;
sfImageEditor.Redo();
}
void Undo_TouchUpInside(object sender, EventArgs e)
{
isPath = false;
isReset = false;
isUndo = true;
isRedo = false;
isRect = false;
isText = false;
RightView.Alpha = 0;
sfImageEditor.Undo();
}
void Reset_TouchUpInside(object sender, EventArgs e)
{
isPath = false;
isReset = true;
isUndo = false;
isRedo = false;
isRect = false;
isText = false;
RightView.Alpha = 0;
sfImageEditor.Reset();
overView.Alpha = 1;
topView.Alpha = 0;
}
void Share_TouchUpInside(object sender, EventArgs e)
{
sfImageEditor.Save();
sfImageEditor.ImageSaved += SfImageEditor_ImageSaved;
}
void ColorButton_TouchUpInside(object sender, EventArgs e)
{
var colorSelected = (sender as UIButton).BackgroundColor;
if (isPath)
{
sfImageEditor.AddShape(ShapeType.Path, new PenSettings() { Color = colorSelected });
}
if (settings is TextSettings)
{
(settings as TextSettings).Color = colorSelected;
}
if (settings is PenSettings)
{
(settings as PenSettings).Color = colorSelected;
//sfImageEditor.AddShape(ShapeType.Rectangle, new PenSettings() { Color = colorSelected, StrokeWidth = 5 });
}
RightView.Alpha = 1;
}
void SfImageEditor_ImageSaved(object sender, ImageSavedEventArgs e)
{
string[] str = e.Location.Split('/');
PHFetchResult assetResult = PHAsset.FetchAssetsUsingLocalIdentifiers(str, null);
PHAsset asset = assetResult.firstObject as PHAsset;
PHImageManager.DefaultManager.RequestImageData(asset, null, async (data, dataUti, orientation, info) =>
{
UIImage newImage = new UIImage(data);
var items = new NSObject[] { newImage };
var activityController = new UIActivityViewController(items, null);
NSString[] excludedActivityTypes = null;
if (excludedActivityTypes != null && excludedActivityTypes.Length > 0)
activityController.ExcludedActivityTypes = excludedActivityTypes;
if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
{
if (activityController.PopoverPresentationController != null)
{
activityController.PopoverPresentationController.SourceView = presentController.View;
}
}
await presentController.PresentViewControllerAsync(activityController, true);
});
}
internal static UIViewController GetVisibleViewController()
{
var rootController = UIApplication.SharedApplication.KeyWindow.RootViewController;
if (rootController.PresentedViewController == null)
return rootController;
if (rootController.PresentedViewController is UINavigationController)
{
return ((UINavigationController)rootController.PresentedViewController).TopViewController;
}
if (rootController.PresentedViewController is UITabBarController)
{
return ((UITabBarController)rootController.PresentedViewController).SelectedViewController;
}
return rootController.PresentedViewController;
}
}
}
| 32.028571
| 130
| 0.680731
|
a9f848a2ed227c21471f0624416f2764fb720e67
| 491
|
php
|
PHP
|
common/components/ErrorController.php
|
mrqikear/sdpcms
|
5047ee034908c26c0698441b4b0f364afb3a64a1
|
[
"BSD-3-Clause"
] | null | null | null |
common/components/ErrorController.php
|
mrqikear/sdpcms
|
5047ee034908c26c0698441b4b0f364afb3a64a1
|
[
"BSD-3-Clause"
] | null | null | null |
common/components/ErrorController.php
|
mrqikear/sdpcms
|
5047ee034908c26c0698441b4b0f364afb3a64a1
|
[
"BSD-3-Clause"
] | null | null | null |
<?php
/**
* Created by PhpStorm.
* User: mrqi
* Date: 2020/12/18
* Time: 15:31
*/
namespace common\components;
use Yii;
use yii\helpers\Json;
class ErrorController extends \yii\web\ErrorHandler{
// protected function renderException($exception){
//
// //todo 业务处理异常
//
// echo Json::encode([
// 'message'=>$exception->getMessage(),
// 'code'=>$exception->getCode() == 0 ? 500 :$exception->getCode(),
// ]);
// }
}
| 17.535714
| 82
| 0.553971
|
f628a6f16a9f1056b1989dcb8ae8e675ae08e8a5
| 541
|
hpp
|
C++
|
lib/AnimationStation/src/Effects/StaticColor.hpp
|
ez2torta/GP2040
|
50d2aaec40e02abeb6ef6d27f58de77009b19874
|
[
"MIT"
] | 2
|
2021-08-30T23:05:29.000Z
|
2021-09-03T04:28:25.000Z
|
lib/AnimationStation/src/Effects/StaticColor.hpp
|
ez2torta/GP2040
|
50d2aaec40e02abeb6ef6d27f58de77009b19874
|
[
"MIT"
] | null | null | null |
lib/AnimationStation/src/Effects/StaticColor.hpp
|
ez2torta/GP2040
|
50d2aaec40e02abeb6ef6d27f58de77009b19874
|
[
"MIT"
] | null | null | null |
#ifndef _STATIC_COLOR_H_
#define _STATIC_COLOR_H_
#include <vector>
#include <stdio.h>
#include <stdlib.h>
#include "../Animation.hpp"
#include "../AnimationStation.hpp"
class StaticColor : public Animation {
public:
StaticColor(PixelMatrix &matrix);
StaticColor(PixelMatrix &matrix, std::vector<Pixel> &pixels);
~StaticColor() {};
void Animate(RGB (&frame)[100]);
void SaveIndexOptions(uint8_t colorIndex);
uint8_t GetColor();
void ParameterUp();
void ParameterDown();
protected:
std::vector<Pixel> *pixels;
};
#endif
| 20.807692
| 63
| 0.726433
|
7abcc437f41f9c1e1910b1fa8be0d1a9e3a9fce6
| 353
|
dart
|
Dart
|
painter/lib/app/core/localization/en-us.dart
|
AbdallahNassar/Painter
|
bd7d756b8b771f48c8667dbc062ca5db0394734e
|
[
"Apache-2.0"
] | null | null | null |
painter/lib/app/core/localization/en-us.dart
|
AbdallahNassar/Painter
|
bd7d756b8b771f48c8667dbc062ca5db0394734e
|
[
"Apache-2.0"
] | null | null | null |
painter/lib/app/core/localization/en-us.dart
|
AbdallahNassar/Painter
|
bd7d756b8b771f48c8667dbc062ca5db0394734e
|
[
"Apache-2.0"
] | null | null | null |
// this will be the dictionary for the english language
const Map<String, String> englishDictionary = {
'home_view_title': 'Painter',
'settings_view_title': 'Settings',
'got_it': 'Got it',
'color_picker_title': 'Choose a Color',
'pen_color': 'Pen Color',
'pen_type': 'Pen Type',
'pen_size': 'Pen Size',
'eraser_size': 'Eraser Size',
};
| 27.153846
| 55
| 0.677054
|
0ddb95a4861d85901d65ee2c2340e82881d7ad26
| 252
|
cs
|
C#
|
Core/KenticoKontent/Services/IKontentRateLimiter.cs
|
yuriys-kentico/KenticoKontentSharePointWordSync
|
2b58437df953f1d7dd6b34a363d6268ac5e5ef8a
|
[
"MIT"
] | null | null | null |
Core/KenticoKontent/Services/IKontentRateLimiter.cs
|
yuriys-kentico/KenticoKontentSharePointWordSync
|
2b58437df953f1d7dd6b34a363d6268ac5e5ef8a
|
[
"MIT"
] | 2
|
2021-09-03T18:54:21.000Z
|
2021-12-20T21:34:03.000Z
|
Core/KenticoKontent/Services/IKontentRateLimiter.cs
|
yuriys-kentico/KenticoKontentSharePointWordSync
|
2b58437df953f1d7dd6b34a363d6268ac5e5ef8a
|
[
"MIT"
] | 4
|
2021-02-05T20:24:18.000Z
|
2021-09-07T14:59:55.000Z
|
using System;
using System.Net.Http;
using System.Threading.Tasks;
namespace Core.KenticoKontent.Services
{
public interface IKontentRateLimiter
{
Task<HttpResponseMessage> WithRetry(Func<Task<HttpResponseMessage>> doRequest);
}
}
| 22.909091
| 87
| 0.757937
|
6424cb0ec77bf4f793c856e0cb52fe6790554016
| 26,732
|
py
|
Python
|
pyinsteon/device_types/dimmable_lighting_control.py
|
michaeldavie/pyinsteon
|
e5b2e2910f4eff1474f158051fa71f75c2077dd6
|
[
"MIT"
] | null | null | null |
pyinsteon/device_types/dimmable_lighting_control.py
|
michaeldavie/pyinsteon
|
e5b2e2910f4eff1474f158051fa71f75c2077dd6
|
[
"MIT"
] | null | null | null |
pyinsteon/device_types/dimmable_lighting_control.py
|
michaeldavie/pyinsteon
|
e5b2e2910f4eff1474f158051fa71f75c2077dd6
|
[
"MIT"
] | null | null | null |
"""Dimmable Lighting Control Devices (CATEGORY 0x01)."""
from functools import partial
from typing import Iterable
from ..constants import FanSpeed
from ..extended_property import (
LED_DIMMING,
ON_LEVEL,
RAMP_RATE,
X10_HOUSE,
X10_UNIT,
ON_MASK,
OFF_MASK,
NON_TOGGLE_MASK,
TRIGGER_GROUP_MASK,
NON_TOGGLE_ON_OFF_MASK,
)
from ..events import ON_EVENT, OFF_EVENT, ON_FAST_EVENT, OFF_FAST_EVENT
from ..groups import (
DIMMABLE_FAN,
DIMMABLE_LIGHT,
DIMMABLE_LIGHT_MAIN,
DIMMABLE_OUTLET,
ON_OFF_SWITCH_A,
ON_OFF_SWITCH_B,
ON_OFF_SWITCH_C,
ON_OFF_SWITCH_D,
ON_OFF_SWITCH_E,
ON_OFF_SWITCH_F,
ON_OFF_SWITCH_G,
ON_OFF_SWITCH_H,
)
from ..groups.on_off import OnOff
from ..groups.on_level import OnLevel
from ..handlers import ResponseStatus
from ..handlers.from_device.manual_change import ManualChangeInbound
from ..handlers.to_device.set_leds import SetLedsCommandHandler
from ..handlers.to_device.status_request import StatusRequestCommand
from ..operating_flag import (
CLEANUP_REPORT_ON,
CRC_ERROR_COUNT,
DATABASE_DELTA,
KEY_BEEP_ON,
LED_BLINK_ON_ERROR_ON,
LED_BLINK_ON_ERROR_OFF,
LED_BLINK_ON_TX_ON,
LED_OFF,
LOAD_SENSE_ON,
POWERLINE_DISABLE_ON,
PROGRAM_LOCK_ON,
RESUME_DIM_ON,
RF_DISABLE_ON,
SIGNAL_TO_NOISE_FAILURE_COUNT,
X10_OFF,
)
from .variable_responder_base import VariableResponderBase
from .commands import (
OFF_COMMAND,
OFF_FAST_COMMAND,
ON_COMMAND,
ON_FAST_COMMAND,
SET_LEDS_COMMAND,
GET_LEDS_COMMAND,
STATUS_COMMAND_FAN,
)
from ..utils import set_bit, bit_is_set, multiple_status, set_fan_speed
from .variable_controller_base import ON_LEVEL_MANAGER
class DimmableLightingControl(VariableResponderBase):
"""Dimmable Lighting Control Device."""
def _register_handlers_and_managers(self):
"""Register command handlers and managers."""
super()._register_handlers_and_managers()
for group in self._groups:
if isinstance(self._groups[group], OnLevel):
self._handlers[group]["manual_change"] = ManualChangeInbound(
self._address, group
)
def _subscribe_to_handelers_and_managers(self):
"""Subscribe methods to handlers and managers."""
super()._subscribe_to_handelers_and_managers()
for group in self._groups:
if isinstance(self._groups[group], OnLevel):
self._handlers[group]["manual_change"].subscribe(self._on_manual_change)
def _on_manual_change(self):
"""Respond to a manual change of the device."""
self.status()
class DimmableLightingControl_LampLinc(DimmableLightingControl):
"""LampLinc based dimmable lights."""
def _register_operating_flags(self):
super()._register_operating_flags()
self._add_operating_flag(PROGRAM_LOCK_ON, 0, 0, 0, 1)
self._add_operating_flag(LED_BLINK_ON_TX_ON, 0, 1, 2, 3)
self._add_operating_flag(RESUME_DIM_ON, 0, 2, 4, 5)
self._add_operating_flag(LED_OFF, 0, 4, 8, 9)
self._add_operating_flag(LOAD_SENSE_ON, 0, 5, 0x0A, 0x0B)
self._add_property(LED_DIMMING, 3, 3)
self._add_property(X10_HOUSE, 5, None)
self._add_property(X10_UNIT, 6, None)
self._add_property(RAMP_RATE, 7, 5)
self._add_property(ON_LEVEL, 8, 6)
class DimmableLightingControl_SwitchLinc(DimmableLightingControl):
"""SwichLinc based dimmable lights."""
def _register_operating_flags(self):
super()._register_operating_flags()
self._add_operating_flag(PROGRAM_LOCK_ON, 0, 0, 0, 1)
self._add_operating_flag(LED_BLINK_ON_TX_ON, 0, 1, 2, 3)
self._add_operating_flag(RESUME_DIM_ON, 0, 2, 4, 5)
self._add_operating_flag(LED_OFF, 0, 4, 8, 9)
self._add_operating_flag(KEY_BEEP_ON, 0, 5, 0x0A, 0x0B)
self._add_operating_flag(LED_BLINK_ON_ERROR_ON, 5, 2, 0x14, 0x15)
self._add_property(LED_DIMMING, 3, 3)
self._add_property(X10_HOUSE, 5, None)
self._add_property(X10_UNIT, 6, None)
self._add_property(RAMP_RATE, 7, 5)
self._add_property(ON_LEVEL, 8, 6)
class DimmableLightingControl_ToggleLinc(DimmableLightingControl):
"""SwichLinc based dimmable lights."""
def _register_operating_flags(self):
super()._register_operating_flags()
self._add_operating_flag(PROGRAM_LOCK_ON, 0, 0, 0, 1)
self._add_operating_flag(LED_BLINK_ON_TX_ON, 0, 1, 2, 3)
self._add_operating_flag(RESUME_DIM_ON, 0, 2, 4, 5)
self._add_operating_flag(KEY_BEEP_ON, 0, 5, 0x0A, 0x0B)
self._add_operating_flag(LED_BLINK_ON_ERROR_ON, 5, 2, 0x14, 0x15)
if self._firmware >= 0x3A:
self._add_property(LED_DIMMING, 2, 3)
self._add_property(X10_HOUSE, 5, None)
self._add_property(X10_UNIT, 6, None)
self._add_property(RAMP_RATE, 7, 5)
self._add_property(ON_LEVEL, 8, 6)
class DimmableLightingControl_InLineLinc(DimmableLightingControl_SwitchLinc):
"""InLineLinc based dimmable lights."""
class DimmableLightingControl_OutletLinc(DimmableLightingControl):
"""OutletLinc based dimmable lights."""
def __init__(self, address, cat, subcat, firmware=0, description="", model=""):
"""Init the DimmableLightingControl_OutletLinc class."""
buttons = {1: DIMMABLE_OUTLET}
super().__init__(
address,
cat,
subcat,
firmware=firmware,
description=description,
model=model,
buttons=buttons,
)
def _register_operating_flags(self):
super()._register_operating_flags()
self._add_operating_flag(PROGRAM_LOCK_ON, 0, 0, 0, 1)
self._add_operating_flag(LED_BLINK_ON_TX_ON, 0, 1, 2, 3)
self._add_operating_flag(LED_OFF, 0, 4, 8, 9)
self._add_property(X10_HOUSE, 5, None)
self._add_property(X10_UNIT, 6, None)
class DimmableLightingControl_DinRail(DimmableLightingControl):
"""DINRail based dimmable lights."""
def _register_operating_flags(self):
super()._register_operating_flags()
self._add_operating_flag(PROGRAM_LOCK_ON, 0, 0, 0, 1)
self._add_operating_flag(LED_BLINK_ON_TX_ON, 0, 1, 2, 3)
self._add_operating_flag(LED_OFF, 0, 4, 8, 9)
self._add_operating_flag(KEY_BEEP_ON, 0, 5, 0x0A, 0x0B)
self._add_property(LED_DIMMING, 3, 3)
self._add_property(X10_HOUSE, 5, None)
self._add_property(X10_UNIT, 6, None)
self._add_property(RAMP_RATE, 7, 5)
self._add_property(ON_LEVEL, 8, 6)
class DimmableLightingControl_FanLinc(DimmableLightingControl):
"""FanLinc model 2475F Dimmable Lighting Control.
Device Class 0x01 subcat 0x2e
"""
def __init__(self, address, cat, subcat, firmware=0, description="", model=""):
"""Init the DimmableLightingControl_FanLinc class."""
buttons = {1: DIMMABLE_LIGHT, 2: DIMMABLE_FAN}
super().__init__(
address,
cat,
subcat,
firmware=firmware,
description=description,
model=model,
buttons=buttons,
)
def fan_on(self, on_level: FanSpeed = FanSpeed.HIGH, fast=False):
"""Turn on the fan.
Parameters:
on_level: Default FanSpeed.HIGH (full on). Set the fan on level.
fast: Default False. If True, bypass device ramp rate otherwise
turn on at the ramp rate.
"""
group = 2
command = ON_FAST_COMMAND if fast else ON_COMMAND
self._handlers[group][command].send(on_level=int(set_fan_speed(on_level)))
async def async_fan_on(self, on_level: FanSpeed = FanSpeed.HIGH, fast=False):
"""Turn on the device.
Parameters:
on_level: Default FanSpeed.HIGH (full on). Set the fan on level.
fast: Default False. If True, bypass fan ramp rate otherwise
turn on at the ramp rate.
Returns a ResponseStatus value
FAILURE: Device did not acknowledge the message
SUCCESS: Device acknowledged the message
UNCLEAR: Device received the message but did not confirm the action
"""
group = 2
command = ON_FAST_COMMAND if fast else ON_COMMAND
return await self._handlers[group][command].async_send(
on_level=int(set_fan_speed(on_level))
)
def fan_off(self, fast=False):
"""Turn off the device.
Parameters:
fast: Default False. If True, bypass device ramp rate otherwise
turn on at the ramp rate.
"""
group = 2
command = OFF_FAST_COMMAND if fast else OFF_COMMAND
self._handlers[group][command].send()
async def async_fan_off(self, fast=False):
"""Turn off the device.
Parameters:
fast: Default False. If True, bypass device ramp rate otherwise
turn on at the ramp rate.
Returns a ResponseStatus value
FAILURE: Device did not acknowledge the message
SUCCESS: Device acknowledged the message
UNCLEAR: Device received the message but did not confirm the action
"""
group = 2
command = OFF_FAST_COMMAND if fast else OFF_COMMAND
return await self._handlers[group][command].async_send()
async def async_status(self):
"""Request the status fo the light and the fan."""
light_status = await super().async_status()
fan_status = await self.async_fan_status()
if light_status == fan_status == ResponseStatus.SUCCESS:
return ResponseStatus.SUCCESS
if (
light_status == ResponseStatus.UNCLEAR
or fan_status == ResponseStatus.UNCLEAR
):
return ResponseStatus.UNCLEAR
return ResponseStatus.FAILURE
def light_status(self):
"""Request the status of the light."""
super().status()
async def async_light_status(self):
"""Request the status of the light."""
return await super().async_status()
def fan_status(self):
"""Request the status of the fan."""
self._handlers[STATUS_COMMAND_FAN].send()
async def async_fan_status(self):
"""Request the status of the fan.
Returns a ResponseStatus value
FAILURE: Device did not acknowledge the message
SUCCESS: Device acknowledged the message
UNCLEAR: Device received the message but did not confirm the action
"""
return await self._handlers[STATUS_COMMAND_FAN].async_send()
def _register_handlers_and_managers(self):
super()._register_handlers_and_managers()
self._handlers[STATUS_COMMAND_FAN] = StatusRequestCommand(self._address, 3)
def _subscribe_to_handelers_and_managers(self):
super()._subscribe_to_handelers_and_managers()
self._handlers[STATUS_COMMAND_FAN].subscribe(self._handle_fan_status)
def _register_operating_flags(self):
super()._register_operating_flags()
self._add_operating_flag(PROGRAM_LOCK_ON, 0, 0, 0, 1)
self._add_operating_flag(LED_BLINK_ON_TX_ON, 0, 1, 2, 3)
self._add_operating_flag(RESUME_DIM_ON, 0, 2, 4, 5)
self._add_operating_flag(LED_OFF, 0, 4, 8, 9)
self._add_operating_flag(KEY_BEEP_ON, 0, 5, 0x0A, 0x0B)
self._add_operating_flag(RF_DISABLE_ON, 0, 6, 0x0C, 0x0D)
self._add_operating_flag(POWERLINE_DISABLE_ON, 0, 7, 0x0E, 0x0F)
self._add_operating_flag(DATABASE_DELTA, 1, None, None, None)
self._add_operating_flag(CRC_ERROR_COUNT, 2, None, None, None)
self._add_operating_flag(SIGNAL_TO_NOISE_FAILURE_COUNT, 3, None, None, None)
self._add_operating_flag(X10_OFF, 5, 1, 0x12, 0x13)
self._add_operating_flag(LED_BLINK_ON_ERROR_ON, 5, 2, 0x14, 0x15)
self._add_operating_flag(CLEANUP_REPORT_ON, 5, 3, 0x16, 0x17)
self._add_property(X10_HOUSE, 5, None)
self._add_property(X10_UNIT, 6, None)
self._add_property(RAMP_RATE, 7, 5)
self._add_property(ON_LEVEL, 8, 6)
def _handle_fan_status(self, db_version, status):
self._groups[2].set_value(status)
# TODO setup operating flags for each KPL button
# TODO trigger scenes
class DimmableLightingControl_KeypadLinc(DimmableLightingControl):
"""KeypadLinc base class."""
def __init__(
self,
address,
cat,
subcat,
firmware=0x00,
description="",
model="",
buttons=None,
):
"""Init the GeneralController_MiniRemoteBase class."""
super().__init__(
address, cat, subcat, firmware, description, model, buttons=buttons
)
async def async_on(self, on_level: int = 0xFF, group: int = 0, fast: bool = False):
"""Turn on the button LED."""
if group in [0, 1]:
result = await super().async_on(on_level=on_level, group=group, fast=fast)
else:
kwargs = self._change_led_status(led=group, is_on=True)
result = await self._handlers[SET_LEDS_COMMAND].async_send(**kwargs)
if result == ResponseStatus.SUCCESS:
event = ON_FAST_EVENT if fast else ON_EVENT
self._update_leds(group=group, value=on_level, event=event)
elif result == ResponseStatus.UNCLEAR:
await self.async_status()
return result
async def async_off(self, group: int = 0, fast: bool = False):
"""Turn off the button LED."""
if group in [0, 1]:
result = await super().async_off(group=group, fast=fast)
else:
kwargs = self._change_led_status(led=group, is_on=False)
result = await self._handlers[SET_LEDS_COMMAND].async_send(**kwargs)
if result == ResponseStatus.SUCCESS:
event = OFF_FAST_EVENT if fast else OFF_EVENT
self._update_leds(group=group, value=0, event=event)
elif result == ResponseStatus.UNCLEAR:
await self.async_status()
return result
async def async_status(self):
"""Check the status of the device."""
retries = 5
status = ResponseStatus.UNSENT
while retries and status != ResponseStatus.SUCCESS:
status0 = await super().async_status()
status1 = await self._handlers[GET_LEDS_COMMAND].async_send()
status = multiple_status(status0, status1)
retries -= 1
return status
def set_radio_buttons(self, buttons: Iterable):
"""Set a group of buttons to act as radio buttons.
This takes in a iterable set of buttons (eg. (3,4,5,6)) to act as radio buttons where
no two buttons are on at the same time.
"""
if len(buttons) < 2:
raise IndexError("At least two buttons required.")
for button in buttons:
if button not in self._buttons.keys():
raise ValueError(f"Button {button} not in button list.")
button_str = f"_{button}" if button != 1 else ""
on_mask = self._properties[f"{ON_MASK}{button_str}"]
off_mask = self._properties[f"{OFF_MASK}{button_str}"]
if not on_mask.is_loaded or not off_mask.is_loaded:
on_mask.load(0)
off_mask.load(0)
on_mask_new_value = 0
off_mask_new_value = 0
for bit in range(0, 8):
if bit + 1 in buttons:
on_mask_value = bit != button - 1
off_mask_value = bit != button - 1
else:
on_mask_value = bit_is_set(on_mask.value, bit)
off_mask_value = bit_is_set(off_mask.value, bit)
on_mask_new_value = set_bit(on_mask_new_value, bit, on_mask_value)
off_mask_new_value = set_bit(off_mask_new_value, bit, off_mask_value)
on_mask.new_value = on_mask_new_value
off_mask.new_value = off_mask_new_value
def clear_radio_buttons(self, buttons: Iterable):
"""Clear the radio button behavior of the button.
This takes in a single button number or a collection of buttons.
For any button received, the radio button behavior of that button and
any button that is grouped with that button will be cleared.
Example:
- Buttons C and D are currently radio buttons
- Call `clear_radio_buttons(3)` which represents the C button.
- Because C and D are currently grouped as radio buttons,
both C and D will have their on and off masks changed to clear the
link to the other button.
"""
other_buttons = [button for button in range(1, 9) if button not in buttons]
addl_buttons = []
for other_button in other_buttons:
button_str = f"_{other_button}" if other_button != 1 else ""
on_mask = self._properties[f"{ON_MASK}{button_str}"]
off_mask = self._properties[f"{OFF_MASK}{button_str}"]
if on_mask.is_loaded and off_mask.is_loaded:
for button in buttons:
bit = button - 1
on_set = (
bit_is_set(on_mask.new_value, bit)
if on_mask.is_dirty
else bit_is_set(on_mask.value, bit)
)
off_set = (
bit_is_set(off_mask.new_value, bit)
if off_mask.is_dirty
else bit_is_set(off_mask.value, bit)
)
if on_set or off_set and other_button not in addl_buttons:
addl_buttons.append(other_button)
continue
for button in buttons:
button_str = f"_{button}" if button != 1 else ""
on_mask = self._properties[f"{ON_MASK}{button_str}"]
off_mask = self._properties[f"{OFF_MASK}{button_str}"]
on_mask.new_value = 0
off_mask.new_value = 0
for addl_button in addl_buttons:
button_str = f"_{addl_button}" if addl_button != 1 else ""
on_mask = self._properties[f"{ON_MASK}{button_str}"]
off_mask = self._properties[f"{OFF_MASK}{button_str}"]
for button in buttons:
if on_mask.is_dirty:
on_mask.new_value = set_bit(on_mask.new_value, button - 1, False)
else:
on_mask.new_value = set_bit(on_mask.value, button - 1, False)
if off_mask.is_dirty:
off_mask.new_value = set_bit(off_mask.new_value, button - 1, False)
else:
off_mask.new_value = set_bit(off_mask.value, button - 1, False)
def set_toggle_mode(self, button: int, mode: int):
"""Set the toggle mode of a button.
Usage:
button: Integer of the button number
mode: Integer of the mode
0: Toggle
1: Non-Toggle ON only
2: Non-Toggle OFF only
"""
if button not in self._buttons.keys():
raise ValueError(f"Button {button} not in button list.")
if mode not in [0, 1, 2]:
raise ValueError(f"Mode {mode} invalid. Valid mode are [0, 1, 2]")
toggle_mask = self.properties[NON_TOGGLE_MASK]
on_off_mask = self.properties[NON_TOGGLE_ON_OFF_MASK]
if not toggle_mask.is_loaded or not on_off_mask.is_loaded:
toggle_mask.load(0)
on_off_mask.load(0)
if toggle_mask.new_value is None:
toggle_mask_test = toggle_mask.value
else:
toggle_mask_test = toggle_mask.new_value
if on_off_mask.new_value is None:
on_off_mask_test = on_off_mask.value
else:
on_off_mask_test = on_off_mask.new_value
if mode == 0:
toggle_mask.new_value = set_bit(toggle_mask_test, button - 1, False)
on_off_mask.new_value = set_bit(on_off_mask_test, button - 1, False)
elif mode == 1:
toggle_mask.new_value = set_bit(toggle_mask_test, button - 1, True)
on_off_mask.new_value = set_bit(on_off_mask_test, button - 1, True)
else:
toggle_mask.new_value = set_bit(toggle_mask_test, button - 1, True)
on_off_mask.new_value = set_bit(on_off_mask_test, button - 1, False)
def _register_handlers_and_managers(self):
super()._register_handlers_and_managers()
self._handlers[SET_LEDS_COMMAND] = SetLedsCommandHandler(address=self.address)
self._handlers[GET_LEDS_COMMAND] = StatusRequestCommand(
self._address, status_type=1
)
for group in self._groups:
if isinstance(self._groups[group], OnLevel):
self._handlers[group]["manual_change"] = ManualChangeInbound(
self._address, group
)
def _register_groups(self):
for button in self._buttons:
name = self._buttons[button]
if button == 1:
self._groups[button] = OnLevel(
name=name, address=self._address, group=button
)
else:
self._groups[button] = OnOff(
name=name, address=self._address, group=button
)
def _subscribe_to_handelers_and_managers(self):
super()._subscribe_to_handelers_and_managers()
self._handlers[GET_LEDS_COMMAND].subscribe(self._led_status)
for group in self._buttons:
if self._groups.get(group) is not None:
led_method = partial(self._led_follow_check, group=group)
self._managers[group][ON_LEVEL_MANAGER].subscribe(led_method)
def _led_follow_check(self, group, on_level):
"""Check the other LEDs to confirm if they follow the effected LED."""
for button in self._buttons:
if button == group:
continue
button_str = f"_{button}" if button != 1 else ""
on_mask = self._properties[f"{ON_MASK}{button_str}"]
off_mask = self._properties[f"{OFF_MASK}{button_str}"]
follow = bit_is_set(on_mask, group)
set_off = bit_is_set(off_mask, group)
if follow:
if set_off:
self._groups[button].value = 0
else:
self._groups[button].value = on_level
def _change_led_status(self, led, is_on):
leds = {}
for curr_led in range(1, 9):
var = "group{}".format(curr_led)
curr_group = self._groups.get(curr_led)
curr_val = bool(curr_group.value) if curr_group else False
leds[var] = is_on if curr_led == led else curr_val
return leds
def _update_leds(self, group, value, event):
"""Check if the LED is toggle or not and set value."""
if not self._groups.get(group):
return
if self._properties[NON_TOGGLE_MASK].value is not None:
non_toogle = bit_is_set(self._properties[NON_TOGGLE_MASK].value, group)
else:
non_toogle = False
if non_toogle:
self._groups[group].value = 0
else:
self._groups[group].value = value
self._events[group][event].trigger(value)
def _led_status(self, db_version, status):
"""Set the on level of the LED from a status command."""
for bit in range(2, 9):
state = self._groups.get(bit)
if state:
state.value = bit_is_set(status, bit - 1)
def _register_operating_flags(self):
"""Register operating flags."""
super()._register_operating_flags()
self._add_operating_flag(PROGRAM_LOCK_ON, 0, 0, 0, 1)
self._add_operating_flag(LED_BLINK_ON_TX_ON, 0, 1, 2, 3)
self._add_operating_flag(RESUME_DIM_ON, 0, 2, 4, 5)
self._add_operating_flag(LED_OFF, 0, 4, 8, 9)
self._add_operating_flag(KEY_BEEP_ON, 0, 5, 0x0A, 0x0B)
self._add_operating_flag(RF_DISABLE_ON, 0, 6, 0x0C, 0x0D)
self._add_operating_flag(POWERLINE_DISABLE_ON, 0, 7, 0x0E, 0x0F)
self._add_operating_flag(LED_BLINK_ON_ERROR_OFF, 5, 2, 0x14, 0x15)
self._add_property(LED_DIMMING, 9, 7, 1)
self._add_property(NON_TOGGLE_MASK, 0x0A, 0x08)
self._add_property(NON_TOGGLE_ON_OFF_MASK, 0x0D, 0x0B)
self._add_property(TRIGGER_GROUP_MASK, 0x0E, 0x0C)
for button in self._buttons:
button_str = f"_{button}" if button != 1 else ""
self._add_property(f"{ON_MASK}{button_str}", 3, 2, button)
self._add_property(f"{OFF_MASK}{button_str}", 4, 3, button)
self._add_property(f"{X10_HOUSE}{button_str}", 5, None, button)
self._add_property(f"{X10_UNIT}{button_str}", 6, None, button)
self._add_property(f"{RAMP_RATE}{button_str}", 7, 5, button)
self._add_property(f"{ON_LEVEL}{button_str}", 8, 6, button)
class DimmableLightingControl_KeypadLinc_6(DimmableLightingControl_KeypadLinc):
"""KeypadLinc 6 button dimmer."""
def __init__(self, address, cat, subcat, firmware=0x00, description="", model=""):
"""Init the DimmableLightingControl_KeypadLinc_6 class."""
buttons = {
1: DIMMABLE_LIGHT_MAIN,
3: ON_OFF_SWITCH_A,
4: ON_OFF_SWITCH_B,
5: ON_OFF_SWITCH_C,
6: ON_OFF_SWITCH_D,
}
super().__init__(
address=address,
cat=cat,
subcat=subcat,
firmware=firmware,
description=description,
model=model,
buttons=buttons,
)
class DimmableLightingControl_KeypadLinc_8(DimmableLightingControl_KeypadLinc):
"""KeypadLinc 8 button dimmer."""
def __init__(self, address, cat, subcat, firmware=0x00, description="", model=""):
"""Init the DimmableLightingControl_KeypadLinc_6 class."""
buttons = {
1: DIMMABLE_LIGHT_MAIN,
2: ON_OFF_SWITCH_B,
3: ON_OFF_SWITCH_C,
4: ON_OFF_SWITCH_D,
5: ON_OFF_SWITCH_E,
6: ON_OFF_SWITCH_F,
7: ON_OFF_SWITCH_G,
8: ON_OFF_SWITCH_H,
}
super().__init__(
address=address,
cat=cat,
subcat=subcat,
firmware=firmware,
description=description,
model=model,
buttons=buttons,
)
| 38.408046
| 93
| 0.629545
|
bb47bd49044d2c2840069c2c77e1c0eb606f3513
| 874
|
cs
|
C#
|
samples/ILAsmBinding/Project/Src/ILAsmProjectBinding.cs
|
dongdapeng110/SharpDevelopTest
|
0339adff83ca9589e700593e6d5d1e7658e7e951
|
[
"MIT"
] | 11
|
2015-05-14T08:36:05.000Z
|
2021-10-06T06:43:47.000Z
|
samples/ILAsmBinding/Project/Src/ILAsmProjectBinding.cs
|
denza/SharpDevelop
|
406354bee0e349186868288447f23301a679c95c
|
[
"MIT"
] | null | null | null |
samples/ILAsmBinding/Project/Src/ILAsmProjectBinding.cs
|
denza/SharpDevelop
|
406354bee0e349186868288447f23301a679c95c
|
[
"MIT"
] | 10
|
2015-04-08T09:02:32.000Z
|
2020-03-01T16:03:28.000Z
|
// <file>
// <copyright see="prj:///doc/copyright.txt"/>
// <license see="prj:///doc/license.txt"/>
// <owner name="Daniel Grunwald" email="daniel@danielgrunwald.de"/>
// <version>$Revision$</version>
// </file>
using System;
using System.Xml;
using ICSharpCode.SharpDevelop.Internal.Templates;
using ICSharpCode.SharpDevelop.Project;
namespace ICSharpCode.ILAsmBinding
{
public class ILAsmProjectBinding : IProjectBinding
{
public const string LanguageName = "ILAsm";
public string Language {
get {
return LanguageName;
}
}
public IProject LoadProject(ProjectLoadInformation loadInformation)
{
return new ILAsmProject(loadInformation);
}
public IProject CreateProject(ProjectCreateInformation info)
{
return new ILAsmProject(info);
}
public bool HandlingMissingProject {
get { return false; }
}
}
}
| 21.85
| 71
| 0.70595
|
013985593bc72ad240d4ea527f1338c066c9a3b4
| 6,961
|
rs
|
Rust
|
src/postfix_math.rs
|
sravan-s/clac
|
88419dae43d1242cf938a825b2b130686aa62e1c
|
[
"Apache-2.0"
] | null | null | null |
src/postfix_math.rs
|
sravan-s/clac
|
88419dae43d1242cf938a825b2b130686aa62e1c
|
[
"Apache-2.0"
] | null | null | null |
src/postfix_math.rs
|
sravan-s/clac
|
88419dae43d1242cf938a825b2b130686aa62e1c
|
[
"Apache-2.0"
] | null | null | null |
use crate::commands::Operation;
use crate::stack::Stack;
fn factorial(n: f64) -> f64 {
if n < 2.0 {
1.0
} else {
n * factorial(n - 1.0)
}
}
pub fn compute(mut variables: Stack, mut operators: Stack, mut stash: Stack) -> Stack {
while variables.len() != 0 && operators.len() != 0 {
let operator = Operation::from_str(&operators.pop().unwrap());
match operator {
Some(Operation::ArithmeticAdd) => {
let op1 = variables.pop().unwrap().parse::<f64>().unwrap();
let op2 = variables.pop().unwrap().parse::<f64>().unwrap();
let result = op1 + op2;
variables.push(result.to_string());
},
Some(Operation::ArithmeticSubstract) => {
let op1 = variables.pop().unwrap().parse::<f64>().unwrap();
let op2 = variables.pop().unwrap().parse::<f64>().unwrap();
let result = op1 - op2;
variables.push(result.to_string());
},
Some(Operation::ArithmeticDivide) => {
let op1 = variables.pop().unwrap().parse::<f64>().unwrap();
let op2 = variables.pop().unwrap().parse::<f64>().unwrap();
let result = op1 / op2;
variables.push(result.to_string());
},
Some(Operation::ArithmeticMultiply) => {
let op1 = variables.pop().unwrap().parse::<f64>().unwrap();
let op2 = variables.pop().unwrap().parse::<f64>().unwrap();
let result = op1 * op2;
variables.push(result.to_string());
},
Some(Operation::Modulo) => {
let op1 = variables.pop().unwrap().parse::<f64>().unwrap();
let op2 = variables.pop().unwrap().parse::<f64>().unwrap();
let result = op1 % op2;
variables.push(result.to_string());
},
Some(Operation::Exponentiation) => {
let op1 = variables.pop().unwrap().parse::<f64>().unwrap();
let op2 = variables.pop().unwrap().parse::<f64>().unwrap();
let result = op1.powf(op2);
variables.push(result.to_string());
},
Some(Operation::LogarithmNatural) => {
let op1 = variables.pop().unwrap().parse::<f64>().unwrap();
let result = op1.log2();
variables.push(result.to_string());
},
Some(Operation::LogarithmBaseTen) => {
let op1 = variables.pop().unwrap().parse::<f64>().unwrap();
let result = op1.log10();
variables.push(result.to_string());
},
Some(Operation::Factorial) => {
let op1 = variables.pop().unwrap().parse::<f64>().unwrap();
let result = factorial(op1);
variables.push(result.to_string());
},
Some(Operation::TrigonometrySin) => {
let op1 = variables.pop().unwrap().parse::<f64>().unwrap();
let result = op1.sin();
variables.push(result.to_string());
},
Some(Operation::TrigonometryCos) => {
let op1 = variables.pop().unwrap().parse::<f64>().unwrap();
let result = op1.cos();
variables.push(result.to_string());
},
Some(Operation::TrigonometryTan) => {
let op1 = variables.pop().unwrap().parse::<f64>().unwrap();
let result = op1.tan();
variables.push(result.to_string());
},
Some(Operation::TrigonometryASin) => {
let op1 = variables.pop().unwrap().parse::<f64>().unwrap();
let result = op1.asin();
variables.push(result.to_string());
},
Some(Operation::TrigonometryACos) => {
let op1 = variables.pop().unwrap().parse::<f64>().unwrap();
let result = op1.acos();
variables.push(result.to_string());
},
Some(Operation::TrigonometryATan) => {
let op1 = variables.pop().unwrap().parse::<f64>().unwrap();
let result = op1.atan();
variables.push(result.to_string());
},
Some(Operation::TrigonometryATanTwo) => {
let op1 = variables.pop().unwrap().parse::<f64>().unwrap();
let op2 = variables.pop().unwrap().parse::<f64>().unwrap();
let result = op1.atan2(op2);
variables.push(result.to_string());
},
Some(Operation::ErrorFunction) => {
// to implement
},
Some(Operation::SummationSum) => {
let mut sum: f64 = 0.0;
while variables.len() != 0 {
let op1 = variables.pop().unwrap().parse::<f64>().unwrap();
sum += op1;
}
variables.push(sum.to_string());
},
Some(Operation::SummationSubstract) => {
let mut diff: f64 = 0.0;
while variables.len() != 0 {
let op1 = variables.pop().unwrap().parse::<f64>().unwrap();
diff -= op1;
}
variables.push(diff.to_string());
},
Some(Operation::RoundingCeil) => {
let op1 = variables.pop().unwrap().parse::<f64>().unwrap();
let result = op1.ceil();
variables.push(result.to_string());
},
Some(Operation::RoundingFloor) => {
let op1 = variables.pop().unwrap().parse::<f64>().unwrap();
let result = op1.floor();
variables.push(result.to_string());
},
Some(Operation::RoundingRound) => {
let op1 = variables.pop().unwrap().parse::<f64>().unwrap();
let result = op1.round();
variables.push(result.to_string());
},
Some(Operation::Absolute) => {
let op1 = variables.pop().unwrap().parse::<f64>().unwrap();
let result = op1.abs();
variables.push(result.to_string());
},
Some(Operation::StackSwap) => {
let op1 = variables.pop().unwrap();
let op2 = variables.pop().unwrap();
variables.push(op2);
variables.push(op1);
},
Some(Operation::StackDup) => {
let op1 = variables.pop().unwrap();
variables.push(op1.clone());
variables.push(op1.clone());
},
Some(Operation::StackRoll) => {
// to implement
// https://www.ugrad.math.ubc.ca/Flat/stack.html
},
Some(Operation::StackDrop) => {
variables.pop();
},
Some(Operation::StackClear) => {
while variables.len() != 0 {
variables.pop();
}
},
Some(Operation::StackCount) => {
let len = variables.len();
variables.push(len.to_string());
},
Some(Operation::StashingStashTop) => {
let op1 = variables.pop().unwrap();
stash.push(op1);
},
Some(Operation::StashingFetchTop) => {
let op1 = stash.pop().unwrap();
variables.push(op1);
},
Some(Operation::StashingStashAll) => {
while variables.len() != 0 {
stash.push(variables.pop().unwrap());
}
},
Some(Operation::StashingFetchAll) => {
while stash.len() != 0 {
variables.push(stash.pop().unwrap());
}
},
_ => println!("Done!"),
}
}
println!("variables: {:?}", variables.items);
println!("operations: {:?}", variables.items);
println!("stash: {:?}", stash.items);
Stack::init(10)
}
| 35.697436
| 87
| 0.5436
|
6231a09df9595b436a5b0de6a7344cd3607b0724
| 1,619
|
dart
|
Dart
|
test/brazil/cnpj_strip_test.dart
|
rafamizes/formdator
|
c2280cb529ce78de95475c9f31a7159a100a3e28
|
[
"MIT"
] | 5
|
2021-05-24T22:40:51.000Z
|
2021-05-31T23:13:10.000Z
|
test/brazil/cnpj_strip_test.dart
|
rafamizes/formdator
|
c2280cb529ce78de95475c9f31a7159a100a3e28
|
[
"MIT"
] | 131
|
2021-06-16T22:40:59.000Z
|
2022-01-29T00:29:11.000Z
|
test/brazil/cnpj_strip_test.dart
|
rafamizes/formdator
|
c2280cb529ce78de95475c9f31a7159a100a3e28
|
[
"MIT"
] | 2
|
2021-05-24T22:40:22.000Z
|
2021-05-25T02:40:33.000Z
|
import 'package:formdator/formdator.dart';
import 'package:test/test.dart';
void main() {
group('CnpjStrip', () {
group('valid CNPJs', () {
test('masked', () {
expect(const CnpjStrip('34.600.728/0001-76').value, '34600728000176');
expect(const CnpjStrip('41.831.918/0001-60').value, '41831918000160');
expect(const CnpjStrip('89.161.992/0001-42').value, '89161992000142');
});
test('unmasked (plain)', () {
const unmasked = ['34600728000176', '41831918000160', '89161992000142'];
for (int i = 0; i < unmasked.length; i++) {
expect(CnpjStrip(unmasked[i]).value, unmasked[i]);
}
});
});
group('invalid CNPJs', () {
test('malformed CNPJs', () {
const malformed = [
'34.600/728000.177',
'41.831.918000161',
'89.161.992/001-43'
];
for (int i = 0; i < malformed.length; i++) {
expect(CnpjStrip(malformed[i]).value, null);
}
});
test('empty string', () {
expect(const CnpjStrip('').value, null);
});
test('unmasked less than 14 characteres', () {
expect(const CnpjStrip('3460072800017').value, null);
});
test('unmasked more than 14 characteres', () {
expect(const CnpjStrip('034600728000176').value, null);
});
test('masked less than 18 characteres', () {
expect(const CnpjStrip('34.600.728/0001-7').value, null);
});
test('masked more than 18 characteres', () {
expect(const CnpjStrip('034.600.728/0001-76').value, null);
});
});
});
}
| 33.040816
| 80
| 0.551575
|
a3537983a548cf93e10e8ed51a629f46925b5e30
| 1,260
|
ts
|
TypeScript
|
packages/ddd-fwk-infra-test/src/index.spec.ts
|
tmorin/p2p-fwk
|
8e9c15a571b1f2becb57a978790412dcbf747763
|
[
"MIT"
] | null | null | null |
packages/ddd-fwk-infra-test/src/index.spec.ts
|
tmorin/p2p-fwk
|
8e9c15a571b1f2becb57a978790412dcbf747763
|
[
"MIT"
] | null | null | null |
packages/ddd-fwk-infra-test/src/index.spec.ts
|
tmorin/p2p-fwk
|
8e9c15a571b1f2becb57a978790412dcbf747763
|
[
"MIT"
] | null | null | null |
import {Event} from '@tmorin/ddd-fwk-model-core';
import {FwkInfraTestContainers} from './FwkInfraTestContainers';
import {waitForMany, waitForOnce} from '@tmorin/ddd-fwk-model-test';
class EventA extends Event {
constructor() {
super(undefined, EventA.name);
}
}
class EventB extends Event {
constructor() {
super(undefined, EventB.name);
}
}
describe('fwk-infra-test', function () {
it('should wait for an event', async function () {
const containers = await FwkInfraTestContainers.create();
const [container1] = await containers.startContainers(1);
const pWaitForOnce = waitForOnce(container1, EventA.name);
await container1.messageBus.publish(new EventA());
await pWaitForOnce;
await containers.disposeContainers();
});
it('should wait for many events', async function () {
const containers = await FwkInfraTestContainers.create();
const [container1] = await containers.startContainers(1);
const pWaitForMany = waitForMany(container1, EventB.name, 3);
await container1.messageBus.publish(new EventB());
await container1.messageBus.publish(new EventB());
await container1.messageBus.publish(new EventB());
await pWaitForMany;
await containers.disposeContainers();
});
})
| 31.5
| 68
| 0.719841
|
39c644cfd33f65f6f5bbcd186257db1c7116727a
| 16,127
|
rs
|
Rust
|
src/disk_format/apple/nibble.rs
|
jgerrish/image-rider
|
48a1073bf37e3a5fbf832330bb2573f464412996
|
[
"MIT"
] | null | null | null |
src/disk_format/apple/nibble.rs
|
jgerrish/image-rider
|
48a1073bf37e3a5fbf832330bb2573f464412996
|
[
"MIT"
] | null | null | null |
src/disk_format/apple/nibble.rs
|
jgerrish/image-rider
|
48a1073bf37e3a5fbf832330bb2573f464412996
|
[
"MIT"
] | null | null | null |
/// Encoding and Decoding Nibble-based disk formats
use std::collections::BTreeMap;
use std::fs::File;
use std::io::Write;
use std::path::PathBuf;
use config::Config;
use log::error;
use nom::bytes::complete::{take, take_until};
use nom::multi::many0;
use nom::number::complete::le_u8;
use nom::IResult;
use crate::disk_format::apple::disk::{format_from_filename, AppleDisk, AppleDiskData};
use crate::disk_format::image::{DiskImage, DiskImageParser};
// const NIBBLE_WRITE_TABLE_6_AND_2: [u8; 64] = [
// 0x96,0x97,0x9A,0x9B,0x9D,0x9E,0x9F,0xA6,
// 0xA7,0xAB,0xAC,0xAD,0xAE,0xAF,0xB2,0xB3,
// 0xB4,0xB5,0xB6,0xB7,0xB9,0xBA,0xBB,0xBC,
// 0xBD,0xBE,0xBF,0xCB,0xCD,0xCE,0xCF,0xD3,
// 0xD6,0xD7,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,
// 0xDF,0xE5,0xE6,0xE7,0xE9,0xEA,0xEB,0xEC,
// 0xED,0xEE,0xEF,0xF2,0xF3,0xF4,0xF5,0xF6,
// 0xF7,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF
// ];
const NIBBLE_READ_TABLE_6_AND_2: [u8; 256] = [
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x02, 0x03, 0x00, 0x04, 0x05, 0x06,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x08, 0x00, 0x00, 0x00, 0x09, 0x0A, 0x0B, 0x0C, 0x0D,
0x00, 0x00, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x00, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1B, 0x00, 0x1C, 0x1D, 0x1E,
0x00, 0x00, 0x00, 0x1F, 0x00, 0x00, 0x20, 0x21, 0x00, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28,
0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x2A, 0x2B, 0x00, 0x2C, 0x2D, 0x2E, 0x2F, 0x30, 0x31, 0x32,
0x00, 0x00, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x00, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F,
];
/// Parse a single byte encoded in 4 and 4 nibble format
/// This is used to encode the volume, track, sector and checksum fields
/// in the address field
pub fn parse_nibble_byte_4_and_4(i: &[u8]) -> IResult<&[u8], u8> {
let (i, bytes) = take(2_usize)(i)?;
let byte = ((bytes[0] << 1) | 0x01) & bytes[1];
Ok((i, byte))
}
/// An address field identifies the data field that follows it
pub struct AddressField {
/// The volume of the track
pub volume: u8,
/// The track of the track
pub track: u8,
/// The sector of the track
pub sector: u8,
/// The checksum of the address field
pub checksum: u8,
}
/// Find and parse an address field in the nibblized file
pub fn find_and_parse_address_field(
config: &Config,
) -> impl Fn(&[u8]) -> IResult<&[u8], AddressField> + '_ {
// Find the first field
// Read in the address field
// 3 byte prologue (D5 AA 96)
// 2 byte odd-even encoded volume:
// odd (D_7 D_5 D_3 D_1) followed by even (D_6 D_4 D_2 D_0)
// 2 byte odd-even encoded track
// 2 byte odd-even encoded sector
// 2 byte odd-even encoded checksum
// Epilogue DE AA EB
// debug!("Searching 1");
move |i| {
let (i, _data) = take_until(&[0xD5, 0xAA, 0x96][..])(i)?;
let (i, _prologue) = take(3_usize)(i)?;
// let (_i, volume_data) = take(2_usize)(i)?;
let (i, volume) = parse_nibble_byte_4_and_4(i)?;
// let (_i, track_data) = take(2_usize)(i)?;
let (i, track) = parse_nibble_byte_4_and_4(i)?;
// let (_i, sector_data) = take(2_usize)(i)?;
let (i, sector) = parse_nibble_byte_4_and_4(i)?;
// let (_i, checksum_data) = take(2_usize)(i)?;
let (i, checksum) = parse_nibble_byte_4_and_4(i)?;
let (i, _epilogue) = take(3_usize)(i)?;
// debug!(
// "Found address field: volume: {:?}, {}, track: {:?} {}, sector: {:?} {}, checksum: {:?} {}",
// volume_data, volume, track_data, track, sector_data, sector, checksum_data, checksum
// );
let computed_checksum = volume ^ track ^ sector;
let address_field = AddressField {
volume,
track,
sector,
checksum,
};
if computed_checksum != checksum {
error!(
"Address field computed checksum not equal to disk checksum: {} {}",
computed_checksum, checksum
);
if !config.get_bool("ignore-checksums").unwrap_or(false) {
panic!(
"Address field computed checksum not equal to disk checksum: {} {}",
computed_checksum, checksum
);
}
}
Ok((i, address_field))
}
}
/// A 6 and 2 encoded data field that follows an address field in a nibblized image
pub struct DataField {
/// 342 bytes of data, encoded as 6 and 2
pub data: Vec<u8>,
/// The checksum of the data
pub checksum: u8,
}
/// Parse the data component of a data field
pub fn parse_6_and_2_nibblized_data(i: &[u8]) -> Vec<u8> {
let data: Vec<u8> = i
.iter()
.map(|b| NIBBLE_READ_TABLE_6_AND_2[(*b & 0x7F) as usize])
.collect();
data
}
/// Find and parse a data field in the nibblized file
pub fn find_and_parse_data_field(i: &[u8]) -> IResult<&[u8], DataField> {
// Find the next sequence of 0xD5 0xAA 0xAD that identifies a field
// let (i, find_tag) = tag([0xD5, 0xAA, 0xAD])(i)?;
// Find the first field
let (i, _data) = take_until(&[0xD5, 0xAA, 0xAD][..])(i)?;
// Read in the data field
// 3 byte prologue (D5 AA AD)
// 342 bytes data, 6 and 2 encoded
// 1 byte checksum
// Epilogue DE AA EB
let (i, _prologue) = take(3_usize)(i)?;
let (i, data) = take(342_usize)(i)?;
let (i, checksum) = le_u8(i)?;
// let (i, _epilogue) = tag(&[0xDE, 0xAA, 0xEB][..])(i)?;
let (i, _epilogue) = take(3_usize)(i)?;
Ok((
i,
DataField {
data: data.to_vec(),
checksum,
},
))
}
/// A 256-byte 8-bit data structure computed from 6 and 2 data
#[derive(Clone)]
pub struct Sector {
/// The data
pub data: Vec<u8>,
}
/// Transform a 6 and 2 data field to a 256-byte sector
pub fn transform_data_field(config: &Config, data_field: &DataField) -> Sector {
// The data is split up into several different sections
// The first 0x56 bytes are the "auxiliary data buffer"
// Starting at offset 0x56 the 6 bit bytes are stored
// Two references that explain the encoding and decoding:
// Beneath Apple DOS and Beneath Apple ProDOS
// The source code for AppleCommander and apple2emu was invaluable
// in writing this code
// let mut data = parse_6_and_2_nibblized_data(data);
let mut computed_checksum: u8 = 0;
// let mut xor_value = 0;
let data_field_data_size = data_field.data.len();
let mut buffer = [0; 342];
let mut data = [0; 256];
// Optimize later
// First, understand the algorithm and disk data structure
for (index, byte) in data_field.data.iter().enumerate() {
computed_checksum ^= NIBBLE_READ_TABLE_6_AND_2[(*byte) as usize];
if index < 0x56 {
// The - 1 is probably optimized away by the compiler
buffer[data_field_data_size - index - 1] = computed_checksum;
} else {
buffer[index - 0x56] = computed_checksum;
}
}
if computed_checksum != data_field.checksum {
error!(
"Invalid checksum on data: calculated: {}, disk: {}",
computed_checksum, data_field.checksum
);
if !config.get_bool("ignore-checksums").unwrap_or(false) {
panic!("Invalid checksum on data");
}
}
let reverse_values = [0x00, 0x02, 0x01, 0x03];
for i in 0..=255 {
let byte_1 = buffer[i];
let nibble_low = buffer.len() - (i % 0x56) - 1;
let byte_2 = buffer[nibble_low];
let shift_pairs = (i / 0x56) * 2;
let byte: u8 = (byte_1 << 2) | reverse_values[((byte_2 >> shift_pairs) & 0x03) as usize];
data[i] = byte;
}
Sector {
data: data.to_vec(),
}
}
/// A single track on the disk
#[derive(Default)]
pub struct Track {
/// The sectors on the disk
pub sectors: BTreeMap<u8, Sector>,
}
/// A single volume on the disk
#[derive(Default)]
pub struct Volume {
/// The tracks on the disk
pub tracks: BTreeMap<u8, Track>,
}
/// A Nibble encoded disk
/// (although this is generic enough a module-wide data structure
/// could be used)
#[derive(Default)]
pub struct NibbleDisk {
/// The sectors on the disk
pub volumes: BTreeMap<u8, Volume>,
}
impl DiskImageParser for NibbleDisk {
fn parse_disk_image<'a>(
config: &Config,
filename: &str,
data: &'a [u8],
) -> IResult<&'a [u8], DiskImage<'a>> {
let guess_option = format_from_filename(filename);
match guess_option {
Some(guess) => {
let (i, disk) = parse_nib_disk(config)(data)?;
Ok((
i,
DiskImage::Apple(AppleDisk {
encoding: guess.encoding,
format: guess.format,
data: AppleDiskData::Nibble(disk),
}),
))
}
None => {
panic!("Invalid format");
}
}
}
fn save_disk_image(&self, _config: &Config, filename: &str) {
let filename = PathBuf::from(filename);
let file_result = File::create(filename);
match file_result {
Ok(mut file) => {
for volume in self.volumes.values() {
for track in volume.tracks.values() {
for sector in track.sectors.values() {
file.write_all(§or.data).unwrap();
}
}
}
}
Err(e) => error!("Error opening file: {}", e),
}
}
}
/// A field, containing both the data field and address field
pub struct Field {
/// The address field, which contains volume, track and sector info indicating
/// where this sector is located on the disk
/// It also contains a checksum
pub address_field: AddressField,
/// The data field, which contains the data and checksum
pub data_field: DataField,
}
/// Parse an address field, data field and build a Sector
/// TODO: Maybe use one of the fold combinators
pub fn parse_nib_sector(config: &Config) -> impl Fn(&[u8]) -> IResult<&[u8], Field> + '_ {
move |i| {
let (i, header) = find_and_parse_address_field(config)(i)?;
let (i, data_field) = find_and_parse_data_field(i)?;
Ok((
i,
Field {
address_field: header,
data_field,
},
))
}
}
/// Parse an entire nibble encoded disk
pub fn parse_nib_disk(config: &Config) -> impl Fn(&[u8]) -> IResult<&[u8], NibbleDisk> + '_ {
move |i| {
let (i, fields) = many0(parse_nib_sector(config))(i)?;
let mut disk = NibbleDisk::default();
for field in &fields {
let volume = disk.volumes.entry(field.address_field.volume);
let track = volume.or_default().tracks.entry(field.address_field.track);
let sector = track.or_default().sectors.entry(field.address_field.sector);
sector.or_insert_with(|| transform_data_field(config, &field.data_field));
}
Ok((i, disk))
}
}
#[cfg(test)]
mod tests {
use super::{find_and_parse_address_field, parse_nibble_byte_4_and_4};
use config::Config;
/// Test nibble byte 4 and 4 parsing works
#[test]
fn parse_nibble_byte_4_and_4_works() {
let volume_data: [u8; 2] = [0xFF, 0xFE];
let track_data: [u8; 2] = [0xAB, 0xBF];
let sector_data: [u8; 2] = [0xAA, 0xAF];
let checksum_data: [u8; 2] = [0xFE, 0xEE];
let zero_data: [u8; 2] = [0x00, 0x00];
let one_data: [u8; 2] = [0x00, 0x01];
let volume_result = parse_nibble_byte_4_and_4(&volume_data);
match volume_result {
Ok(volume) => {
assert_eq!(volume.1, 0xFE);
}
Err(e) => {
panic!("Parser failed: {}", e);
}
}
let track_result = parse_nibble_byte_4_and_4(&track_data);
match track_result {
Ok(track) => {
assert_eq!(track.1, 0x17);
}
Err(e) => {
panic!("Parser failed: {}", e);
}
}
let sector_result = parse_nibble_byte_4_and_4(§or_data);
match sector_result {
Ok(sector) => {
assert_eq!(sector.1, 0x05);
}
Err(e) => {
panic!("Parser failed: {}", e);
}
}
let checksum_result = parse_nibble_byte_4_and_4(&checksum_data);
match checksum_result {
Ok(checksum) => {
assert_eq!(checksum.1, 0xEC);
}
Err(e) => {
panic!("Parser failed: {}", e);
}
}
let zero_result = parse_nibble_byte_4_and_4(&zero_data);
match zero_result {
Ok(zero) => {
assert_eq!(zero.1, 0x00);
}
Err(e) => {
panic!("Parser failed: {}", e);
}
}
let one_result = parse_nibble_byte_4_and_4(&one_data);
match one_result {
Ok(one) => {
assert_eq!(one.1, 0x01);
}
Err(e) => {
panic!("Parser failed: {}", e);
}
}
}
/// Test find_and_parse_address_field with valid data
#[test]
fn find_and_parse_address_field_works() {
// volume: 254, track: 23, sector: 5
let address_field_data: [u8; 14] = [
0xD5, 0xAA, 0x96, 0xFF, 0xFE, 0xAB, 0xBF, 0xAA, 0xAF, 0xFE, 0xEE, 0xDE, 0xAA, 0xEB,
];
let config = Config::default();
let address_field_result = find_and_parse_address_field(&config)(&address_field_data);
match address_field_result {
Ok(address_field) => {
assert_eq!(address_field.1.volume, 0xFE);
assert_eq!(address_field.1.track, 0x17);
assert_eq!(address_field.1.sector, 0x05);
assert_eq!(address_field.1.checksum, 0xEC);
}
Err(e) => {
panic!("Parsing error: {}", e);
}
}
}
/// Test find_and_parse_address_field with invalid checksum
#[test]
#[should_panic(expected = "Address field computed checksum not equal to disk checksum: 236 0")]
fn find_and_parse_address_field_panics_with_invalid_checksum() {
// volume: 254, track: 23, sector: 5
let address_field_data: [u8; 14] = [
0xD5, 0xAA, 0x96, 0xFF, 0xFE, 0xAB, 0xBF, 0xAA, 0xAF, 0x00, 0x00, 0xDE, 0xAA, 0xEB,
];
let config = Config::default();
let address_field_result = find_and_parse_address_field(&config)(&address_field_data);
match address_field_result {
Ok(_address_field) => {
panic!("Should fail with checksum error");
}
Err(_e) => {
panic!("Should fail with checksum error");
}
}
}
}
| 34.312766
| 107
| 0.569356
|
33c2ff8edb0d7c00e51b9c543f0be879a86380de
| 16,770
|
c
|
C
|
modules/Scene/Scene/src/Scene.c
|
akb825/DeepSea
|
fff790d0a472cf2f9f89de653e0b4470ce605d24
|
[
"Apache-2.0"
] | 5
|
2018-11-17T23:13:22.000Z
|
2021-09-30T13:37:04.000Z
|
modules/Scene/Scene/src/Scene.c
|
akb825/DeepSea
|
fff790d0a472cf2f9f89de653e0b4470ce605d24
|
[
"Apache-2.0"
] | null | null | null |
modules/Scene/Scene/src/Scene.c
|
akb825/DeepSea
|
fff790d0a472cf2f9f89de653e0b4470ce605d24
|
[
"Apache-2.0"
] | 2
|
2019-09-23T12:23:35.000Z
|
2020-04-07T05:31:06.000Z
|
/*
* Copyright 2019-2020 Aaron Barany
*
* 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.
*/
#include <DeepSea/Scene/Scene.h>
#include "Nodes/SceneTreeNode.h"
#include "SceneTypes.h"
#include <DeepSea/Core/Containers/Hash.h>
#include <DeepSea/Core/Containers/HashTable.h>
#include <DeepSea/Core/Memory/Allocator.h>
#include <DeepSea/Core/Memory/BufferAllocator.h>
#include <DeepSea/Core/Streams/FileStream.h>
#include <DeepSea/Core/Streams/ResourceStream.h>
#include <DeepSea/Core/Streams/Stream.h>
#include <DeepSea/Core/Assert.h>
#include <DeepSea/Core/Error.h>
#include <DeepSea/Core/Log.h>
#include <DeepSea/Core/Profile.h>
#include <DeepSea/Math/Matrix44.h>
#include <DeepSea/Scene/ItemLists/SceneItemList.h>
#include <DeepSea/Scene/Nodes/SceneNode.h>
#include <DeepSea/Scene/SceneGlobalData.h>
#include <DeepSea/Scene/SceneLoadScratchData.h>
#include <DeepSea/Scene/SceneRenderPass.h>
#include <string.h>
static void destroyObjects(const dsSceneItemLists* sharedItems, uint32_t sharedItemCount,
const dsScenePipelineItem* pipeline, uint32_t pipelineCount,
dsSceneGlobalData* const* globalData, uint32_t globalDataCount, void* userData,
dsDestroySceneUserDataFunction destroyUserDataFunc)
{
if (sharedItems)
{
for (uint32_t i = 0; i < sharedItemCount; ++i)
{
const dsSceneItemLists* itemLists = sharedItems + i;
for (uint32_t j = 0; j < itemLists->count; ++j)
dsSceneItemList_destroy(itemLists->itemLists[j]);
}
}
if (pipeline)
{
for (uint32_t i = 0; i < pipelineCount; ++i)
{
dsSceneRenderPass_destroy(pipeline[i].renderPass);
dsSceneItemList_destroy(pipeline[i].computeItems);
}
}
if (globalData)
{
for (uint32_t i = 0; i < globalDataCount; ++i)
dsSceneGlobalData_destroy(globalData[i]);
}
if (destroyUserDataFunc)
destroyUserDataFunc(userData);
}
static size_t fullAllocSize(uint32_t* outNameCount, const dsSceneItemLists* sharedItems,
uint32_t sharedItemCount, const dsScenePipelineItem* pipeline, uint32_t pipelineCount,
dsSceneGlobalData* const* globalData, uint32_t globalDataCount)
{
size_t fullSize = DS_ALIGNED_SIZE(sizeof(dsScene)) +
DS_ALIGNED_SIZE(sizeof(dsSceneItemList)*sharedItemCount) +
DS_ALIGNED_SIZE(sizeof(dsScenePipelineItem)*pipelineCount) +
DS_ALIGNED_SIZE(sizeof(dsSceneGlobalData*)*globalDataCount);
*outNameCount = 0;
for (uint32_t i = 0; i < sharedItemCount; ++i)
{
const dsSceneItemLists* itemLists = sharedItems + i;
if (sharedItems[i].count > 0 && !itemLists->itemLists)
return 0;
for (uint32_t j = 0; j < itemLists->count; ++j)
{
if (!itemLists->itemLists[j])
return 0;
}
*outNameCount += itemLists->count;
fullSize += DS_ALIGNED_SIZE(sizeof(dsSceneItemList*)*itemLists->count);
}
for (uint32_t i = 0; i < pipelineCount; ++i)
{
const dsScenePipelineItem* item = pipeline + i;
if ((item->renderPass && item->computeItems) ||
(!item->renderPass && !item->computeItems))
{
DS_LOG_ERROR(DS_SCENE_LOG_TAG,
"A scene pipeline item must contain either a render pass or a compute item.");
return 0;
}
if (item->renderPass)
{
const dsRenderPass* baseRenderPass = item->renderPass->renderPass;
for (uint32_t j = 0; j < baseRenderPass->subpassCount; ++j)
{
const dsSceneItemLists* items = item->renderPass->drawLists + j;
for (uint32_t k = 0; k < items->count; ++k)
{
if (!items->itemLists[k])
return 0;
}
*outNameCount += items->count;
}
}
else
++*outNameCount;
}
for (uint32_t i = 0; i < globalDataCount; ++i)
{
if (!globalData[i])
return 0;
}
return fullSize + dsHashTable_fullAllocSize(dsHashTable_getTableSize(*outNameCount)) +
DS_ALIGNED_SIZE(sizeof(dsSceneItemListNode)**outNameCount);
}
static bool insertSceneList(dsHashTable* hashTable, dsSceneItemListNode* node,
dsSceneItemList* list)
{
node->list = list;
if (!dsHashTable_insert(hashTable, list->name, (dsHashTableNode*)node, NULL))
{
DS_LOG_ERROR_F(DS_SCENE_LOG_TAG, "Scene item list '%s' isn't unique within the scene.",
node->list->name);
return false;
}
return true;
}
static void dummyDestroyFunc(dsSceneNode* node)
{
DS_UNUSED(node);
}
dsScene* dsScene_loadImpl(dsAllocator* allocator, dsAllocator* resourceAllocator,
const dsSceneLoadContext* loadContext, dsSceneLoadScratchData* scratchData, const void* data,
size_t dataSize, void* userData, dsDestroySceneUserDataFunction destroyUserDataFunc,
const char* fileName);
dsScene* dsScene_create(dsAllocator* allocator, dsRenderer* renderer,
const dsSceneItemLists* sharedItems, uint32_t sharedItemCount,
const dsScenePipelineItem* pipeline, uint32_t pipelineCount,
dsSceneGlobalData* const* globalData, uint32_t globalDataCount, void* userData,
dsDestroySceneUserDataFunction destroyUserDataFunc)
{
if (!allocator || !renderer || (!sharedItems && sharedItemCount > 0) || !pipeline ||
pipelineCount == 0 || (!globalData && globalDataCount > 0))
{
errno = EINVAL;
destroyObjects(sharedItems, sharedItemCount, pipeline, pipelineCount, globalData,
globalDataCount, userData, destroyUserDataFunc);
return NULL;
}
if (!allocator->freeFunc)
{
errno = EINVAL;
DS_LOG_ERROR(DS_SCENE_LOG_TAG, "Scene allocator must support freeing memory.");
destroyObjects(sharedItems, sharedItemCount, pipeline, pipelineCount, globalData,
globalDataCount, userData, destroyUserDataFunc);
return NULL;
}
uint32_t nameCount;
size_t fullSize = fullAllocSize(&nameCount, sharedItems, sharedItemCount, pipeline,
pipelineCount, globalData, globalDataCount);
if (fullSize == 0)
{
errno = EINVAL;
destroyObjects(sharedItems, sharedItemCount, pipeline, pipelineCount, globalData,
globalDataCount, userData, destroyUserDataFunc);
return NULL;
}
void* buffer = dsAllocator_alloc(allocator, fullSize);
if (!buffer)
{
destroyObjects(sharedItems, sharedItemCount, pipeline, pipelineCount, globalData,
globalDataCount, userData, destroyUserDataFunc);
return NULL;
}
dsBufferAllocator bufferAlloc;
DS_VERIFY(dsBufferAllocator_initialize(&bufferAlloc, buffer, fullSize));
dsScene* scene = DS_ALLOCATE_OBJECT(&bufferAlloc, dsScene);
DS_ASSERT(scene);
scene->allocator = dsAllocator_keepPointer(allocator);
scene->renderer = renderer;
scene->userData = userData;
scene->destroyUserDataFunc = destroyUserDataFunc;
DS_VERIFY(dsSceneNode_initialize(&scene->rootNode, allocator, &dsRootSceneNodeType, NULL, 0,
&dummyDestroyFunc));
dsSceneTreeNode* rootTreeNode = &scene->rootTreeNode.node;
rootTreeNode->allocator = allocator;
rootTreeNode->node = &scene->rootNode;
rootTreeNode->parent = NULL;
rootTreeNode->children = NULL;
rootTreeNode->itemLists = NULL;
rootTreeNode->childCount = 0;
rootTreeNode->maxChildren = 0;
dsMatrix44_identity(rootTreeNode->transform);
rootTreeNode->dirty = false;
scene->rootTreeNode.scene = scene;
scene->rootTreeNodePtr = (dsSceneTreeNode*)&scene->rootTreeNode;
scene->rootNode.treeNodes = &scene->rootTreeNodePtr;
scene->rootNode.treeNodeCount = 1;
scene->rootNode.maxTreeNodes = 1;
if (sharedItemCount > 0)
{
scene->sharedItems =
DS_ALLOCATE_OBJECT_ARRAY(&bufferAlloc, dsSceneItemLists, sharedItemCount);
DS_ASSERT(scene->sharedItems);
for (uint32_t i = 0; i < sharedItemCount; ++i)
{
const dsSceneItemLists* origItemLists = sharedItems + i;
dsSceneItemLists* itemLists = scene->sharedItems + i;
itemLists->count = origItemLists->count;
if (itemLists->count)
{
itemLists->itemLists = DS_ALLOCATE_OBJECT_ARRAY(&bufferAlloc, dsSceneItemList*,
itemLists->count);
DS_ASSERT(itemLists->itemLists);
memcpy(itemLists->itemLists, origItemLists->itemLists,
sizeof(dsSceneItemLists*)*itemLists->count);
}
else
itemLists->itemLists = NULL;
}
}
else
scene->sharedItems = NULL;
scene->sharedItemCount = sharedItemCount;
scene->pipeline = DS_ALLOCATE_OBJECT_ARRAY(&bufferAlloc, dsScenePipelineItem, pipelineCount);
DS_ASSERT(scene->pipeline);
memcpy(scene->pipeline, pipeline, sizeof(dsScenePipelineItem)*pipelineCount);
scene->pipelineCount = pipelineCount;
scene->globalValueCount = 0;
if (globalDataCount > 0)
{
scene->globalData =
DS_ALLOCATE_OBJECT_ARRAY(&bufferAlloc, dsSceneGlobalData*, globalDataCount);
DS_ASSERT(scene->globalData);
memcpy(scene->globalData, globalData, sizeof(dsSceneGlobalData*)*globalDataCount);
for (uint32_t i = 0; i < globalDataCount; ++i)
scene->globalValueCount += globalData[i]->valueCount;
}
else
scene->globalData = NULL;
scene->globalDataCount = globalDataCount;
uint32_t tableSize = dsHashTable_getTableSize(nameCount);
size_t hashTableSize = dsHashTable_fullAllocSize(tableSize);
scene->itemLists = (dsHashTable*)dsAllocator_alloc((dsAllocator*)&bufferAlloc, hashTableSize);
DS_ASSERT(scene->itemLists);
DS_VERIFY(dsHashTable_initialize(scene->itemLists, tableSize, &dsHashString,
&dsHashStringEqual));
scene->dirtyNodes = NULL;
scene->dirtyNodeCount = 0;
scene->maxDirtyNodes = 0;
dsSceneItemListNode* itemNodes = DS_ALLOCATE_OBJECT_ARRAY(&bufferAlloc, dsSceneItemListNode,
nameCount);
DS_ASSERT(itemNodes);
uint32_t curItems = 0;
for (uint32_t i = 0; i < sharedItemCount; ++i)
{
const dsSceneItemLists* itemLists = sharedItems + i;
for (uint32_t j = 0; j < itemLists->count; ++j)
{
dsSceneItemListNode* node = itemNodes + curItems++;
if (!insertSceneList(scene->itemLists, node, sharedItems[i].itemLists[j]))
{
errno = EINVAL;
dsScene_destroy(scene);
return NULL;
}
}
}
for (uint32_t i = 0; i < pipelineCount; ++i)
{
const dsScenePipelineItem* item = pipeline + i;
if (item->renderPass)
{
for (uint32_t j = 0; j < item->renderPass->renderPass->subpassCount; ++j)
{
const dsSceneItemLists* items = item->renderPass->drawLists + j;
for (uint32_t k = 0; k < items->count; ++k)
{
dsSceneItemListNode* node = itemNodes + curItems++;
if (!insertSceneList(scene->itemLists, node, items->itemLists[k]))
{
errno = EINVAL;
dsScene_destroy(scene);
return NULL;
}
}
}
}
else
{
dsSceneItemListNode* node = itemNodes + curItems++;
if (!insertSceneList(scene->itemLists, node, item->computeItems))
{
errno = EINVAL;
dsScene_destroy(scene);
return NULL;
}
}
}
DS_ASSERT(curItems == nameCount);
return scene;
}
dsScene* dsScene_loadFile(dsAllocator* allocator, dsAllocator* resourceAllocator,
const dsSceneLoadContext* loadContext, dsSceneLoadScratchData* scratchData,
void* userData, dsDestroySceneUserDataFunction destroyUserDataFunc, const char* filePath)
{
DS_PROFILE_FUNC_START();
if (!allocator || !loadContext || !scratchData || !filePath)
{
errno = EINVAL;
DS_PROFILE_FUNC_RETURN(NULL);
}
if (!resourceAllocator)
resourceAllocator = allocator;
dsFileStream stream;
if (!dsFileStream_openPath(&stream, filePath, "rb"))
{
DS_LOG_ERROR_F(DS_RENDER_LOG_TAG, "Couldn't open scene file '%s'.", filePath);
DS_PROFILE_FUNC_RETURN(NULL);
}
size_t size;
void* buffer = dsSceneLoadScratchData_readUntilEnd(&size, scratchData, (dsStream*)&stream);
dsFileStream_close(&stream);
if (!buffer)
DS_PROFILE_FUNC_RETURN(NULL);
dsScene* scene = dsScene_loadImpl(allocator, resourceAllocator, loadContext, scratchData,
buffer, size, userData, destroyUserDataFunc, filePath);
DS_VERIFY(dsSceneLoadScratchData_freeReadBuffer(scratchData, buffer));
DS_PROFILE_FUNC_RETURN(scene);
}
dsScene* dsScene_loadResource(dsAllocator* allocator, dsAllocator* resourceAllocator,
const dsSceneLoadContext* loadContext, dsSceneLoadScratchData* scratchData,
void* userData, dsDestroySceneUserDataFunction destroyUserDataFunc, dsFileResourceType type,
const char* filePath)
{
DS_PROFILE_FUNC_START();
if (!allocator || !loadContext || !scratchData || !filePath)
{
errno = EINVAL;
DS_PROFILE_FUNC_RETURN(NULL);
}
dsResourceStream stream;
if (!dsResourceStream_open(&stream, type, filePath, "rb"))
{
DS_LOG_ERROR_F(DS_RENDER_LOG_TAG, "Couldn't open scene node file '%s'.", filePath);
DS_PROFILE_FUNC_RETURN(NULL);
}
size_t size;
void* buffer = dsSceneLoadScratchData_readUntilEnd(&size, scratchData, (dsStream*)&stream);
dsResourceStream_close(&stream);
if (!buffer)
DS_PROFILE_FUNC_RETURN(NULL);
dsScene* scene = dsScene_loadImpl(allocator, resourceAllocator, loadContext, scratchData,
buffer, size, userData, destroyUserDataFunc, filePath);
DS_VERIFY(dsSceneLoadScratchData_freeReadBuffer(scratchData, buffer));
DS_PROFILE_FUNC_RETURN(scene);
}
dsScene* dsScene_loadStream(dsAllocator* allocator, dsAllocator* resourceAllocator,
const dsSceneLoadContext* loadContext, dsSceneLoadScratchData* scratchData, void* userData,
dsDestroySceneUserDataFunction destroyUserDataFunc, dsStream* stream)
{
DS_PROFILE_FUNC_START();
if (!allocator || !loadContext || !scratchData || !stream)
{
errno = EINVAL;
DS_PROFILE_FUNC_RETURN(NULL);
}
size_t size;
void* buffer = dsSceneLoadScratchData_readUntilEnd(&size, scratchData, stream);
if (!buffer)
DS_PROFILE_FUNC_RETURN(NULL);
dsScene* scene = dsScene_loadImpl(allocator, resourceAllocator, loadContext, scratchData,
buffer, size, userData, destroyUserDataFunc, NULL);
DS_VERIFY(dsSceneLoadScratchData_freeReadBuffer(scratchData, buffer));
DS_PROFILE_FUNC_RETURN(scene);
}
dsScene* dsScene_loadData(dsAllocator* allocator, dsAllocator* resourceAllocator,
const dsSceneLoadContext* loadContext, dsSceneLoadScratchData* scratchData, void* userData,
dsDestroySceneUserDataFunction destroyUserDataFunc, const void* data, size_t size)
{
DS_PROFILE_FUNC_START();
if (!allocator || !loadContext || !scratchData || !data || size == 0)
{
errno = EINVAL;
DS_PROFILE_FUNC_RETURN(NULL);
}
dsScene* scene = dsScene_loadImpl(allocator, resourceAllocator, loadContext, scratchData, data,
size, userData, destroyUserDataFunc, NULL);
DS_PROFILE_FUNC_RETURN(scene);
}
dsAllocator* dsScene_getAllocator(const dsScene* scene)
{
if (!scene)
return NULL;
return scene->allocator;
}
dsRenderer* dsScene_getRenderer(const dsScene* scene)
{
if (!scene)
return NULL;
return scene->renderer;
}
void* dsScene_getUserData(const dsScene* scene)
{
if (!scene)
return NULL;
return scene->userData;
}
uint32_t dsScene_getNodeCount(const dsScene* scene)
{
if (!scene)
return 0;
return scene->rootNode.childCount;
}
dsSceneNode* dsScene_getNode(const dsScene* scene, uint32_t index)
{
if (!scene)
{
errno = EINVAL;
return NULL;
}
if (index >= scene->rootNode.childCount)
{
errno = EINDEX;
return NULL;
}
return scene->rootNode.children[index];
}
bool dsScene_addNode(dsScene* scene, dsSceneNode* node)
{
if (!scene || !node)
{
errno = EINVAL;
return false;
}
return dsSceneNode_addChild(&scene->rootNode, node);
}
bool dsScene_removeNodeIndex(dsScene* scene, uint32_t nodeIndex)
{
if (!scene)
{
errno = EINVAL;
return false;
}
return dsSceneNode_removeChildIndex(&scene->rootNode, nodeIndex);
}
bool dsScene_removeNode(dsScene* scene, dsSceneNode* node)
{
if (!scene || !node)
{
errno = EINVAL;
return false;
}
return dsSceneNode_removeChildNode(&scene->rootNode, node);
}
void dsScene_clearNodes(dsScene* scene)
{
if (scene)
dsSceneNode_clear(&scene->rootNode);
}
bool dsScene_update(dsScene* scene)
{
if (!scene)
{
errno = EINVAL;
return false;
}
for (uint32_t i = 0; i < scene->dirtyNodeCount; ++i)
dsSceneTreeNode_updateSubtree(scene->dirtyNodes[i]);
scene->dirtyNodeCount = 0;
return true;
}
void dsScene_destroy(dsScene* scene)
{
if (!scene)
return;
// Prevent tree teardown from removing from the dirty list, which is just a waste of cycles on
// destruction.
scene->dirtyNodeCount = 0;
DS_ASSERT(scene->rootNode.refCount == 1);
dsSceneNode_freeRef(&scene->rootNode);
dsSceneTreeNode* rootTreeNode = &scene->rootTreeNode.node;
DS_ASSERT(rootTreeNode->childCount == 0);
DS_VERIFY(dsAllocator_free(rootTreeNode->allocator, rootTreeNode->children));
destroyObjects(scene->sharedItems, scene->sharedItemCount, scene->pipeline,
scene->pipelineCount, scene->globalData, scene->globalDataCount, scene->userData,
scene->destroyUserDataFunc);
DS_VERIFY(dsAllocator_free(scene->allocator, scene->dirtyNodes));
DS_VERIFY(dsAllocator_free(scene->allocator, scene));
}
| 29.064125
| 96
| 0.746213
|
7942a0edbdd4487cf2aaf0fd5fb38de31752fb20
| 1,265
|
kt
|
Kotlin
|
core/src/test/java/com/schibsted/account/test/MockedCall.kt
|
JohNan/account-sdk-android
|
87042fbfab623a27b3c334404e1e2d8864da942f
|
[
"MIT"
] | null | null | null |
core/src/test/java/com/schibsted/account/test/MockedCall.kt
|
JohNan/account-sdk-android
|
87042fbfab623a27b3c334404e1e2d8864da942f
|
[
"MIT"
] | null | null | null |
core/src/test/java/com/schibsted/account/test/MockedCall.kt
|
JohNan/account-sdk-android
|
87042fbfab623a27b3c334404e1e2d8864da942f
|
[
"MIT"
] | null | null | null |
/*
* Copyright (c) 2018 Schibsted Products & Technology AS. Licensed under the terms of the MIT license. See LICENSE in the project root.
*/
package com.schibsted.account.test
import okhttp3.Request
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
open class MockedCall<T>(private val response: Response<T>) : Call<T> {
override fun enqueue(callback: Callback<T>?) {
callback?.onResponse(this, response)
}
override fun execute(): Response<T> = response
override fun isExecuted(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun clone(): Call<T> {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun isCanceled(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun cancel() {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun request(): Request {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
}
| 32.435897
| 135
| 0.688538
|
94de0818a1b25ad88fb86e82e43217b0ec0f76d9
| 5,481
|
lua
|
Lua
|
app/simulationModelSets/demo/scripts/Crowd_In_Front_Of.lua
|
YinMuHuaDao/EntityEditor
|
a76acb3ab117c98899958148df65eb3340693c18
|
[
"CC0-1.0"
] | null | null | null |
app/simulationModelSets/demo/scripts/Crowd_In_Front_Of.lua
|
YinMuHuaDao/EntityEditor
|
a76acb3ab117c98899958148df65eb3340693c18
|
[
"CC0-1.0"
] | 3
|
2021-01-28T20:44:40.000Z
|
2021-10-12T22:40:22.000Z
|
app/simulationModelSets/mySms/scripts/Crowd_In_Front_Of.lua
|
YinMuHuaDao/EntityEditor
|
a76acb3ab117c98899958148df65eb3340693c18
|
[
"CC0-1.0"
] | null | null | null |
-- This script template has each of the script entry point functions.
-- They are described in detail in VR-Forces Configuration Guide.
-- Some basic VRF Utilities defined in a common module.
require "vrfutil"
local DEBUG_DETAIL = false
-- Global Variables. Global variables get saved when a scenario gets checkpointed.
-- They get re-initialized when a checkpointed scenario is loaded.
subtaskId = -1
surroundedLocation = Location3D(0,0,0)
-- If object of interest moves more than the retaskDistance, then we will restart
-- our crowd_around_location subtask. This should NOT be used for moving objects,
-- but rather objects that can be occasionally re-placed.
local retaskDistance = 2
-- Task Parameters Available in Script
-- taskParameters.objectOfInterest Type: SimObject - The object to crowd around
-- taskParameters.idleTask Type: String - The task which will be given to each pedestrian when they arrive
-- taskParameters.speedMultiplier Type: Real - Chosen speed for each entity is multiplied by this value. Used to slow down or speed up entities.
-- Called when the task first starts. Never called again.
function init()
-- Set the tick period for this script.
vrf:setTickPeriod(0.5)
end
-- Called each tick while this task is active.
function tick()
if taskParameters.objectOfInterest:isValid() then
local currentObjectLocation = taskParameters.objectOfInterest:getLocation3D()
local currentObjectHeading = taskParameters.objectOfInterest:getHeading()
local currentDirection = taskParameters.objectOfInterest:getDirection3D()
-- adjust object location for bounding volume center
local boundingVolume, offset = taskParameters.objectOfInterest:getBoundingVolume()
offset:setUp(0) -- ignore up offset
local offsetVec = offset:makeVectorRefToDirection(currentDirection)
currentObjectLocation = currentObjectLocation:addVector3D(offsetVec)
-- find location in front of object
local halfLength = boundingVolume:getForward()/2
local fwdVec = Vector3D(0,0,0)
fwdVec:setBearingInclRange(currentObjectHeading, 0, halfLength + 0.25)
local locationInFrontOfObject = currentObjectLocation:addVector3D(fwdVec)
-- If not already doing so, surround the object
if subtaskId < 0 then
-- surrounded location should be right in front of object
surroundedLocation = locationInFrontOfObject
fwdVec:setBearingInclRange(currentObjectHeading, 0, 1)
local leftVec = Vector3D(0,0,0)
leftVec:setBearingInclRange(currentObjectHeading-(math.pi/2), 0, 10)
local rightVec = Vector3D(0,0,0)
rightVec:setBearingInclRange(currentObjectHeading+(math.pi/2), 0, 10)
local fwdPoint = surroundedLocation:addVector3D(fwdVec)
local leftPoint = fwdPoint:addVector3D(leftVec)
local rightPoint = fwdPoint:addVector3D(rightVec)
if DEBUG_DETAIL then
-- draw our points for debugging purposes
vrf:updateTaskVisualization("fwd", "point",
{color={0,255,0,175}, size=1, location=fwdPoint})
vrf:updateTaskVisualization("left", "point",
{color={255,0,0,175}, size=1, location=leftPoint})
vrf:updateTaskVisualization("right", "point",
{color={0,0,255,175}, size=1, location=rightPoint})
vrf:updateTaskVisualization("srndloc", "point",
{color={255,0,255,200}, size=1, location=surroundedLocation})
end
subtaskId = vrf:startSubtask("Crowd_Around_Location",
{ locationOfInterest = surroundedLocation,
idleTask = taskParameters.idleTask,
speedMultiplier = taskParameters.speedMultiplier,
keepLeftOfLine = true,
leftOfLineStart = leftPoint,
leftOfLineEnd = rightPoint,
subordinatesToIgnore = {taskParameters.objectOfInterest} })
end
if subtaskId > 0 and
locationInFrontOfObject:distanceToLocation3D(surroundedLocation) > retaskDistance then
vrf:stopSubtask(subtaskId)
subtaskId = -1
end
-- See if we are done
if subtaskId > 0 and vrf:isSubtaskComplete(subtaskId) then
vrf:endTask(true)
end
end
end
-- Called when this task is being suspended, likely by a reaction activating.
function suspend()
-- By default, halt all subtasks and other entity tasks started by this task when suspending.
vrf:stopAllSubtasks()
vrf:stopAllTasks()
end
-- Called when this task is being resumed after being suspended.
function resume()
-- By default, simply call init() to start the task over.
init()
end
-- Called immediately before a scenario checkpoint is saved when
-- this task is active.
-- It is typically not necessary to add code to this function.
function saveState()
end
-- Called immediately after a scenario checkpoint is loaded in which
-- this task is active.
-- It is typically not necessary to add code to this function.
function loadState()
end
-- Called when this task is ending, for any reason.
-- It is typically not necessary to add code to this function.
function shutdown()
end
-- Called whenever the entity receives a text report message while
-- this task is active.
-- message is the message text string.
-- sender is the SimObject which sent the message.
function receiveTextMessage(message, sender)
end
| 38.598592
| 145
| 0.70863
|
028e7cbdf1e43feb8ada7ee6eef1eac47839e56c
| 13,358
|
cpp
|
C++
|
source/Bit/System/Bencode/BencodeValue.cpp
|
jimmiebergmann/Bit-Engine
|
39324a9e7fb5ab4b1cf3738f871470e0a9ef7575
|
[
"Zlib"
] | null | null | null |
source/Bit/System/Bencode/BencodeValue.cpp
|
jimmiebergmann/Bit-Engine
|
39324a9e7fb5ab4b1cf3738f871470e0a9ef7575
|
[
"Zlib"
] | null | null | null |
source/Bit/System/Bencode/BencodeValue.cpp
|
jimmiebergmann/Bit-Engine
|
39324a9e7fb5ab4b1cf3738f871470e0a9ef7575
|
[
"Zlib"
] | null | null | null |
// Copyright (C) 2013 Jimmie Bergmann - jimmiebergmann@gmail.com
//
// This software is provided 'as-is', without any express or
// implied warranty. In no event will the authors be held
// liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute
// it freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but
// is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any
// source distribution.
// ///////////////////////////////////////////////////////////////////////////
#include <Bit/System/Bencode/Value.hpp>
#include <sstream>
#include <Bit/System/MemoryLeak.hpp>
namespace Bit
{
namespace Bencode
{
// Global varaibles
static std::string g_EmptyString = "";
static std::string g_TemporaryString = "";
static std::string g_NilString = "[Nil]";
static std::string g_DictionaryString = "[Dictionary]";
static std::string g_ListString = "[List]";
// Static variable members
const Value Value::NilValue( Nil );
Value Value::s_DefaultValue( Nil );
// Value definitions
Value::Value( ) :
m_Type( Nil )
{
}
Value::Value( eType p_Type ) :
m_Type( p_Type )
{
}
Value::Value( const Value & p_Value )
{
// Always clear the old data
Clear( );
// Get this value's pointer
Value * pValue = const_cast<Value *>( this );
// Copy the value
CopyValue( p_Value, *pValue );
}
Value::~Value( )
{
Clear( );
}
void Value::Clear( )
{
switch( m_Type )
{
case Integer:
{
m_Value.Integer = 0;
}
break;
case String:
{
if( m_Value.String )
{
delete m_Value.String;
}
}
break;
case List:
{
if( m_Value.List )
{
// Delete all the values in the list
for( ValueVector::iterator it = m_Value.List->begin( ); it != m_Value.List->end( ); it++ )
{
delete *it;
}
delete m_Value.List;
}
}
break;
case Dictionary:
{
if( m_Value.Dictionary )
{
// Go through the dictionary and delete all the values
for( ValueMap::iterator it = m_Value.Dictionary->begin( ); it != m_Value.Dictionary->end( ); it++ )
{
delete it->second;
}
// Delete the dictionary pointer.
delete m_Value.Dictionary;
}
}
break;
default:
break;
}
// Set the type to Nil.
m_Type = Nil;
}
void Value::Append( const Value & p_Value )
{
// The value is not a list, turn it into a list
if( m_Type != List || !m_Value.List )
{
// Clear the old data first
Clear( );
m_Type = List;
m_Value.List = new ValueVector;
}
// Create a new value
Value * pValue = new Value;
// Copy the value
CopyValue( p_Value, *pValue );
// Push the new value value to the vector.
m_Value.List->push_back( pValue );
}
void Value::Append( const Int32 & p_Integer )
{
// The value is not a list, turn it into a list
if( m_Type != List || !m_Value.List )
{
// Clear the old data first
Clear( );
m_Type = List;
m_Value.List = new ValueVector;
}
// Create a value and push it to the vector
Value * pValue = new Value( Integer );
pValue->m_Value.Integer = p_Integer;
m_Value.List->push_back( pValue );
}
void Value::Append( const std::string & p_String )
{
// The value is not a list, turn it into a list
if( m_Type != List || !m_Value.List )
{
// Clear the old data first
Clear( );
m_Type = List;
m_Value.List = new ValueVector;
}
// Create a new value
Value * pValue = new Value( String );
pValue->m_Value.String = new std::string( );
// Set the string data for the new value.
pValue->m_Value.String->reserve( p_String.size( ) );
pValue->m_Value.String->append( p_String );
// Push the new value value to the vector.
m_Value.List->push_back( pValue );
}
void Value::Erase( const SizeType & p_Index )
{
// Make sure that this is a list.
if( m_Type != List || !m_Value.List )
{
return;
}
// Error check the size
if( p_Index >= m_Value.List->size( ) )
{
return;
}
// Delete the value
Value * pValue = *(m_Value.List->begin( ) + p_Index);
delete pValue;
// Erase the item
m_Value.List->erase( m_Value.List->begin( ) + p_Index );
}
void Value::Erase( const std::string & p_Key )
{
// Make sure that this is a dictionary.
if( m_Type != Dictionary || !m_Value.Dictionary )
{
return;
}
// Find the value
ValueMap::iterator it = m_Value.Dictionary->find( p_Key );
// Could we find the value?
if( it == m_Value.Dictionary->end( ) )
{
return;
}
// Delete the value
delete it->second;
// Erase the value from the dictionary
m_Value.Dictionary->erase( it );
}
Value::eType Value::GetType( ) const
{
return m_Type;
}
Bool Value::IsNil( ) const
{
return m_Type == Nil;
}
Value & Value::Get( const std::string & p_Key, const Value & p_DefaultValue ) const
{
// This function only works for dictionaries
if( m_Type != Dictionary )
{
s_DefaultValue = p_DefaultValue;
return s_DefaultValue;
}
// Find the key
ValueMap::iterator it = m_Value.Dictionary->find( p_Key );
// Could not find the key
if( it == m_Value.Dictionary->end( ) )
{
s_DefaultValue = p_DefaultValue;
return s_DefaultValue;
}
// Return the found value.
return *(it->second);
}
Value & Value::Get( const std::string & p_Key, const Int32 & p_DefaultValue ) const
{
// This function only works for dictionaries
if( m_Type != Dictionary )
{
s_DefaultValue = p_DefaultValue;
return s_DefaultValue;
}
// Find the key
ValueMap::iterator it = m_Value.Dictionary->find( p_Key );
// Could not find the key
if( it == m_Value.Dictionary->end( ) )
{
s_DefaultValue = p_DefaultValue;
return s_DefaultValue;
}
// Return the found value.
return *(it->second);
}
Value & Value::Get( const std::string & p_Key, const std::string & p_DefaultValue ) const
{
// This function only works for dictionaries
if( m_Type != Dictionary )
{
s_DefaultValue = p_DefaultValue;
return s_DefaultValue;
}
// Find the key
ValueMap::iterator it = m_Value.Dictionary->find( p_Key );
// Could not find the key
if( it == m_Value.Dictionary->end( ) )
{
s_DefaultValue = p_DefaultValue;
return s_DefaultValue;
}
// Return the found value.
return *(it->second);
}
SizeType Value::GetSize( ) const
{
if( m_Type == Dictionary && m_Value.Dictionary )
{
return static_cast<SizeType>( m_Value.Dictionary->size( ) );
}
else if( m_Type == List && m_Value.List )
{
return static_cast<SizeType>( m_Value.List->size( ) );
}
return 0;
}
const std::string & Value::AsString( ) const
{
// Switch the type in order to know which method you
// are going to use to convert the value into a string.
switch( m_Type )
{
case Nil:
{
return g_NilString;
}
break;
case String:
{
// Return the string if it's allocated.
return m_Value.String ? *m_Value.String : g_EmptyString;
}
break;
case Integer:
{
std::stringstream ss;
ss << m_Value.Integer;
g_TemporaryString = ss.str( );
return g_TemporaryString;
}
break;
case List:
{
return g_ListString;
}
break;
case Dictionary:
{
return g_DictionaryString;
}
break;
}
return g_EmptyString;
}
Int32 Value::AsInt( ) const
{
// Switch the type in order to know which method you
// are going to use to convert the value into a string.
switch( m_Type )
{
case Nil:
{
return 0;
}
break;
case String:
{
if( !m_Value.String )
{
return 0;
}
// Get the string as an int
return atoi( m_Value.String->c_str( ) );
}
break;
case Integer:
{
return m_Value.Integer;
}
break;
case List:
{
return 0;
}
break;
case Dictionary:
{
return 0;
}
break;
}
return 0;
}
Value & Value::operator [ ] ( const std::string & p_Key )
{
// This function only works for dictionaries.
// Turn this value into a dictionary.
if( m_Type != Dictionary )
{
// Clear all the old data
Clear( );
m_Type = Dictionary;
m_Value.Dictionary = new ValueMap;
}
// Find the key
ValueMap::iterator it = m_Value.Dictionary->find( p_Key );
// Could not find the key, add a Nil value to the dictionary.
if( it == m_Value.Dictionary->end( ) )
{
// Create a value
Value * pValue = new Value( Nil );
(*m_Value.Dictionary)[ p_Key ] = pValue;
// Return the nil value you just created.
return *pValue;
}
// Return the found value.
return *(it->second);
}
Value & Value::operator [ ] ( const SizeType & p_Index )
{
// Make sure that the value is a list.
if( m_Type != List )
{
s_DefaultValue.Clear( );
return s_DefaultValue;
}
// Error check the index.
if( p_Index > m_Value.List->size( ) )
{
s_DefaultValue.Clear( );
return s_DefaultValue;
}
return *(*m_Value.List)[ p_Index ];
}
Value & Value::operator = ( const Value & p_Value )
{
// Always clear the old data
Clear( );
// Get this value's pointer
Value * pValue = const_cast<Value *>( this );
// Copy the value
CopyValue( p_Value, *pValue );
// Return this value.
return *pValue;
}
Value & Value::operator = ( const Int32 & p_Integer )
{
// The value is not an integer, turn it into an integer value.
if( m_Type != Integer )
{
Clear( );
m_Type = Integer;
}
// Set the string data.
m_Value.Integer = p_Integer;
// Return this value.
return *const_cast<Value *>( this );
}
Value & Value::operator = ( const char * p_Characters )
{
return Value::operator=( std::string( p_Characters ) );
}
Value & Value::operator = ( const std::string & p_String )
{
// The value is not a string, turn it into a string value.
if( m_Type != String )
{
Clear( );
m_Type = String;
m_Value.String = new std::string( );
}
// Set the string data.
m_Value.String->reserve( p_String.size( ) );
m_Value.String->append( p_String );
// Return this value.
return *const_cast<Value *>( this );
}
bool Value::operator == ( const Value & p_Value ) const
{
return m_Type == p_Value.m_Type;
}
bool Value::operator != ( const Value & p_Value ) const
{
return m_Type != p_Value.m_Type;
}
// Private functions
void Value::CopyValue( const Value & p_From, Value & p_To ) const
{
// Set the type
p_To.m_Type = p_From.m_Type;
// Set the data
switch( p_From.m_Type )
{
case Integer:
{
p_To.m_Type = Integer;
p_To.m_Value.Integer = p_From.m_Value.Integer;
}
break;
case String:
{
// Make sure that the string is valid.
if( !p_From.m_Value.String )
{
p_To.m_Type = Nil;
break;
}
p_To.m_Type = String;
p_To.m_Value.String = new std::string;
p_To.m_Value.String->reserve( p_From.m_Value.String->size( ) );
p_To.m_Value.String->append( *p_From.m_Value.String );
}
break;
case List:
{
// Make sure that the list is valid.
if( !p_From.m_Value.List )
{
p_To.m_Type = Nil;
break;
}
p_To.m_Type = List;
p_To.m_Value.List = new ValueVector;
// Go throguh all the values in the list, and make copies of them.
for( ValueVector::iterator it = p_From.m_Value.List->begin( ); it != p_From.m_Value.List->end( ); it++ )
{
// Create a new value
Value * pValue = new Value( );
// Copy the value
CopyValue( *(*(it)), * pValue );
// Add the new value to the target list
p_To.m_Value.List->push_back( pValue );
}
}
break;
case Dictionary:
{
// Make sure that the dictionary is valid.
if( !p_From.m_Value.Dictionary )
{
p_To.m_Type = Nil;
break;
}
p_To.m_Type = Dictionary;
p_To.m_Value.Dictionary = new ValueMap;
// Go throguh all the values in the dictionary, and make copies of them.
for( ValueMap::iterator it = p_From.m_Value.Dictionary->begin( ); it != p_From.m_Value.Dictionary->end( ); it++ )
{
// Create a new value
Value * pValue = new Value( );
// Copy the value
CopyValue( *(it->second), * pValue );
// Add the new value to the target dictionary
(*p_To.m_Value.Dictionary)[ it->first ] = pValue;
}
}
break;
default: // Nil value
{
p_To.m_Type = Nil;
}
break;
}
}
}
}
| 21.579968
| 118
| 0.59485
|
b0d418a6cbc049abc9fed366ac7fe10f4acc6bde
| 21,232
|
py
|
Python
|
logger/listener/listen.py
|
vwarner1411/openrvdas-1
|
57e8b12aa7e0f840293e8727000f69252578e8a3
|
[
"MIT"
] | null | null | null |
logger/listener/listen.py
|
vwarner1411/openrvdas-1
|
57e8b12aa7e0f840293e8727000f69252578e8a3
|
[
"MIT"
] | null | null | null |
logger/listener/listen.py
|
vwarner1411/openrvdas-1
|
57e8b12aa7e0f840293e8727000f69252578e8a3
|
[
"MIT"
] | null | null | null |
#!/usr/bin/env python3
"""Instantiates and runs the Listener class. Try
listen.py --help
for details.
Examples:
logger/listener/listen.py \
--logfile test/nmea/NBP1700/s330/raw/NBP1700_s330 \
--interval 0.25 \
--transform_slice 1: \
--transform_timestamp \
--transform_prefix s330 \
--write_file -
(Reads lines from the Seapath300 sample logfiles every 0.25 seconds,
strips the old timestamps off, prepends a new one, then the prefix
's330', then writes the result to stdout.)
logger/listener/listen.py \
--config_file test/configs/simple_logger.json
(Instantiates logger from config file that says to read from the
project's LICENSE file, prepend a timestamp and the string "license:"
and writ to stdout every 0.2 seconds.)
The listen.py script is essentially a form of 'cat' on steroids,
reading records from files, serial or network ports, modifying what it
receives, then writing it back out to somewhere else.
For fun, you can even run listen.py as an Ouroboros script, feeding it on its
own output:
echo x > tmp
listen.py --file tmp --prefix p --write_file tmp --tail --interval 1 -v -v
"""
import argparse
import logging
import re
import sys
import time
sys.path.append('.')
from logger.readers.composed_reader import ComposedReader
from logger.readers.logfile_reader import LogfileReader
from logger.readers.network_reader import NetworkReader
from logger.readers.serial_reader import SerialReader
from logger.readers.text_file_reader import TextFileReader
from logger.readers.database_reader import DatabaseReader
from logger.readers.timeout_reader import TimeoutReader
from logger.transforms.prefix_transform import PrefixTransform
from logger.transforms.regex_filter_transform import RegexFilterTransform
from logger.transforms.qc_filter_transform import QCFilterTransform
from logger.transforms.slice_transform import SliceTransform
from logger.transforms.timestamp_transform import TimestampTransform
from logger.transforms.parse_nmea_transform import ParseNMEATransform
from logger.transforms.xml_aggregator_transform import XMLAggregatorTransform
from logger.transforms.true_winds_transform import TrueWindsTransform
from logger.transforms.derived_data_transform import DerivedDataTransform
from logger.transforms.derived_data_transform import ComposedDerivedDataTransform
from logger.writers.composed_writer import ComposedWriter
from logger.writers.network_writer import NetworkWriter
from logger.writers.text_file_writer import TextFileWriter
from logger.writers.logfile_writer import LogfileWriter
from logger.writers.database_writer import DatabaseWriter
from logger.writers.record_screen_writer import RecordScreenWriter
from logger.utils import read_json, timestamp
from logger.listener.listener import Listener
################################################################################
class ListenerFromLoggerConfig(Listener):
"""Helper class for instantiating a Listener object from a Python dict."""
############################
def __init__(self, config):
"""Create a Listener from a Python config dict."""
kwargs = self._kwargs_from_config(config)
super().__init__(**kwargs)
############################
def _kwargs_from_config(self, config_json):
"""Parse a kwargs from a JSON string, making exceptions for keywords
'readers', 'transforms', and 'writers' as internal class references."""
kwargs = {}
for key, value in config_json.items():
# Declaration of readers, transforms and writers. Note that the
# singular "reader" is a special case for TimeoutReader that
# takes a single reader.
if key in ['reader', 'readers', 'transforms', 'writers']:
kwargs[key] = self._class_kwargs_from_config(value)
# If value is a simple float/int/string/etc, just add to keywords
elif type(value) in [float, bool, int, str, list]:
kwargs[key] = value
# Else what do we have?
else:
raise ValueError('unexpected key:value in configuration: '
'{}: {}'.format(key, str(value)))
return kwargs
############################
def _class_kwargs_from_config(self, class_json):
"""Parse a class's kwargs from a JSON string."""
if not type(class_json) in [list, dict]:
raise ValueError('class_kwargs_from_config expected dict or list; '
'got: "{}"'.format(class_json))
# If we've got a list, recurse on each element
if type(class_json) is list:
return [self._class_kwargs_from_config(c) for c in class_json]
# Get name and constructor for component we're going to instantiate
class_name = class_json.get('class', None)
if class_name is None:
raise ValueError('missing "class" definition in "{}"'.format(class_json))
class_const = globals().get(class_name, None)
if not class_const:
raise ValueError('No component class "{}" found: "{}"'.format(
class_name, class_json))
# Get the keyword args for the component
kwarg_dict = class_json.get('kwargs', {})
kwargs = self._kwargs_from_config(kwarg_dict)
if not kwargs:
logging.info('No kwargs found for component {}'.format(class_name))
# Instantiate!
logging.info('Instantiating {}({})'.format(class_name, kwargs))
component = class_const(**kwargs)
return component
################################################################################
class ListenerFromLoggerConfigFile(ListenerFromLoggerConfig):
"""Helper class for instantiating a Listener object from a JSON config."""
############################
def __init__(self, config_file):
"""Create a Listener from a Python config file."""
config = read_json.read_json(config_file)
super().__init__(config)
################################################################################
if __name__ == '__main__':
parser = argparse.ArgumentParser(
epilog='Note that arguments are parsed and applied IN ORDER, so if you '
'want a flag like --tail to be applied to a reader, or --slice_separator '
'to be applied to --transform_slice, it must appear before that reader on '
'the command line. Similarly, transforms will be added to the queue and '
'applied in the order they appear on the command line; multiple '
'specifications of a reader, writer or transform will result in multiple '
'instances of it being created. Trust us, that\'s a feature.'
)
############################
# Set up from config file
parser.add_argument('--config_file', dest='config_file', default=None,
help='Read Listener configuration from JSON file. If '
'specified, no other command line arguments (except '
'-v) are allowed.')
############################
# Readers
parser.add_argument('--network', dest='network', default=None,
help='Comma-separated network addresses to read from')
parser.add_argument('--database', dest='database', default=None,
help='Format: user@host:database:field1,field2,... '
'Read specified fields from database. If no fields are '
'specified, read all fields in database. Should '
'be accompanied by the --database_password flag.')
parser.add_argument('--file', dest='file', default=None,
help='Comma-separated files to read from in parallel. '
'Note that wildcards in a filename will be expanded, '
'and the resulting files read sequentially. A single '
'dash (\'-\') will be interpreted as stdout.')
parser.add_argument('--logfile', dest='logfile', default=None,
help='Comma-separated logfile base filenames to read '
'from in parallel. Logfile dates will be added '
'automatically.')
parser.add_argument('--logfile_use_timestamps', dest='logfile_use_timestamps',
action='store_true', default=False,
help='Make LogfileReaders deliver records at intervals '
'corresponding to the intervals indicated by the stored '
'record timestamps.')
parser.add_argument('--serial', dest='serial', default=None,
help='Comma-separated serial port spec containing at '
'least port=[port], but also optionally baudrate, '
'timeout, max_bytes and/or other SerialReader '
'parameters.')
parser.add_argument('--interval', dest='interval', type=float, default=0,
help='Number of seconds between reads')
parser.add_argument('--tail', dest='tail',
action='store_true', default=False, help='Do not '
'exit after reading file EOF; continue to check for '
'additional input.')
parser.add_argument('--refresh_file_spec', dest='refresh_file_spec',
action='store_true', default=False, help='When at EOF '
'and --tail is specified, check for new matching files '
'that may have appeared since our last attempt to read.')
############################
# Transforms
parser.add_argument('--transform_prefix', dest='prefix', default='',
help='Prefix each record with this string')
parser.add_argument('--transform_timestamp', dest='timestamp',
action='store_true', default=False,
help='Timestamp each record as it is read')
parser.add_argument('--transform_slice', dest='slice', default='',
help='Return only the specified (space-separated) '
'fields of a text record. Can be comma-separated '
'integer values and/or ranges, e.g. "1,3,5:7,-1". '
'Note: zero-base indexing, so "1:" means "start at '
'second element.')
parser.add_argument('--slice_separator', dest='slice_separator', default=' ',
help='Field separator for --slice.')
parser.add_argument('--transform_regex_filter', dest='regex_filter',
default='',
help='Only pass records containing this regex.')
parser.add_argument('--transform_qc_filter', dest='qc_filter',
default='', help='Pass nothing unless the fields in the '
'received DASRecord exceed comma-separated '
'<field_name>:<lower>:<upper> bounds.')
parser.add_argument('--transform_parse_nmea', dest='parse_nmea',
action='store_true', default=False,
help='Convert tagged, timestamped NMEA records into '
'Python DASRecords.')
parser.add_argument('--time_format', dest='time_format',
default=timestamp.TIME_FORMAT,
help='Format in which to expect time strings.')
parser.add_argument('--transform_aggregate_xml', dest='aggregate_xml',
default='', help='Aggregate records of XML until a '
'completed XML record whose outer element matches '
'the specified tag has been seen, then pass it along '
'as a single record.')
############################
# Writers
parser.add_argument('--write_file', dest='write_file', default=None,
help='File(s) to write to (\'-\' for stdout)')
parser.add_argument('--write_logfile', dest='write_logfile', default=None,
help='Filename base to write to. A date string that '
'corresponds to the timestamped date of each record '
'Will be appended to filename, with one file per date.')
parser.add_argument('--write_network', dest='write_network', default=None,
help='Network address(es) to write to')
parser.add_argument('--write_database', dest='write_database', default=None,
help='user@host:database to write to. Should be '
'accompanied by the --database_password flag.')
parser.add_argument('--database_password', dest='database_password',
default=None, help='Password for database specified by '
'--write_database and/or --read_database.')
parser.add_argument('--write_record_screen', dest='write_record_screen',
action='store_true', default=False,
help='Display the most current DASRecord field values '
'on the terminal.')
############################
# Miscellaneous args
parser.add_argument('--check_format', dest='check_format',
action='store_true', default=False, help='Check '
'reader/transform/writer format compatibility')
parser.add_argument('-v', '--verbosity', dest='verbosity',
default=0, action='count',
help='Increase output verbosity')
############################
# Set up logging before we do any other argument parsing (so that we
# can log problems with argument parsing.)
parsed_args = parser.parse_args()
LOGGING_FORMAT = '%(asctime)-15s %(filename)s:%(lineno)d %(message)s'
logging.basicConfig(format=LOGGING_FORMAT)
LOG_LEVELS ={0:logging.WARNING, 1:logging.INFO, 2:logging.DEBUG}
verbosity = min(parsed_args.verbosity, max(LOG_LEVELS))
logging.getLogger().setLevel(LOG_LEVELS[verbosity])
############################
# If --config_file present, create Listener from config file. If
# not, manually parse and create from all other arguments on command
# line.
if parsed_args.config_file:
# Ensure that no other flags have been specified.
i = 1
while i < len(sys.argv):
if sys.argv[i] in ['-v', '--verbosity']:
i += 1
elif sys.argv[i] == '--config_file':
i += 2
else:
raise ValueError(
'When --config is specified, no other command '
'line arguments (except -v) may be used: {}'.format(sys.argv[i]))
# Read config file and instantiate
listener = ListenerFromLoggerConfigFile(parsed_args.config_file)
# If not --config, go parse all those crazy command line arguments manually
else:
############################
# Where we'll store our components
readers = []
transforms = []
writers = []
############################
# Parse args out. We do this in a rather non-standard way to use the
# order of args on the command line to determine the order of our
# transforms. Specifically: break command line up into sections that
# end with the next '-'-prefixed argument (excluding the empty
# argument '-' and arguments starting with a negative number),
# and process those sections sequentially, adding
# them to the 'args' namespace as we go.
#
# So
#
# listen.py -v 1 2 3 -w -x - -y -4 -1,1 -z
#
# will be processed in five chunks:
#
# ['-v', '1', '2', '3']
# ['-w']
# ['-x', '-']
# ['-y', '-4', '-1,1']
# ['-z']
#
#
# Functionally, it means that
#
# --transform_a <params_a> --transform_b <params_b>
#
# will push transform_a into the transform list before transform_b,
# (meaning it will be applied to records first), while
#
# --transform_b <params_b> --transform_a <params_a>
#
# will do the opposite. It also means that repeating a transform on
# the command line will apply it twice. Repetitions of readers or
# writers will create multiple instances but, since readers and
# writers are applied in parallel, ordering is irrelevant.
arg_start = arg_end = 1 # start at beginning of args, minus script name;
all_args = None # initial namespace is empty
# Loop while we have args left
while arg_end <= len(sys.argv):
arg_start = arg_end
arg_end += 1
# Get everything up to, but not including, the next arg beginning with '-'
# that isn't a plain '-' or something numeric.
while arg_end < len(sys.argv):
next_arg = sys.argv[arg_end]
if next_arg.find('-') == 0:
if next_arg != '-' and not re.match('-\d', next_arg):
break
arg_end += 1
# We have our next set of arguments - parse them
arg_list = sys.argv[arg_start:arg_end]
logging.debug('next set of command line arguments: %s', arg_list)
# These are just the new values
new_args = parser.parse_args(arg_list)
# We also want to accumulate old arguments so that we have access
# to flags that have been previously set.
all_args = parser.parse_args(arg_list, all_args)
logging.debug('namespace of all command-line args so far: %s', all_args)
##########################
# Now go through new_args and see what they want us to do. Draw
# on all_args for the previously-set options that a reader,
# transform or writer might need.
##########################
# Readers
if new_args.file:
for filename in new_args.file.split(','):
readers.append(TextFileReader(
file_spec=filename, tail=all_args.tail,
refresh_file_spec=all_args.refresh_file_spec))
if new_args.network:
for addr in new_args.network.split(','):
readers.append(NetworkReader(network=addr))
if new_args.logfile:
for filebase in new_args.logfile.split(','):
readers.append(LogfileReader(
filebase=filebase, use_timestamps=all_args.logfile_use_timestamps,
refresh_file_spec=all_args.refresh_file_spec))
# For each comma-separated spec, parse out values for
# user@host:database:data_id[:message_type]. We count on
# --database_password having been specified somewhere.
if new_args.database:
password = all_args.database_password
(user, host_db) = new_args.database.split('@')
(host, database) = host_db.split(':', maxsplit=1)
if ':' in database:
(database, fields) = database.split(':')
else:
fields = None
readers.append(DatabaseReader(fields=fields,
database=database, host=host,
user=user, password=password))
# SerialReader is a little more complicated than other readers
# because it can take so many parameters. Use the kwargs trick to
# pass them all in.
if new_args.serial:
kwargs = {}
for pair in new_args.serial.split(','):
(key, value) = pair.split('=')
kwargs[key] = value
readers.append(SerialReader(**kwargs))
##########################
# Transforms
if new_args.slice:
transforms.append(SliceTransform(new_args.slice,
all_args.slice_separator))
if new_args.timestamp:
transforms.append(TimestampTransform(time_format=all_args.time_format))
if new_args.prefix:
transforms.append(PrefixTransform(new_args.prefix))
if new_args.regex_filter:
transforms.append(RegexFilterTransform(new_args.regex_filter))
if new_args.qc_filter:
transforms.append(QCFilterTransform(new_args.qc_filter))
if new_args.parse_nmea:
transforms.append(ParseNMEATransform(time_format=all_args.time_format))
if new_args.aggregate_xml:
transforms.append(XMLAggregatorTransform(new_args.aggregate_xml))
##########################
# Writers
if new_args.write_file:
for filename in new_args.write_file.split(','):
if filename == '-':
filename = None
writers.append(TextFileWriter(filename=filename))
if new_args.write_logfile:
writers.append(LogfileWriter(filebase=new_args.write_logfile))
if new_args.write_network:
for addr in new_args.write_network.split(','):
writers.append(NetworkWriter(network=addr))
if new_args.write_record_screen:
writers.append(RecordScreenWriter())
if new_args.write_database:
password = all_args.database_password
# Parse out values for user@host:database. We count on
# --database_password having been specified somewhere.
(user, host_db) = new_args.write_database.split('@')
(host, database) = host_db.split(':')
writers.append(DatabaseWriter(database=database, host=host,
user=user, password=password))
##########################
# Now that we've got our readers, transforms and writers defined,
# create the Listener.
listener = Listener(readers=readers, transforms=transforms, writers=writers,
interval=all_args.interval,
check_format=all_args.check_format)
############################
# Whichever way we created the listener, run it.
listener.run()
| 42.549098
| 81
| 0.625
|
5e26abaa0a655cbca80b005e3ed39c0a77de45e7
| 57
|
rb
|
Ruby
|
lib/shopify_api/resources/note_attribute.rb
|
EmmaB/shopify_api
|
24d2640c04fead8871097f23f5c1dadd4a9c298f
|
[
"MIT"
] | 4
|
2020-08-18T20:59:47.000Z
|
2020-09-16T06:21:08.000Z
|
lib/shopify_api/resources/note_attribute.rb
|
EmmaB/shopify_api
|
24d2640c04fead8871097f23f5c1dadd4a9c298f
|
[
"MIT"
] | 2
|
2020-05-04T16:46:21.000Z
|
2020-05-06T09:50:51.000Z
|
lib/shopify_api/resources/note_attribute.rb
|
EmmaB/shopify_api
|
24d2640c04fead8871097f23f5c1dadd4a9c298f
|
[
"MIT"
] | 3
|
2015-04-15T11:17:53.000Z
|
2018-03-27T03:57:04.000Z
|
module ShopifyAPI
class NoteAttribute < Base
end
end
| 11.4
| 28
| 0.77193
|
daca6ba891caf078ff5f88a2ddd7ee890a75128d
| 7,854
|
lua
|
Lua
|
game/scripts/vscripts/heroes/warp_beast/warp_beast_latch.lua
|
DarkoniusXNG/ancient_battle_dota2
|
f4936c592ed8f61703a6dcaa2ce3054c3b035ccb
|
[
"MIT"
] | 1
|
2018-09-21T03:29:51.000Z
|
2018-09-21T03:29:51.000Z
|
game/scripts/vscripts/heroes/warp_beast/warp_beast_latch.lua
|
DarkoniusXNG/ancient_battle_dota2
|
f4936c592ed8f61703a6dcaa2ce3054c3b035ccb
|
[
"MIT"
] | null | null | null |
game/scripts/vscripts/heroes/warp_beast/warp_beast_latch.lua
|
DarkoniusXNG/ancient_battle_dota2
|
f4936c592ed8f61703a6dcaa2ce3054c3b035ccb
|
[
"MIT"
] | null | null | null |
LinkLuaModifier("modifier_latch", "scripts/vscripts/heroes/warp_beast/warp_beast_latch.lua", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_latch_target", "scripts/vscripts/heroes/warp_beast/warp_beast_latch.lua", LUA_MODIFIER_MOTION_NONE)
warp_beast_latch = class({})
function warp_beast_latch:CastFilterResultTarget(target)
local caster = self:GetCaster()
local default_result = self.BaseClass.CastFilterResultTarget(self, target)
if target == caster then
return UF_FAIL_CUSTOM
end
return default_result
end
function warp_beast_latch:GetCustomCastErrorTarget(target)
local caster = self:GetCaster()
if target == caster then
return "#dota_hud_error_cant_cast_on_self"
end
end
function warp_beast_latch:OnSpellStart()
if not IsServer() then return end
local caster = self:GetCaster()
local target = self:GetCursorTarget()
if caster == nil or target == nil then
return nil
end
if target:GetTeam() ~= caster:GetTeam() and target:TriggerSpellAbsorb(self) then
return
end
if target:HasModifier("modifier_item_lotus_orb_active") or target:HasModifier("modifier_latch") then -- or target:HasModifier("modifier_latch_target") then
return
end
local distance = -80
local duration = self:GetSpecialValueFor("duration")
if target:GetTeam() == caster:GetTeam() then
distance = -20
duration = -1
end
local bonusAttackSpeed = self:GetSpecialValueFor("attackspeed_bonus")
local talent = caster:FindAbilityByName("special_bonus_unique_warp_beast_latch_attackspeed")
if talent then
if talent:GetLevel() ~= 0 then
bonusAttackSpeed = bonusAttackSpeed + talent:GetSpecialValueFor("value")
end
end
local modifier = caster:AddNewModifier(caster, self, "modifier_latch", {Duration = duration, attackSpeed = bonusAttackSpeed})
target:AddNewModifier(caster, self, "modifier_latch_target", {Duration = duration})
modifier.target = target
local latchPosition = target:GetAbsOrigin() + (target:GetForwardVector() * distance) + Vector(0, RandomFloat(-2, 2), 0)
local latchDirection = (target:GetAbsOrigin() - latchPosition):Normalized()
caster:Hold()
caster:EmitSound("Hero_Warp_Beast.Latch")
local targetHeight = self:GetLatchHeight(target)
caster:SetAbsOrigin(latchPosition + Vector(0,0,targetHeight))
caster:SetForwardVector(latchDirection)
-- caster:SetAbsOrigin(target:GetAbsOrigin() + Vector(0, 0, 150) + caster:GetForwardVector() * -75)
caster:SetParent(target, "attach_origin")
if target:GetTeam() ~= caster:GetTeam() then
caster:SetAngles(45, caster:GetAngles().y, caster:GetAngles().z)
caster:SetAttacking(target)
local order =
{
UnitIndex = caster:entindex(),
OrderType = DOTA_UNIT_ORDER_ATTACK_TARGET,
TargetIndex = target:entindex()
}
ExecuteOrderFromTable(order)
caster:SetForceAttackTarget(target)
-- Timers:CreateTimer(0.1, function() ExecuteOrderFromTable(order) return nil end )
end
end
function warp_beast_latch:GetLatchHeight(target)
if target:GetUnitName() == "npc_dota_hero_phoenix" then return 180 end
if target:GetUnitName() == "npc_dota_hero_skywrath_mage" then return 240 end
if target:IsHero() then return 120 end
if target:IsBarracks() then return 250 end
if target:IsTower() then return 275 end
if target:IsRoshan() then return 300 end
if target:IsFort() then return 400 end
if target:GetUnitName() == "npc_dota_phoenix_sun" then return 340 end
-- Default height
return 80
end
------------------------------------------------------------------------------------------------------------------
modifier_latch = class({})
function modifier_latch:CheckState( )
local states = {
-- [MODIFIER_STATE_ROOTED] = true,
[MODIFIER_STATE_NO_UNIT_COLLISION] = true,
[MODIFIER_STATE_FLYING_FOR_PATHING_PURPOSES_ONLY] = true
}
return states
end
function modifier_latch:OnCreated(keys)
self.attackspeed_bonus = keys.attackSpeed
if IsServer() then
self:StartIntervalThink(0.1)
end
end
function modifier_latch:OnIntervalThink()
if not IsServer() then return end
if self.target then
local caster = self:GetCaster()
local target = self.target
if not caster:CanEntityBeSeenByMyTeam(target) then
target:RemoveModifierByNameAndCaster("modifier_latch_target", caster)
end
if caster:IsStunned() then
target:RemoveModifierByNameAndCaster("modifier_latch_target", caster)
end
end
end
function modifier_latch:GetEffectName()
return "particles/units/heroes/hero_warp_beast/warp_beast_latch.vpcf"
end
function modifier_latch:DeclareFunctions()
local funcs = {
MODIFIER_PROPERTY_ATTACKSPEED_BONUS_CONSTANT,
-- MODIFIER_EVENT_ON_ATTACK_LANDED,
MODIFIER_EVENT_ON_ORDER
}
return funcs
end
function modifier_latch:GetModifierAttackSpeedBonus_Constant()
return self.attackspeed_bonus
end
--[[
-- Lifesteal part
function modifier_latch:OnAttackLanded(event)
if IsServer() and self:GetParent() == event.attacker then
local attacker = event.attacker
local target = event.target
if target:IsBuilding() or target:IsIllusion() or (target:GetTeam() == attacker:GetTeam()) then
return
end
local damage = event.damage * (100 - target:GetPhysicalArmorReduction()) / 100
local heal = self:GetAbility():GetSpecialValueFor("lifesteal_bonus") * damage / 100
if attacker:IsRealHero() then
attacker:Heal(heal, attacker)
end
local lifesteal_pfx = ParticleManager:CreateParticle("particles/generic_gameplay/generic_lifesteal.vpcf", PATTACH_ABSORIGIN_FOLLOW, attacker)
ParticleManager:SetParticleControl(lifesteal_pfx, 0, attacker:GetAbsOrigin())
ParticleManager:ReleaseParticleIndex(lifesteal_pfx)
end
end
]]
function modifier_latch:OnOrder(event)
if IsServer() and event.unit == self:GetParent() and self.target and self.target:HasModifier("modifier_latch_target") and self.target:GetTeam() == self:GetParent():GetTeam() then
self.target:RemoveModifierByNameAndCaster("modifier_latch_target", self:GetCaster())
self:Destroy()
end
end
function modifier_latch:OnDestroy()
if not IsServer() then return end
local caster = self:GetCaster()
caster:SetForceAttackTarget(nil)
self:GetAbility():SetActivated(true)
caster:SetParent(nil, "attach_origin")
caster:SetAngles(0, caster:GetAngles().y, 0)
FindClearSpaceForUnit(caster, caster:GetAbsOrigin(), true)
end
modifier_latch_target = class({})
if IsServer() then
cast_orders = {
[DOTA_UNIT_ORDER_CAST_POSITION] = true,
[DOTA_UNIT_ORDER_CAST_TARGET] = true,
}
end
function modifier_latch_target:IsPurgable()
return false
end
-- function modifier_latch_target:DeclareFunctions()
-- local funcs = {
-- MODIFIER_EVENT_ON_ORDER
-- }
-- return funcs
-- end
-- -- Being able to use spells and items while latched
-- function modifier_latch_target:OnOrder(event)
-- if not IsServer() then return end
-- local caster = self:GetCaster()
-- if event.unit == caster and caster:IsRealHero() then
-- if cast_orders[event.order_type] and not self:GetCaster():IsSilenced() then
-- local ability = event.ability
-- if ability then
-- local castPosition
-- if event.target then
-- castPosition = event.target:GetAbsOrigin()
-- else
-- castPosition = event.new_pos
-- end
-- local maxCastRange = ability:GetCastRange(castPosition, caster) + caster:GetCastRangeBonus()
-- local distance = (caster:GetAbsOrigin() - castPosition):Length2D()
-- -- Remove latch if Temporal Jump is used and within range
-- if maxCastRange >= distance and ability:GetName() == "warp_beast_temporal_jump" then
-- self:Destroy()
-- -- Remove latch if Warp is used
-- elseif caster:HasModifier("modifier_warp") and maxCastRange < distance then
-- self:Destroy()
-- end
-- end
-- end
-- end
-- end
function modifier_latch_target:OnDestroy()
if not IsServer() then return end
local caster = self:GetCaster()
caster:RemoveModifierByName("modifier_latch")
end
| 30.560311
| 180
| 0.751464
|
6217f135a758ac64045d36d0d419010eeba4c5e6
| 2,965
|
dart
|
Dart
|
mobile-application/lib/main_screen/components/input_numpad.dart
|
fmteotonio/social-augmented-hiit
|
36e47f9e42a5030539f8cf38c2ceacc144c75de5
|
[
"CC0-1.0"
] | null | null | null |
mobile-application/lib/main_screen/components/input_numpad.dart
|
fmteotonio/social-augmented-hiit
|
36e47f9e42a5030539f8cf38c2ceacc144c75de5
|
[
"CC0-1.0"
] | null | null | null |
mobile-application/lib/main_screen/components/input_numpad.dart
|
fmteotonio/social-augmented-hiit
|
36e47f9e42a5030539f8cf38c2ceacc144c75de5
|
[
"CC0-1.0"
] | null | null | null |
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:ble/constants.dart';
class InputNumpad extends StatelessWidget {
final int heartRate;
final String currentInput;
final Function numpadKeyOnPressed;
final bool activeCondition;
InputNumpad({this.heartRate, this.currentInput, this.numpadKeyOnPressed, this.activeCondition});
@override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Row(
children: <Widget>[
NumpadKey(onPressedFunction: numpadKeyOnPressed, text: "1", activeCondition: activeCondition),
NumpadKey(onPressedFunction: numpadKeyOnPressed, text: "2", activeCondition: activeCondition),
NumpadKey(onPressedFunction: numpadKeyOnPressed, text: "3", activeCondition: activeCondition),
],
),
SizedBox(height: 4),
Row(
children: <Widget>[
NumpadKey(onPressedFunction: numpadKeyOnPressed, text: "4", activeCondition: activeCondition),
NumpadKey(onPressedFunction: numpadKeyOnPressed, text: "5", activeCondition: activeCondition),
NumpadKey(onPressedFunction: numpadKeyOnPressed, text: "6", activeCondition: activeCondition),
],
),
SizedBox(height: 4),
Row(
children: <Widget>[
NumpadKey(onPressedFunction: numpadKeyOnPressed, text: "7", activeCondition: activeCondition),
NumpadKey(onPressedFunction: numpadKeyOnPressed, text: "8", activeCondition: activeCondition),
NumpadKey(onPressedFunction: numpadKeyOnPressed, text: "9", activeCondition: activeCondition),
],
),
SizedBox(height: 4),
Row(
children: <Widget>[
NumpadKey(onPressedFunction: numpadKeyOnPressed, text: "0", activeCondition: activeCondition),
],
),
],
);
}
}
class NumpadKey extends StatelessWidget {
final Function onPressedFunction;
final String text;
final bool activeCondition;
NumpadKey({this.onPressedFunction, this.text, this.activeCondition});
@override
Widget build(BuildContext context) {
return Expanded(
child: RawMaterialButton(
constraints: BoxConstraints.expand(width: 70, height: 70),
onPressed: () {
if (activeCondition) this.onPressedFunction(text);
},
elevation: 0.0,
fillColor: activeCondition ? kSmallButtonColor : kSmallButtonPressedColor,
padding: EdgeInsets.fromLTRB(0, 0, 0, 0),
shape: CircleBorder(),
child: Text(
this.text,
style: TextStyle(
fontSize: 24,
fontFamily: "Inter",
color: activeCondition ? kIconColor : kIconPressedColor,
),
),
),
);
}
}
| 36.158537
| 107
| 0.63339
|
c6cbb5caa5db831eb874586cc4284c546526818d
| 242
|
py
|
Python
|
tests/agent_finder_test.py
|
pnarvor/nephelae_simulation
|
7b3f3a2c2aaa49324f8b09a6ab62819c280efa4c
|
[
"BSD-3-Clause"
] | null | null | null |
tests/agent_finder_test.py
|
pnarvor/nephelae_simulation
|
7b3f3a2c2aaa49324f8b09a6ab62819c280efa4c
|
[
"BSD-3-Clause"
] | null | null | null |
tests/agent_finder_test.py
|
pnarvor/nephelae_simulation
|
7b3f3a2c2aaa49324f8b09a6ab62819c280efa4c
|
[
"BSD-3-Clause"
] | null | null | null |
#! /usr/bin/python3
import os
import sys
sys.path.append("../")
import signal
import ivy_ros_tunnel as irt
finder = irt.IvyAgentFinder()
signal.signal(signal.SIGINT, lambda signal, frame: finder.stop())
finder.start()
signal.pause()
| 12.1
| 65
| 0.727273
|