branch_name
stringclasses 149
values | text
stringlengths 23
89.3M
| directory_id
stringlengths 40
40
| languages
listlengths 1
19
| num_files
int64 1
11.8k
| repo_language
stringclasses 38
values | repo_name
stringlengths 6
114
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
|
|---|---|---|---|---|---|---|---|---|
refs/heads/master
|
<file_sep>//
// PackageImageLoader.cs
//
// Author:
// <NAME> <<EMAIL>>
//
// Copyright (c) 2014 Xamarin Inc. (http://xamarin.com)
//
// 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.
using System;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using MonoDevelop.Core;
using NuGet;
using MonoDevelop.PackageManagement;
using Xwt.Drawing;
using System.Collections.Generic;
namespace MonoDevelop.PackageManagement
{
internal class ImageLoader
{
public event EventHandler<ImageLoadedEventArgs> Loaded;
BackgroundDispatcher dispatcher;
Dictionary<Uri, List<object>> callersWaitingForImageLoad = new Dictionary<Uri, List<object>> ();
static readonly ImageCache imageCache = new ImageCache ();
public void LoadFrom (string uri, object state)
{
LoadFrom (new Uri (uri), state);
}
public void LoadFrom (Uri uri, object state)
{
Image image = imageCache.GetImage (uri);
if (image != null) {
OnLoaded (new ImageLoadedEventArgs (image, uri, state));
return;
}
if (AddToCallersWaitingForImageLoad (uri, state))
return;
if (dispatcher == null) {
dispatcher = new BackgroundDispatcher ();
dispatcher.Start ("Paket image loader");
}
dispatcher.Dispatch (() => {
ImageLoadedEventArgs eventArgs = LoadImage (uri, state);
Runtime.RunInMainThread (() => {
OnLoaded (eventArgs);
eventArgs = null;
});
});
}
bool AddToCallersWaitingForImageLoad (Uri uri, object state)
{
List<object> callers = GetCallersWaitingForImageLoad (uri);
if (callers != null) {
callers.Add (state);
return true;
} else {
callersWaitingForImageLoad.Add (uri, new List<object> ());
}
return false;
}
List<object> GetCallersWaitingForImageLoad (Uri uri)
{
List<object> callers = null;
if (callersWaitingForImageLoad.TryGetValue (uri, out callers)) {
return callers;
}
return null;
}
ImageLoadedEventArgs LoadImage (Uri uri, object state)
{
try {
Stream stream = GetResponseStream (uri);
var loader = Runtime.RunInMainThread (() => Image.FromStream (stream));
return new ImageLoadedEventArgs (loader.Result, uri, state);
} catch (Exception ex) {
return new ImageLoadedEventArgs (ex, uri, state);
}
}
static Stream GetResponseStream (Uri uri)
{
WebResponse response = null;
if (uri.IsFile) {
var request = WebRequest.Create (uri);
response = request.GetResponse ();
} else {
var httpClient = new HttpClient (uri);
response = httpClient.GetResponse ();
}
var stream = new MemoryStream ();
response.GetResponseStream ().CopyTo (stream); // force the download to complete
stream.Position = 0;
return stream;
}
void OnLoaded (ImageLoadedEventArgs eventArgs)
{
if (eventArgs.Image != null) {
imageCache.AddImage (eventArgs.Uri, eventArgs.Image);
}
OnLoaded (this, eventArgs);
List<object> callers = GetCallersWaitingForImageLoad (eventArgs.Uri);
if (callers != null) {
OnLoaded (callers, eventArgs);
callersWaitingForImageLoad.Remove (eventArgs.Uri);
}
}
void OnLoaded (object sender, ImageLoadedEventArgs eventArgs)
{
if (Loaded != null) {
Loaded (this, eventArgs);
}
}
void OnLoaded (IEnumerable<object> states, ImageLoadedEventArgs eventArgs)
{
foreach (object state in states) {
OnLoaded (this, eventArgs.WithState (state));
}
}
public void ShrinkImageCache ()
{
imageCache.ShrinkImageCache ();
}
public void Dispose ()
{
dispatcher?.Stop ();
ShrinkImageCache ();
}
}
}
<file_sep>//
// MonoDevelopNuGetProjectFactory.cs
//
// Author:
// <NAME> <<EMAIL>>
//
// Copyright (c) 2016 Xamarin Inc. (http://xamarin.com)
//
// 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.
using System;
using System.IO;
using MonoDevelop.Core;
using MonoDevelop.Projects;
using NuGet.Common;
using NuGet.Configuration;
using NuGet.PackageManagement;
using NuGet.ProjectManagement;
namespace MonoDevelop.PackageManagement
{
internal class MonoDevelopNuGetProjectFactory
{
ISettings settings;
public MonoDevelopNuGetProjectFactory ()
: this (SettingsLoader.LoadDefaultSettings ())
{
}
public MonoDevelopNuGetProjectFactory (ISettings settings)
{
this.settings = settings;
}
public NuGetProject CreateNuGetProject (IDotNetProject project)
{
return CreateNuGetProject (project.DotNetProject);
}
public NuGetProject CreateNuGetProject (DotNetProject project)
{
return CreateNuGetProject (project, new EmptyNuGetProjectContext ());
}
public NuGetProject CreateNuGetProject (IDotNetProject project, INuGetProjectContext context)
{
return CreateNuGetProject (project.DotNetProject, context);
}
public NuGetProject CreateNuGetProject (DotNetProject project, INuGetProjectContext context)
{
Runtime.AssertMainThread ();
var projectSystem = new MonoDevelopMSBuildNuGetProjectSystem (project, context);
string projectJsonPath = ProjectJsonPathUtilities.GetProjectConfigPath (project.BaseDirectory, project.Name);
if (File.Exists (projectJsonPath)) {
return new BuildIntegratedProjectSystem (
projectJsonPath,
project.FileName,
project,
projectSystem,
project.Name,
settings);
}
string baseDirectory = GetBaseDirectory (project);
string folderNuGetProjectFullPath = PackagesFolderPathUtility.GetPackagesFolderPath (baseDirectory, settings);
string packagesConfigFolderPath = project.BaseDirectory;
return new MSBuildNuGetProject (
projectSystem,
folderNuGetProjectFullPath,
packagesConfigFolderPath);
}
static string GetBaseDirectory (DotNetProject project)
{
if (project.ParentSolution != null)
return project.ParentSolution.BaseDirectory;
LoggingService.LogWarning ("Project has no solution. Using project directory as base directory for NuGet. Project: '{0}'", project.FileName);
return project.BaseDirectory;
}
}
}
<file_sep>// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using NuGet.Packaging.Core;
using NuGet.ProjectManagement;
using NuGet.Versioning;
namespace NuGet.PackageManagement.UI
{
// used to manage packages in one project.
internal class PackageDetailControlModel : DetailControlModel
{
public PackageDetailControlModel (NuGetProject nugetProject)
: this (new [] { nugetProject })
{
}
public PackageDetailControlModel(
IEnumerable<NuGetProject> nugetProjects)
: base(nugetProjects)
{
Debug.Assert(nugetProjects.Count() == 1);
}
//public async override Task SetCurrentPackage(
// PackageItemListViewModel searchResultPackage)
// ItemFilter filter)
//{
// await base.SetCurrentPackage(searchResultPackage);
//
// UpdateInstalledVersion();
//}
public override bool IsSolution
{
get { return false; }
}
/*
private void UpdateInstalledVersion()
{
var installed = InstalledPackageDependencies.Where(p =>
StringComparer.OrdinalIgnoreCase.Equals(p.Id, Id)).OrderByDescending(p => p.VersionRange?.MinVersion, VersionComparer.Default);
var dependency = installed.FirstOrDefault(package => package.VersionRange != null && package.VersionRange.HasLowerBound);
if (dependency != null)
{
InstalledVersion = dependency.VersionRange.MinVersion;
}
else
{
InstalledVersion = null;
}
}
*/
public override void Refresh()
{
// UpdateInstalledVersion();
// CreateVersions();
}
private static bool HasId(string id, IEnumerable<PackageIdentity> packages)
{
return packages.Any(p =>
StringComparer.OrdinalIgnoreCase.Equals(p.Id, id));
}
protected override void CreateVersions()
{
/* _versions = new List<DisplayVersion>();
var installedDependency = InstalledPackageDependencies.Where(p =>
StringComparer.OrdinalIgnoreCase.Equals(p.Id, Id) && p.VersionRange != null && p.VersionRange.HasLowerBound)
.OrderByDescending(p => p.VersionRange.MinVersion)
.FirstOrDefault();
// installVersion is null if the package is not installed
var installedVersion = installedDependency?.VersionRange?.MinVersion;
var allVersions = _allPackageVersions.OrderByDescending(v => v);
var latestPrerelease = allVersions.FirstOrDefault(v => v.IsPrerelease);
var latestStableVersion = allVersions.FirstOrDefault(v => !v.IsPrerelease);
// Add lastest prerelease if neeeded
if (latestPrerelease != null
&& (latestStableVersion == null || latestPrerelease > latestStableVersion) &&
!latestPrerelease.Equals(installedVersion))
{
_versions.Add(new DisplayVersion(latestPrerelease, Resources.Version_LatestPrerelease));
}
// Add latest stable if needed
if (latestStableVersion != null &&
!latestStableVersion.Equals(installedVersion))
{
_versions.Add(new DisplayVersion(latestStableVersion, Resources.Version_LatestStable));
}
// add a separator
if (_versions.Count > 0)
{
_versions.Add(null);
}
foreach (var version in allVersions)
{
if (!version.Equals(installedVersion))
{
_versions.Add(new DisplayVersion(version, string.Empty));
}
}
SelectVersion();
OnPropertyChanged(nameof(Versions));
*/ }
private NuGetVersion _installedVersion;
public NuGetVersion InstalledVersion
{
get { return _installedVersion; }
private set
{
_installedVersion = value;
OnPropertyChanged(nameof(InstalledVersion));
}
}
//public override IEnumerable<NuGetProject> GetSelectedProjects(UserAction action)
//{
// return _nugetProjects;
//}
public IEnumerable<NuGetVersion> AllPackageVersions {
get { return _allPackageVersions; }
}
}
}<file_sep>// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Globalization;
using NuGet.Versioning;
namespace NuGet.PackageManagement.UI
{
public class PackageDependencyMetadata
{
public PackageDependencyMetadata()
{
}
public PackageDependencyMetadata(Packaging.Core.PackageDependency serverData)
{
Id = serverData.Id;
Range = serverData.VersionRange;
}
public string Id { get; }
public VersionRange Range { get; }
public PackageDependencyMetadata(string id, VersionRange range)
{
Id = id;
Range = range;
}
public override string ToString()
{
if (Range == null)
{
return Id;
}
return string.Format(
CultureInfo.InvariantCulture,
"{0} {1}",
Id, Range.PrettyPrint());
}
}
}<file_sep>//
// PackageSearchResultViewModel.cs
//
// Author:
// <NAME> <<EMAIL>>
//
// Copyright (c) 2016 Xamarin Inc. (http://xamarin.com)
//
// 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.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using MonoDevelop.Core;
using MonoDevelop.Paket;
using NuGet.Common;
using NuGet.PackageManagement.UI;
using NuGet.Packaging.Core;
using NuGet.Protocol.Core.Types;
using NuGet.Frameworks;
using NuGet.Versioning;
namespace MonoDevelop.PackageManagement
{
internal class PackageSearchResultViewModel : ViewModelBase<PackageSearchResultViewModel>
{
AllPackagesViewModel parent;
PackageItemListViewModel viewModel;
PackageDetailControlModel packageDetailModel;
List<PackageDependencyMetadata> dependencies;
string summary;
bool isChecked;
NuGetVersion selectedVersion;
public PackageSearchResultViewModel (
AllPackagesViewModel parent,
PackageItemListViewModel viewModel)
{
this.parent = parent;
this.viewModel = viewModel;
Versions = new ObservableCollection<NuGetVersion> ();
SelectedVersion = Version;
IsLatestVersionSelected = true;
}
public AllPackagesViewModel Parent {
get { return parent; }
set { parent = value; }
}
public string Id {
get { return viewModel.Id; }
}
public NuGetVersion Version {
get { return viewModel.Version; }
}
public string Title {
get { return viewModel.Title; }
}
public string Name {
get {
if (String.IsNullOrEmpty (Title))
return Id;
return Title;
}
}
public bool IsChecked {
get { return isChecked; }
set {
if (value != isChecked) {
isChecked = value;
parent.OnPackageCheckedChanged (this);
}
}
}
public bool HasLicenseUrl {
get { return LicenseUrl != null; }
}
public Uri LicenseUrl {
get { return viewModel.LicenseUrl; }
}
public bool HasProjectUrl {
get { return ProjectUrl != null; }
}
public Uri ProjectUrl {
get { return viewModel.ProjectUrl; }
}
public bool HasGalleryUrl {
get { return GalleryUrl != null; }
}
public bool HasNoGalleryUrl {
get { return !HasGalleryUrl; }
}
public Uri GalleryUrl {
get { return null; }
//get { return viewModel.GalleryUrl; }
}
public Uri IconUrl {
get { return viewModel.IconUrl; }
}
public bool HasIconUrl {
get { return IconUrl != null; }
}
public string Author {
get { return viewModel.Author; }
}
public string Summary {
get {
if (summary == null) {
summary = StripNewLinesAndIndentation (GetSummaryOrDescription ());
}
return summary;
}
}
string GetSummaryOrDescription ()
{
if (String.IsNullOrEmpty (viewModel.Summary))
return viewModel.Description;
return viewModel.Summary;
}
string StripNewLinesAndIndentation (string text)
{
return PackageListViewTextFormatter.Format (text);
}
public string Description {
get { return viewModel.Description; }
}
public bool HasDownloadCount {
get { return viewModel.DownloadCount >= 0; }
}
public string GetNameMarkup ()
{
return GetBoldText (Name);
}
static string GetBoldText (string text)
{
return String.Format ("<b>{0}</b>", text);
}
public string GetDownloadCountOrVersionDisplayText ()
{
if (ShowVersionInsteadOfDownloadCount) {
return Version.ToString ();
}
return GetDownloadCountDisplayText ();
}
public string GetDownloadCountDisplayText ()
{
if (HasDownloadCount) {
return viewModel.DownloadCount.Value.ToString ("N0");
}
return String.Empty;
}
public bool ShowVersionInsteadOfDownloadCount { get; set; }
public DateTimeOffset? LastPublished {
get { return viewModel.Published; }
}
public bool HasLastPublished {
get { return viewModel.Published.HasValue; }
}
public string GetLastPublishedDisplayText()
{
if (HasLastPublished) {
return LastPublished.Value.Date.ToShortDateString ();
}
return String.Empty;
}
public bool IsLatestVersionSelected { get; private set; }
public NuGetVersion SelectedVersion {
get { return selectedVersion; }
set {
selectedVersion = value;
IsLatestVersionSelected = (value is LatestNuGetVersion);
}
}
public ObservableCollection<NuGetVersion> Versions { get; private set; }
protected virtual Task ReadVersions (CancellationToken cancellationToken)
{
try {
packageDetailModel = new PackageDetailControlModel (parent.NuGetProject);
packageDetailModel.SelectedVersion = new DisplayVersion (SelectedVersion, null);
return ReadVersionsFromPackageDetailControlModel (cancellationToken).ContinueWith (
task => OnVersionsRead (task),
TaskScheduler.FromCurrentSynchronizationContext ());
} catch (Exception ex) {
LoggingService.LogError ("ReadVersions error.", ex);
}
return Task.FromResult (0);
}
Task ReadVersionsFromPackageDetailControlModel (CancellationToken cancellationToken)
{
if (!IsRecentPackage) {
return packageDetailModel.SetCurrentPackage (viewModel);
}
return ReadVersionsForRecentPackage (cancellationToken);
}
async Task ReadVersionsForRecentPackage (CancellationToken cancellationToken)
{
var identity = new PackageIdentity (viewModel.Id, viewModel.Version);
foreach (var sourceRepository in parent.SelectedPackageSource.GetSourceRepositories ()) {
try {
var metadata = await sourceRepository.GetPackageMetadataAsync (identity, parent.IncludePrerelease, cancellationToken);
if (metadata != null) {
var packageViewModel = CreatePackageItemListViewModel (metadata);
await packageDetailModel.SetCurrentPackage (packageViewModel);
return;
}
} catch (Exception ex) {
LoggingService.LogError (
String.Format ("Unable to get metadata for {0} from source {1}.", identity, sourceRepository.PackageSource.Name),
ex);
}
}
}
PackageItemListViewModel CreatePackageItemListViewModel (IPackageSearchMetadata metadata)
{
return new PackageItemListViewModel {
Id = metadata.Identity.Id,
Version = metadata.Identity.Version,
IconUrl = metadata.IconUrl,
Author = metadata.Authors,
DownloadCount = metadata.DownloadCount,
Summary = metadata.Summary,
Description = metadata.Description,
Title = metadata.Title,
LicenseUrl = metadata.LicenseUrl,
ProjectUrl = metadata.ProjectUrl,
Published = metadata.Published,
Versions = AsyncLazy.New (() => metadata.GetVersionsAsync ())
};
}
void OnVersionsRead (Task task)
{
try {
if (task.IsFaulted) {
LoggingService.LogError ("Failed to read package versions.", task.Exception);
} else if (task.IsCanceled) {
// Ignore.
} else {
Versions.Clear ();
foreach (NuGetVersion version in packageDetailModel.AllPackageVersions.OrderByDescending (v => v.Version)) {
Versions.Add (version);
}
OnPropertyChanged (viewModel => viewModel.Versions);
}
} catch (Exception ex) {
LoggingService.LogError ("Failed to read package versions.", ex);
}
}
public bool IsOlderPackageInstalled ()
{
return parent.IsOlderPackageInstalled (Id, SelectedVersion);
}
public override bool Equals (object obj)
{
var other = obj as PackageSearchResultViewModel;
if (other == null)
return false;
return StringComparer.OrdinalIgnoreCase.Equals (Id, other.Id);
}
public override int GetHashCode ()
{
return Id.GetHashCode ();
}
public void UpdateFromPreviouslyCheckedViewModel (PackageSearchResultViewModel packageViewModel)
{
IsChecked = packageViewModel.IsChecked;
SelectedVersion = packageViewModel.SelectedVersion;
IsLatestVersionSelected = packageViewModel.IsLatestVersionSelected;
if (SelectedVersion != Version) {
Versions.Add (Version);
Versions.Add (SelectedVersion);
}
}
public void LoadPackageMetadata (IPackageMetadataProvider metadataProvider, CancellationToken cancellationToken)
{
if (packageDetailModel != null) {
return;
}
if (IsRecentPackage) {
ReadVersions (cancellationToken).ContinueWith (
task => LoadPackageMetadataFromPackageDetailModel (metadataProvider, cancellationToken),
TaskScheduler.FromCurrentSynchronizationContext ());
} else {
ReadVersions (cancellationToken);
LoadPackageMetadataFromPackageDetailModel (metadataProvider, cancellationToken);
}
}
void LoadPackageMetadataFromPackageDetailModel (IPackageMetadataProvider metadataProvider, CancellationToken cancellationToken)
{
try {
LoadPackageMetadataFromPackageDetailModelAsync (metadataProvider, cancellationToken);
} catch (Exception ex) {
LoggingService.LogError ("Error getting detailed package metadata.", ex);
}
}
protected virtual Task LoadPackageMetadataFromPackageDetailModelAsync (
IPackageMetadataProvider metadataProvider,
CancellationToken cancellationToken)
{
return packageDetailModel.LoadPackageMetadaAsync (metadataProvider, cancellationToken).ContinueWith (
task => OnPackageMetadataLoaded (task),
TaskScheduler.FromCurrentSynchronizationContext ());
}
void OnPackageMetadataLoaded (Task task)
{
try {
if (task.IsFaulted) {
LoggingService.LogError ("Failed to read package metadata.", task.Exception);
} else if (task.IsCanceled) {
// Ignore.
} else {
var metadata = packageDetailModel?.PackageMetadata;
if (metadata != null) {
viewModel.Published = metadata.Published;
dependencies = GetCompatibleDependencies ().ToList ();
OnPropertyChanged ("Dependencies");
}
}
} catch (Exception ex) {
LoggingService.LogError ("Failed to read package metadata.", ex);
}
}
public bool HasDependencies {
get { return CompatibleDependencies.Any (); }
}
public bool HasNoDependencies {
get { return !HasDependencies; }
}
public string GetPackageDependenciesDisplayText ()
{
var displayText = new StringBuilder ();
foreach (PackageDependencyMetadata dependency in CompatibleDependencies) {
displayText.AppendLine (dependency.ToString ());
}
return displayText.ToString ();
}
IEnumerable<PackageDependencyMetadata> CompatibleDependencies {
get { return dependencies ?? new List<PackageDependencyMetadata> (); }
}
IEnumerable<PackageDependencyMetadata> GetCompatibleDependencies ()
{
var metadata = packageDetailModel?.PackageMetadata;
if (metadata?.HasDependencies == true && parent.Project.DotNetProject != null) {
var projectTargetFramework = new ProjectTargetFramework (parent.Project);
var targetFramework = NuGetFramework.Parse (projectTargetFramework.TargetFrameworkName.FullName);
foreach (var dependencySet in packageDetailModel.PackageMetadata.DependencySets) {
if (DefaultCompatibilityProvider.Instance.IsCompatible (targetFramework, dependencySet.TargetFramework)) {
return dependencySet.Dependencies;
}
}
}
return Enumerable.Empty<PackageDependencyMetadata> ();
}
public bool IsDependencyInformationAvailable {
get { return dependencies != null; }
}
public bool IsRecentPackage { get; set; }
public void ResetDetailedPackageMetadata ()
{
packageDetailModel = null;
}
public void ResetForRedisplay (bool includePrereleaseVersions)
{
ResetDetailedPackageMetadata ();
IsChecked = false;
if (!includePrereleaseVersions) {
RemovePrereleaseVersions ();
}
}
void RemovePrereleaseVersions ()
{
var prereleaseVersions = Versions.Where (version => version.IsPrerelease).ToArray ();
foreach (NuGetVersion prereleaseVersion in prereleaseVersions) {
Versions.Remove (prereleaseVersion);
}
}
}
}
<file_sep>//
// AllPackagesViewModel.cs
//
// Author:
// <NAME> <<EMAIL>>
//
// Copyright (c) 2016 Xamarin Inc. (http://xamarin.com)
//
// 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.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using MonoDevelop.Core;
using MonoDevelop.Ide;
using MonoDevelop.Projects;
using NuGet.Configuration;
using NuGet.PackageManagement;
using NuGet.PackageManagement.UI;
using NuGet.Packaging;
using NuGet.ProjectManagement;
using NuGet.Protocol.Core.Types;
using NuGet.Versioning;
namespace MonoDevelop.PackageManagement
{
internal class AllPackagesViewModel : ViewModelBase<AllPackagesViewModel>, INuGetUILogger
{
SourceRepositoryViewModel selectedPackageSource;
IPackageSourceProvider packageSourceProvider;
PackageItemLoader currentLoader;
CancellationTokenSource cancellationTokenSource;
List<SourceRepositoryViewModel> packageSources;
bool includePrerelease;
bool ignorePackageCheckedChanged;
IMonoDevelopSolutionManager solutionManager;
NuGetProject nugetProject;
IDotNetProject dotNetProject;
List<PackageReference> packageReferences = new List<PackageReference> ();
AggregatePackageSourceErrorMessage aggregateErrorMessage;
NuGetPackageManager packageManager;
RecentNuGetPackagesRepository recentPackagesRepository;
public static AllPackagesViewModel Create (RecentNuGetPackagesRepository recentPackagesRepository)
{
var solutionManager = new MonoDevelopSolutionManager (IdeApp.ProjectOperations.CurrentSelectedSolution);
var dotNetProject = new DotNetProjectProxy ((DotNetProject)IdeApp.ProjectOperations.CurrentSelectedProject);
return new AllPackagesViewModel (solutionManager, dotNetProject, recentPackagesRepository);
}
public AllPackagesViewModel (
IMonoDevelopSolutionManager solutionManager,
IDotNetProject dotNetProject,
RecentNuGetPackagesRepository recentPackagesRepository)
{
this.solutionManager = solutionManager;
this.dotNetProject = dotNetProject;
this.recentPackagesRepository = recentPackagesRepository;
PackageViewModels = new ObservableCollection<PackageSearchResultViewModel> ();
CheckedPackageViewModels = new ObservableCollection<PackageSearchResultViewModel> ();
ErrorMessage = String.Empty;
packageManager = new NuGetPackageManager (
solutionManager.CreateSourceRepositoryProvider (),
solutionManager.Settings,
solutionManager,
new DeleteOnRestartManager ()
);
if (dotNetProject.DotNetProject != null) {
nugetProject = solutionManager.GetNuGetProject (dotNetProject);
GetPackagesInstalledInProject ();
}
}
public NuGetProject NuGetProject {
get { return nugetProject; }
}
public IDotNetProject Project {
get { return dotNetProject; }
}
public string SearchTerms { get; set; }
public IEnumerable<SourceRepositoryViewModel> PackageSources {
get {
if (packageSources == null) {
packageSources = GetPackageSources ().ToList ();
}
return packageSources;
}
}
IEnumerable<SourceRepositoryViewModel> GetPackageSources ()
{
ISourceRepositoryProvider provider = solutionManager.CreateSourceRepositoryProvider ();
packageSourceProvider = provider.PackageSourceProvider;
var repositories = provider.GetRepositories ().ToList ();
if (repositories.Count > 1) {
// yield return new AggregateSourceRepositoryViewModel (repositories);
}
foreach (SourceRepository repository in repositories) {
yield return new SourceRepositoryViewModel (repository);
}
}
public SourceRepositoryViewModel SelectedPackageSource {
get {
if (selectedPackageSource == null) {
selectedPackageSource = GetActivePackageSource ();
}
return selectedPackageSource;
}
set {
if (selectedPackageSource != value) {
selectedPackageSource = value;
SaveActivePackageSource ();
ReadPackages ();
OnPropertyChanged (null);
}
}
}
SourceRepositoryViewModel GetActivePackageSource ()
{
if (packageSources == null)
return null;
if (!String.IsNullOrEmpty (packageSourceProvider.ActivePackageSourceName)) {
SourceRepositoryViewModel packageSource = packageSources
.FirstOrDefault (viewModel => String.Equals (viewModel.PackageSource.Name, packageSourceProvider.ActivePackageSourceName, StringComparison.CurrentCultureIgnoreCase));
if (packageSource != null) {
return packageSource;
}
}
return packageSources.FirstOrDefault (packageSource => !packageSource.IsAggregate);
}
void SaveActivePackageSource ()
{
if (selectedPackageSource == null || packageSourceProvider == null)
return;
packageSourceProvider.SaveActivePackageSource (selectedPackageSource.PackageSource);
}
public ObservableCollection<PackageSearchResultViewModel> PackageViewModels { get; private set; }
public ObservableCollection<PackageSearchResultViewModel> CheckedPackageViewModels { get; private set; }
public bool HasError { get; private set; }
public string ErrorMessage { get; private set; }
public bool IsLoadingNextPage { get; private set; }
public bool IsReadingPackages { get; private set; }
public bool HasNextPage { get; private set; }
public bool IncludePrerelease {
get { return includePrerelease; }
set {
if (includePrerelease != value) {
includePrerelease = value;
ReadPackages ();
OnPropertyChanged (null);
}
}
}
public void Dispose()
{
OnDispose ();
CancelReadPackagesTask ();
IsDisposed = true;
}
protected virtual void OnDispose()
{
}
public bool IsDisposed { get; private set; }
public void Search ()
{
ReadPackages ();
OnPropertyChanged (null);
}
public void ReadPackages ()
{
if (SelectedPackageSource == null) {
return;
}
HasNextPage = false;
IsLoadingNextPage = false;
currentLoader = null;
StartReadPackagesTask ();
}
void StartReadPackagesTask (bool clearPackages = true)
{
IsReadingPackages = true;
ClearError ();
if (clearPackages) {
CancelReadPackagesTask ();
ClearPackages ();
}
CreateReadPackagesTask ();
}
void CancelReadPackagesTask()
{
if (cancellationTokenSource != null) {
// Cancel on another thread since CancellationTokenSource.Cancel can sometimes
// take up to a second on Mono and we do not want to block the UI thread.
var tokenSource = cancellationTokenSource;
Task.Run (() => {
try {
tokenSource.Cancel ();
tokenSource.Dispose ();
} catch (Exception ex) {
LoggingService.LogError ("Unable to cancel task.", ex);
}
});
cancellationTokenSource = null;
}
}
protected virtual Task CreateReadPackagesTask()
{
var loader = currentLoader ?? CreatePackageLoader ();
cancellationTokenSource = cancellationTokenSource ?? new CancellationTokenSource ();
return LoadPackagesAsync (loader, cancellationTokenSource.Token)
.ContinueWith (t => OnPackagesRead (t, loader), TaskScheduler.FromCurrentSynchronizationContext ());
}
PackageItemLoader CreatePackageLoader ()
{
var context = new PackageLoadContext (
selectedPackageSource.GetSourceRepositories (),
false,
nugetProject);
var loader = new PackageItemLoader (
context,
CreatePackageFeed (context.SourceRepositories),
SearchTerms,
IncludePrerelease
);
currentLoader = loader;
return loader;
}
protected virtual IPackageFeed CreatePackageFeed (IEnumerable<SourceRepository> sourceRepositories)
{
return new MultiSourcePackageFeed (sourceRepositories, this);
}
protected virtual Task LoadPackagesAsync (PackageItemLoader loader, CancellationToken token)
{
return Task.Run (async () => {
await loader.LoadNextAsync (null, token);
while (loader.State.LoadingStatus == LoadingStatus.Loading) {
token.ThrowIfCancellationRequested ();
await loader.UpdateStateAsync (null, token);
}
});
}
void ClearError ()
{
HasError = false;
ErrorMessage = String.Empty;
aggregateErrorMessage = new AggregatePackageSourceErrorMessage (GetTotalPackageSources ());
}
int GetTotalPackageSources ()
{
if (selectedPackageSource != null) {
return selectedPackageSource.GetSourceRepositories ().Count ();
}
return 0;
}
public void ShowNextPage ()
{
IsLoadingNextPage = true;
StartReadPackagesTask (false);
base.OnPropertyChanged (null);
}
void OnPackagesRead (Task task, PackageItemLoader loader)
{
IsReadingPackages = false;
IsLoadingNextPage = false;
if (task.IsFaulted) {
SaveError (task.Exception);
} else if (task.IsCanceled || !IsCurrentQuery (loader)) {
// Ignore.
return;
} else {
SaveAnyWarnings ();
UpdatePackagesForSelectedPage (loader);
}
base.OnPropertyChanged (null);
}
bool IsCurrentQuery (PackageItemLoader loader)
{
return currentLoader == loader;
}
void SaveError (AggregateException ex)
{
HasError = true;
ErrorMessage = GetErrorMessage (ex);
LoggingService.LogInfo ("PackagesViewModel error", ex);
}
string GetErrorMessage (AggregateException ex)
{
var errorMessage = new AggregateExceptionErrorMessage (ex);
return errorMessage.ToString ();
}
void SaveAnyWarnings ()
{
string warning = GetWarningMessage ();
if (!String.IsNullOrEmpty (warning)) {
HasError = true;
ErrorMessage = warning;
}
}
protected virtual string GetWarningMessage ()
{
return String.Empty;
}
void UpdatePackagesForSelectedPage (PackageItemLoader loader)
{
HasNextPage = loader.State.LoadingStatus == LoadingStatus.Ready;
UpdatePackageViewModels (loader.GetCurrent ());
}
void UpdatePackageViewModels (IEnumerable<PackageItemListViewModel> newPackageViewModels)
{
var packages = ConvertToPackageViewModels (newPackageViewModels).ToList ();
packages = PrioritizePackages (packages).ToList ();
foreach (PackageSearchResultViewModel packageViewModel in packages) {
PackageViewModels.Add (packageViewModel);
}
}
public IEnumerable<PackageSearchResultViewModel> ConvertToPackageViewModels (IEnumerable<PackageItemListViewModel> itemViewModels)
{
foreach (PackageItemListViewModel itemViewModel in itemViewModels) {
PackageSearchResultViewModel packageViewModel = CreatePackageViewModel (itemViewModel);
UpdatePackageViewModelIfPreviouslyChecked (packageViewModel);
yield return packageViewModel;
}
}
PackageSearchResultViewModel CreatePackageViewModel (PackageItemListViewModel viewModel)
{
return new PackageSearchResultViewModel (this, viewModel);
}
void ClearPackages ()
{
PackageViewModels.Clear();
}
public void OnPackageCheckedChanged (PackageSearchResultViewModel packageViewModel)
{
if (ignorePackageCheckedChanged)
return;
if (packageViewModel.IsChecked) {
UncheckExistingCheckedPackageWithDifferentVersion (packageViewModel);
CheckedPackageViewModels.Add (packageViewModel);
} else {
CheckedPackageViewModels.Remove (packageViewModel);
}
}
void UpdatePackageViewModelIfPreviouslyChecked (PackageSearchResultViewModel packageViewModel)
{
ignorePackageCheckedChanged = true;
try {
PackageSearchResultViewModel existingPackageViewModel = GetExistingCheckedPackageViewModel (packageViewModel.Id);
if (existingPackageViewModel != null) {
packageViewModel.UpdateFromPreviouslyCheckedViewModel (existingPackageViewModel);
CheckedPackageViewModels.Remove (existingPackageViewModel);
CheckedPackageViewModels.Add (packageViewModel);
}
} finally {
ignorePackageCheckedChanged = false;
}
}
void UncheckExistingCheckedPackageWithDifferentVersion (PackageSearchResultViewModel packageViewModel)
{
PackageSearchResultViewModel existingPackageViewModel = GetExistingCheckedPackageViewModel (packageViewModel.Id);
if (existingPackageViewModel != null) {
CheckedPackageViewModels.Remove (existingPackageViewModel);
existingPackageViewModel.IsChecked = false;
}
}
PackageSearchResultViewModel GetExistingCheckedPackageViewModel (string packageId)
{
return CheckedPackageViewModels
.FirstOrDefault (item => item.Id == packageId);
}
public PackageSearchResultViewModel SelectedPackage { get; set; }
public bool IsOlderPackageInstalled (string id, NuGetVersion version)
{
return packageReferences.Any (packageReference => IsOlderPackageInstalled (packageReference, id, version));
}
bool IsOlderPackageInstalled (PackageReference packageReference, string id, NuGetVersion version)
{
return packageReference.PackageIdentity.Id == id &&
packageReference.PackageIdentity.Version < version;
}
protected virtual Task GetPackagesInstalledInProject ()
{
return nugetProject
.GetInstalledPackagesAsync (CancellationToken.None)
.ContinueWith (task => OnReadInstalledPackages (task), TaskScheduler.FromCurrentSynchronizationContext ());
}
void OnReadInstalledPackages (Task<IEnumerable<PackageReference>> task)
{
try {
if (task.IsFaulted) {
LoggingService.LogError ("Unable to read installed packages.", task.Exception);
} else {
packageReferences = task.Result.ToList ();
}
} catch (Exception ex) {
LoggingService.LogError ("OnReadInstalledPackages", ex);
}
}
void INuGetUILogger.Log (MessageLevel level, string message, params object [] args)
{
if (level == MessageLevel.Error) {
string fullErrorMessage = String.Format (message, args);
AppendErrorMessage (fullErrorMessage);
}
}
void AppendErrorMessage (string message)
{
aggregateErrorMessage.AddError (message);
ErrorMessage = aggregateErrorMessage.ErrorMessage;
HasError = true;
OnPropertyChanged (null);
}
public void LoadPackageMetadata (PackageSearchResultViewModel packageViewModel)
{
var provider = new MultiSourcePackageMetadataProvider (
selectedPackageSource.GetSourceRepositories (),
packageManager.PackagesFolderSourceRepository,
packageManager.GlobalPackagesFolderSourceRepository,
new NuGet.Logging.NullLogger ());
packageViewModel.LoadPackageMetadata (provider, cancellationTokenSource.Token);
}
public void OnInstallingSelectedPackages ()
{
try {
UpdateRecentPackages ();
} catch (Exception ex) {
LoggingService.LogError ("Unable to update recent packages", ex);
}
}
void UpdateRecentPackages ()
{
if (SelectedPackageSource == null)
return;
if (CheckedPackageViewModels.Any ()) {
foreach (PackageSearchResultViewModel packageViewModel in CheckedPackageViewModels) {
recentPackagesRepository.AddPackage (packageViewModel, SelectedPackageSource.Name);
}
} else {
recentPackagesRepository.AddPackage (SelectedPackage, SelectedPackageSource.Name);
}
}
IEnumerable<PackageSearchResultViewModel> PrioritizePackages (IEnumerable<PackageSearchResultViewModel> packages)
{
var recentPackages = GetRecentPackages ().ToList ();
foreach (PackageSearchResultViewModel package in recentPackages) {
package.Parent = this;
package.ResetForRedisplay (IncludePrerelease);
yield return package;
}
foreach (PackageSearchResultViewModel package in packages) {
if (!recentPackages.Contains (package, PackageSearchResultViewModelComparer.Instance)) {
yield return package;
}
}
}
IEnumerable<PackageSearchResultViewModel> GetRecentPackages ()
{
if (PackageViewModels.Count == 0 &&
String.IsNullOrEmpty (SearchTerms) &&
selectedPackageSource != null) {
return recentPackagesRepository.GetPackages (SelectedPackageSource.Name)
.Where (recentPackage => SelectedVersionMatchesIncludePreleaseFilter (recentPackage));
}
return Enumerable.Empty<PackageSearchResultViewModel> ();
}
bool SelectedVersionMatchesIncludePreleaseFilter (PackageSearchResultViewModel package)
{
if (package.SelectedVersion.IsPrerelease) {
return IncludePrerelease;
}
return true;
}
}
}
<file_sep>//
// Styles.cs
//
// Author:
// <NAME> <<EMAIL>>
//
// Copyright (c) 2015 Xamarin Inc. (http://www.xamarin.com)
//
// 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.
using MonoDevelop.Ide;
using MonoDevelop.Core;
namespace MonoDevelop.PackageManagement
{
internal static class Styles
{
public static Xwt.Drawing.Color LineBorderColor { get; internal set; }
public static Xwt.Drawing.Color BackgroundColor { get; internal set; }
public static Xwt.Drawing.Color PackageInfoBackgroundColor { get; internal set; }
public static Xwt.Drawing.Color CellBackgroundColor { get; internal set; }
public static Xwt.Drawing.Color CellSelectionColor { get; internal set; }
public static Xwt.Drawing.Color CellStrongSelectionColor { get; internal set; }
public static Xwt.Drawing.Color CellTextColor { get; internal set; }
public static Xwt.Drawing.Color CellTextSelectionColor { get; internal set; }
public static Xwt.Drawing.Color PackageSourceUrlTextColor { get; internal set; }
public static Xwt.Drawing.Color PackageSourceUrlSelectedTextColor { get; internal set; }
public static Xwt.Drawing.Color PackageSourceErrorTextColor { get; internal set; }
public static Xwt.Drawing.Color PackageSourceErrorSelectedTextColor { get; internal set; }
public static Xwt.Drawing.Color ErrorBackgroundColor { get; internal set; }
public static Xwt.Drawing.Color ErrorForegroundColor { get; internal set; }
static Styles ()
{
LoadStyles ();
Ide.Gui.Styles.Changed += (o, e) => LoadStyles ();
}
public static void LoadStyles ()
{
if (IdeApp.Preferences.UserInterfaceTheme == Theme.Light) {
CellBackgroundColor = Ide.Gui.Styles.PadBackground;
} else {
CellBackgroundColor = Xwt.Drawing.Color.FromName ("#3c3c3c");
}
// Shared
BackgroundColor = Ide.Gui.Styles.PrimaryBackgroundColor;
CellTextColor = Ide.Gui.Styles.BaseForegroundColor;
CellStrongSelectionColor = Ide.Gui.Styles.BaseSelectionBackgroundColor;
CellSelectionColor = Ide.Gui.Styles.BaseSelectionBackgroundColor;
CellTextSelectionColor = Ide.Gui.Styles.BaseSelectionTextColor;
PackageInfoBackgroundColor = Ide.Gui.Styles.SecondaryBackgroundLighterColor;
PackageSourceErrorTextColor = Ide.Gui.Styles.ErrorForegroundColor;
PackageSourceUrlTextColor = Ide.Gui.Styles.DimTextColor;
PackageSourceErrorSelectedTextColor = PackageSourceErrorTextColor;
// Blue selection text color only on Mac
PackageSourceUrlSelectedTextColor = Platform.IsMac ? Xwt.Drawing.Color.FromName ("#ffffff") : Ide.Gui.Styles.DimTextColor;
LineBorderColor = Ide.Gui.Styles.SeparatorColor;
ErrorBackgroundColor = Ide.Gui.Styles.StatusWarningBackgroundColor;
ErrorForegroundColor = Ide.Gui.Styles.StatusWarningTextColor;
}
}
}
<file_sep>//
// MonoDevelopMSBuildNuGetProjectSystem.cs
//
// Author:
// <NAME> <<EMAIL>>
//
// Copyright (c) 2016 Xamarin Inc. (http://xamarin.com)
//
// 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.
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using MonoDevelop.Core;
using MonoDevelop.Projects;
using MonoDevelop.Projects.MSBuild;
using NuGet.Frameworks;
using NuGet.Packaging.Core;
using NuGet.ProjectManagement;
namespace MonoDevelop.PackageManagement
{
internal class MonoDevelopMSBuildNuGetProjectSystem : IMSBuildNuGetProjectSystem
{
IDotNetProject project;
NuGetFramework targetFramework;
string projectFullPath;
// IPackageManagementEvents packageManagementEvents;
// IPackageManagementFileService fileService;
Action<Action> guiSyncDispatcher;
Func<Func<Task>,Task> guiSyncDispatcherFunc;
public MonoDevelopMSBuildNuGetProjectSystem (DotNetProject project, INuGetProjectContext context)
: this (
new DotNetProjectProxy (project),
context,
// new PackageManagementFileService (),
// PackageManagementServices.PackageManagementEvents,
DefaultGuiSyncDispatcher,
GuiSyncDispatchWithException)
{
}
public MonoDevelopMSBuildNuGetProjectSystem (
IDotNetProject project,
INuGetProjectContext context,
// IPackageManagementFileService fileService,
// IPackageManagementEvents packageManagementEvents,
Action<Action> guiSyncDispatcher,
Func<Func<Task>, Task> guiSyncDispatcherFunc)
{
this.project = project;
NuGetProjectContext = context;
// this.fileService = fileService;
// this.packageManagementEvents = packageManagementEvents;
this.guiSyncDispatcher = guiSyncDispatcher;
this.guiSyncDispatcherFunc = guiSyncDispatcherFunc;
}
public INuGetProjectContext NuGetProjectContext { get; private set; }
public string ProjectFullPath {
get {
if (projectFullPath == null) {
projectFullPath = GuiSyncDispatch (() => project.BaseDirectory);
}
return projectFullPath;
}
}
public string ProjectName {
get {
return GuiSyncDispatch (() => project.Name);
}
}
public string ProjectUniqueName {
get { return ProjectName; }
}
public NuGetFramework TargetFramework {
get {
if (targetFramework == null) {
targetFramework = GuiSyncDispatch (() => GetTargetFramework ());
}
return targetFramework;
}
}
NuGetFramework GetTargetFramework()
{
var projectTargetFramework = new ProjectTargetFramework (project);
return NuGetFramework.Parse (projectTargetFramework.TargetFrameworkName.FullName);
}
public void AddBindingRedirects ()
{
}
public void AddExistingFile (string path)
{
GuiSyncDispatch (async () => await AddFileToProject (path));
}
public void AddFile (string path, Stream stream)
{
PhysicalFileSystemAddFile (path, stream);
GuiSyncDispatch (async () => await AddFileToProject (path));
}
protected virtual void PhysicalFileSystemAddFile (string path, Stream stream)
{
FileSystemUtility.AddFile (ProjectFullPath, path, stream, NuGetProjectContext);
}
async Task AddFileToProject (string path)
{
if (ShouldAddFileToProject (path)) {
await AddFileProjectItemToProject (path);
}
OnFileChanged (path);
LogAddedFileToProject (path);
}
bool ShouldAddFileToProject (string path)
{
return !IsBinDirectory (path) && !FileExistsInProject (path);
}
void OnFileChanged (string path)
{
// GuiSyncDispatch (() => fileService.OnFileChanged (GetFullPath (path)));
}
bool IsBinDirectory(string path)
{
string directoryName = Path.GetDirectoryName (path);
return IsMatchIgnoringCase (directoryName, "bin");
}
async Task AddFileProjectItemToProject(string path)
{
ProjectFile fileItem = CreateFileProjectItem (path);
project.AddFile (fileItem);
await project.SaveAsync ();
}
ProjectFile CreateFileProjectItem(string path)
{
//TODO custom tool?
string fullPath = GetFullPath (path);
string buildAction = project.GetDefaultBuildAction (fullPath);
return new ProjectFile (fullPath) {
BuildAction = buildAction
};
}
void LogAddedFileToProject (string fileName)
{
LogAddedFileToProject (fileName, ProjectName);
}
protected virtual void LogAddedFileToProject (string fileName, string projectName)
{
DebugLogFormat("Added file '{0}' to project '{1}'.", fileName, projectName);
}
public void AddFrameworkReference (string name)
{
GuiSyncDispatch (async () => {
ProjectReference assemblyReference = CreateGacReference (name);
await AddReferenceToProject (assemblyReference);
});
}
ProjectReference CreateGacReference (string name)
{
return ProjectReference.CreateAssemblyReference (name);
}
public void AddImport (string targetFullPath, ImportLocation location)
{
//GuiSyncDispatch (async () => {
// string relativeTargetPath = GetRelativePath (targetFullPath);
// string condition = GetCondition (relativeTargetPath);
// using (var handler = CreateNewImportsHandler ()) {
// handler.AddImportIfMissing (relativeTargetPath, condition, location);
// await project.SaveAsync ();
// }
//});
}
//protected virtual INuGetPackageNewImportsHandler CreateNewImportsHandler ()
//{
// return new NuGetPackageNewImportsHandler ();
//}
static string GetCondition (string targetPath)
{
return String.Format ("Exists('{0}')", targetPath);
}
string GetRelativePath (string path)
{
return MSBuildProjectService.ToMSBuildPath (project.BaseDirectory, path);
}
public void AddReference (string referencePath)
{
GuiSyncDispatch (async () => {
ProjectReference assemblyReference = CreateReference (referencePath);
//packageManagementEvents.OnReferenceAdding (assemblyReference);
await AddReferenceToProject (assemblyReference);
});
}
ProjectReference CreateReference (string referencePath)
{
string fullPath = GetFullPath (referencePath);
return ProjectReference.CreateAssemblyFileReference (fullPath);
}
string GetFullPath (string relativePath)
{
return project.BaseDirectory.Combine (relativePath);
}
async Task AddReferenceToProject (ProjectReference assemblyReference)
{
project.References.Add (assemblyReference);
await project.SaveAsync ();
LogAddedReferenceToProject (assemblyReference);
}
void LogAddedReferenceToProject (ProjectReference referenceProjectItem)
{
LogAddedReferenceToProject (referenceProjectItem.Reference, ProjectName);
}
protected virtual void LogAddedReferenceToProject (string referenceName, string projectName)
{
DebugLogFormat ("Added reference '{0}' to project '{1}'.", referenceName, projectName);
}
void DebugLogFormat (string format, params object[] args)
{
NuGetProjectContext.Log (MessageLevel.Debug, format, args);
}
public void BeginProcessing ()
{
}
// TODO: Support recursive.
public void DeleteDirectory (string path, bool recursive)
{
GuiSyncDispatch (async () => {
string directory = GetFullPath (path);
//fileService.RemoveDirectory (directory);
await project.SaveAsync ();
LogDeletedDirectory (path);
});
}
protected virtual void LogDeletedDirectory (string folder)
{
DebugLogFormat ("Removed folder '{0}'.", folder);
}
public void EndProcessing ()
{
}
public Task ExecuteScriptAsync (PackageIdentity identity, string packageInstallPath, string scriptRelativePath, NuGetProject nuGetProject, bool throwOnFailure)
{
string message = GettextCatalog.GetString (
"WARNING: {0} Package contains PowerShell script '{1}' which will not be run.",
identity.Id,
scriptRelativePath);
NuGetProjectContext.Log (MessageLevel.Info, message);
return Task.FromResult (0);
}
public bool FileExistsInProject (string path)
{
return GuiSyncDispatch (() => {
string fullPath = GetFullPath (path);
return project.IsFileInProject (fullPath);
});
}
public IEnumerable<string> GetDirectories (string path)
{
string fullPath = GetFullPath (path);
return EnumerateDirectories (fullPath);
}
protected virtual IEnumerable<string> EnumerateDirectories (string path)
{
return Directory.EnumerateDirectories (path);
}
public IEnumerable<string> GetFiles (string path, string filter, bool recursive)
{
if (recursive) {
// Visual Studio does not support recursive so we do the same.
throw new NotImplementedException ();
}
string fullPath = GetFullPath (path);
return EnumerateFiles (fullPath, filter, SearchOption.TopDirectoryOnly);
}
protected virtual IEnumerable<string> EnumerateFiles (string path, string searchPattern, SearchOption searchOption)
{
return Directory.EnumerateFiles (path, searchPattern, searchOption);
}
/// <summary>
/// This method is only used when adding/removing binding redirects which are not
/// currently supported.
/// </summary>
public IEnumerable<string> GetFullPaths (string fileName)
{
throw new NotImplementedException ();
}
public dynamic GetPropertyValue (string propertyName)
{
return GuiSyncDispatch (() => {
if ("RootNamespace".Equals(propertyName, StringComparison.OrdinalIgnoreCase)) {
return project.DefaultNamespace;
}
return String.Empty;
});
}
public bool IsSupportedFile (string path)
{
return GuiSyncDispatch (() => {
if (project.IsWebProject ()) {
return !IsAppConfigFile (path);
}
return !IsWebConfigFile (path);
});
}
bool IsWebConfigFile (string path)
{
return IsFileNameMatchIgnoringPath ("web.config", path);
}
bool IsAppConfigFile (string path)
{
return IsFileNameMatchIgnoringPath ("app.config", path);
}
bool IsFileNameMatchIgnoringPath (string fileName1, string path)
{
string fileName2 = Path.GetFileName (path);
return IsMatchIgnoringCase (fileName1, fileName2);
}
public bool ReferenceExists (string name)
{
return GuiSyncDispatch (() => {
ProjectReference referenceProjectItem = FindReference (name);
if (referenceProjectItem != null) {
return true;
}
return false;
});
}
ProjectReference FindReference (string name)
{
string referenceName = GetReferenceName (name);
foreach (ProjectReference referenceProjectItem in project.References) {
string projectReferenceName = GetProjectReferenceName (referenceProjectItem.Reference);
if (IsMatchIgnoringCase (projectReferenceName, referenceName)) {
return referenceProjectItem;
}
}
return null;
}
string GetReferenceName (string name)
{
if (HasDllOrExeFileExtension (name)) {
return Path.GetFileNameWithoutExtension (name);
}
return name;
}
string GetProjectReferenceName (string name)
{
string referenceName = GetReferenceName(name);
return GetAssemblyShortName(referenceName);
}
string GetAssemblyShortName(string name)
{
string[] parts = name.Split(',');
return parts[0];
}
bool HasDllOrExeFileExtension (string name)
{
string extension = Path.GetExtension (name);
return
IsMatchIgnoringCase (extension, ".dll") ||
IsMatchIgnoringCase (extension, ".exe");
}
bool IsMatchIgnoringCase (string lhs, string rhs)
{
return String.Equals (lhs, rhs, StringComparison.InvariantCultureIgnoreCase);
}
public void RegisterProcessedFiles (IEnumerable<string> files)
{
}
public void RemoveFile (string path)
{
GuiSyncDispatch (async () => {
string fileName = GetFullPath (path);
project.Files.Remove (fileName);
//fileService.RemoveFile (fileName);
await project.SaveAsync ();
LogDeletedFileInfo (path);
});
}
void LogDeletedFileInfo (string path)
{
string fileName = Path.GetFileName (path);
string directory = Path.GetDirectoryName (path);
if (String.IsNullOrEmpty (directory)) {
LogDeletedFile (fileName);
} else {
LogDeletedFileFromDirectory (fileName, directory);
}
}
protected virtual void LogDeletedFile (string fileName)
{
DebugLogFormat ("Removed file '{0}'.", fileName);
}
protected virtual void LogDeletedFileFromDirectory (string fileName, string directory)
{
DebugLogFormat ("Removed file '{0}' from folder '{1}'.", fileName, directory);
}
public void RemoveImport (string targetFullPath)
{
//GuiSyncDispatch (async () => {
// string relativeTargetPath = GetRelativePath (targetFullPath);
// project.RemoveImport (relativeTargetPath);
// RemoveImportWithForwardSlashes (targetFullPath);
// using (var updater = new EnsureNuGetPackageBuildImportsTargetUpdater ()) {
// updater.RemoveImport (relativeTargetPath);
// await project.SaveAsync ();
// }
// packageManagementEvents.OnImportRemoved (project, relativeTargetPath);
//});
}
void RemoveImportWithForwardSlashes (string targetPath)
{
string relativeTargetPath = FileService.AbsoluteToRelativePath (project.BaseDirectory, targetPath);
if (Path.DirectorySeparatorChar == '\\') {
relativeTargetPath = relativeTargetPath.Replace ('\\', '/');
}
project.RemoveImport (relativeTargetPath);
}
public void RemoveReference (string name)
{
//GuiSyncDispatch (async () => {
// ProjectReference referenceProjectItem = FindReference (name);
// if (referenceProjectItem != null) {
// packageManagementEvents.OnReferenceRemoving (referenceProjectItem);
// project.References.Remove (referenceProjectItem);
// await project.SaveAsync ();
// LogRemovedReferenceFromProject (referenceProjectItem);
// }
//});
}
void LogRemovedReferenceFromProject (ProjectReference referenceProjectItem)
{
LogRemovedReferenceFromProject (referenceProjectItem.Reference, ProjectName);
}
protected virtual void LogRemovedReferenceFromProject (string referenceName, string projectName)
{
DebugLogFormat ("Removed reference '{0}' from project '{1}'.", referenceName, projectName);
}
public string ResolvePath (string path)
{
return path;
}
public void SetNuGetProjectContext (INuGetProjectContext nuGetProjectContext)
{
NuGetProjectContext = nuGetProjectContext;
}
T GuiSyncDispatch<T> (Func<T> action)
{
T result = default(T);
guiSyncDispatcher (() => result = action ());
return result;
}
void GuiSyncDispatch (Action action)
{
guiSyncDispatcher (() => action ());
}
static Task GuiSyncDispatchWithException (Func<Task> func)
{
if (Runtime.IsMainThread)
throw new InvalidOperationException ("GuiSyncDispatch called from GUI thread");
return Runtime.RunInMainThread (func);
}
public static void DefaultGuiSyncDispatcher (Action action)
{
Runtime.RunInMainThread (action).Wait ();
}
void GuiSyncDispatch (Func<Task> func)
{
guiSyncDispatcherFunc (func).Wait ();
}
}
}
<file_sep>// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using NuGet.Protocol.Core.Types;
using NuGet.Protocol.Core.v2;
using NuGet.Versioning;
using MonoDevelop.Core;
namespace NuGet.Protocol.VisualStudio
{
public class PackageSearchResourceLocal : PackageSearchResource
{
private IPackageRepository V2Client { get; }
public PackageSearchResourceLocal(V2Resource resource)
{
V2Client = resource.V2Client;
}
public PackageSearchResourceLocal(IPackageRepository repo)
{
V2Client = repo;
}
public async override Task<IEnumerable<IPackageSearchMetadata>> SearchAsync(string searchTerm, SearchFilter filters, int skip, int take, Logging.ILogger log, CancellationToken cancellationToken)
{
return await Task.Run(() =>
{
// Check if source is available.
if (!IsHttpSource(V2Client.Source) && !IsLocalOrUNC(V2Client.Source))
{
throw new InvalidOperationException(
GettextCatalog.GetString ("Source not found '{0}'.", V2Client.Source));
}
var query = V2Client.Search(
searchTerm,
filters.SupportedFrameworks,
filters.IncludePrerelease);
// V2 sometimes requires that we also use an OData filter for
// latest /latest prerelease version
if (filters.IncludePrerelease)
{
query = query.Where(p => p.IsAbsoluteLatestVersion);
}
else
{
query = query.Where(p => p.IsLatestVersion);
}
query = query
.OrderByDescending(p => p.DownloadCount)
.ThenBy(p => p.Id);
// Some V2 sources, e.g. NuGet.Server, local repository, the result contains all
// versions of each package. So we need to group the result by Id.
var collapsedQuery = query.AsEnumerable().AsCollapsed();
// execute the query
var packages = collapsedQuery
.Skip(skip)
.Take(take)
.ToArray();
return packages
.Select(package => CreatePackageSearchResult(package, filters, cancellationToken))
.ToArray();
});
}
private IPackageSearchMetadata CreatePackageSearchResult(IPackage package, SearchFilter filter, CancellationToken cancellationToken)
{
var metadata = new PackageSearchMetadata(package);
return metadata
.WithVersions(() => GetVersions(package, filter, CancellationToken.None));
}
public IEnumerable<VersionInfo> GetVersions(IPackage package, SearchFilter filter, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
// apply the filters to the version list returned
var packages = V2Client.FindPackagesById(package.Id)
.Where(p => filter.IncludeDelisted || !p.Published.HasValue || p.Published.Value.Year > 1901)
.Where(v => filter.IncludePrerelease || string.IsNullOrEmpty(v.Version.SpecialVersion))
.ToArray();
IEnumerable<VersionInfo> versions = packages
.Select(p => new VersionInfo(V2Utilities.SafeToNuGetVer(p.Version), p.DownloadCount))
.OrderByDescending(v => v.Version, VersionComparer.VersionRelease);
var packageVersion = V2Utilities.SafeToNuGetVer(package.Version);
if (!versions.Any(v => v.Version == packageVersion))
{
versions = versions.Concat(
new[] { new VersionInfo(packageVersion, package.DownloadCount) });
}
return versions;
}
private static bool IsHttpSource(string source)
{
if (string.IsNullOrEmpty(source))
{
return false;
}
Uri uri;
if (Uri.TryCreate(source, UriKind.Absolute, out uri))
{
return (uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps);
}
else
{
return false;
}
}
private static bool IsLocalOrUNC(string currentSource)
{
Uri currentURI;
if (Uri.TryCreate(currentSource, UriKind.RelativeOrAbsolute, out currentURI))
{
if (currentURI.IsFile || currentURI.IsUnc)
{
if (Directory.Exists(currentSource))
{
return true;
}
}
}
return false;
}
}
}<file_sep>//
// SolutionPaketDependenciesFolderNode.cs
//
// Author:
// <NAME> <<EMAIL>>
//
// Copyright (c) 2015 <NAME>
//
// 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.
//
using System.Collections.Generic;
using System.Linq;
using MonoDevelop.Core;
using MonoDevelop.Ide.Gui;
using MonoDevelop.Projects;
using MonoDevelop.Ide.Tasks;
using Paket;
namespace MonoDevelop.Paket.NodeBuilders
{
public class SolutionPaketDependenciesFolderNode
{
readonly Solution solution;
SolutionPackageRequirements packageRequirements;
public SolutionPaketDependenciesFolderNode (Solution solution)
{
this.solution = solution;
}
internal Solution Solution {
get { return solution; }
}
public IconId Icon {
get { return Stock.OpenReferenceFolder; }
}
public IconId ClosedIcon {
get { return Stock.ClosedReferenceFolder; }
}
public string GetLabel ()
{
return GettextCatalog.GetString ("Paket Dependencies") + GetUpdatedCountLabel ();
}
public TaskSeverity? StatusSeverity {
get {
if (PackageRequirements.HasError) {
return TaskSeverity.Error;
}
return null;
}
}
public string GetStatusMessage ()
{
if (PackageRequirements.HasError) {
return PackageRequirements.ErrorMessage;
}
return string.Empty;
}
string GetUpdatedCountLabel ()
{
int count = PaketServices.UpdatedPackagesInSolution.UpdatedPackagesCount;
if (count == 0) {
return string.Empty;
}
return " <span color='grey'>" + GetUpdatedPackagesCountLabel (count) + "</span>";
}
string GetUpdatedPackagesCountLabel (int count)
{
return string.Format ("({0} {1})", count, GetUpdateText (count));
}
string GetUpdateText (int count)
{
if (count > 1) {
return GettextCatalog.GetString ("updates");
}
return GettextCatalog.GetString ("update");
}
public void RefreshPackageRequirements ()
{
packageRequirements = solution.GetPackageRequirements ();
}
public SolutionPackageRequirements PackageRequirements {
get {
if (packageRequirements == null) {
RefreshPackageRequirements ();
}
return packageRequirements;
}
}
public IEnumerable<NuGetPackageDependencyNode> GetPackageDependencies ()
{
return PackageRequirements.PackageRequirements
.Select (packageReference => CreateDependencyNode (packageReference));
}
NuGetPackageDependencyNode CreateDependencyNode (Requirements.PackageRequirement packageReference)
{
var node = new NuGetPackageDependencyNode (solution, packageReference);
node.UpdatedPackage = PaketServices.UpdatedPackagesInSolution.FindUpdatedPackage (node.Id);
return node;
}
public void OpenFile ()
{
solution.OpenPaketDependenciesFile ();
}
public FilePath GetPaketDependenciesFile ()
{
return solution.GetPaketDependenciesFile ();
}
}
}
<file_sep>//
// PaketDependencyFileLineParser.cs
//
// Author:
// <NAME> <<EMAIL>>
//
// Copyright (c) 2015 <NAME>
//
// 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.
//
using System;
using System.Collections.Generic;
using System.Linq;
using MonoDevelop.Ide.Editor;
namespace MonoDevelop.Paket.Completion
{
public class PaketDependencyFileLineParser
{
List<PaketDependencyRulePart> parts;
public PaketDependencyFileLineParseResult Parse (IReadonlyTextDocument document, int offset, int lastOffset)
{
parts = new List<PaketDependencyRulePart> ();
int currentOffset = offset;
while (currentOffset < lastOffset) {
char currentChar = document.GetCharAt (currentOffset);
if (currentChar == ' ') {
currentOffset++;
} else if (currentChar == '"') {
currentOffset = ParseString (document, currentOffset, lastOffset);
} else if (IsCommentCharacter (currentChar) && !parts.Any ()) {
return PaketDependencyFileLineParseResult.CommentLine;
} else {
currentOffset = ParsePart (document, currentOffset, lastOffset);
}
}
return new PaketDependencyFileLineParseResult (parts, lastOffset);
}
bool IsCommentCharacter (char currentChar)
{
return (currentChar == '#') || (currentChar == '/');
}
int ParsePart (IReadonlyTextDocument document, int currentOffset, int lastOffset)
{
return ParsePart (document, currentOffset, lastOffset, ' ');
}
int ParsePart (IReadonlyTextDocument document, int currentOffset, int lastOffset, char delimiter)
{
int index = document.Text.IndexOf (delimiter, currentOffset + 1, lastOffset - currentOffset - 1);
if (index >= 0) {
parts.Add (new PaketDependencyRulePart (document, currentOffset, index));
EnsurePartAddedForSettingsDelimiter ();
return index + 1;
}
parts.Add (new PaketDependencyRulePart (document, currentOffset, lastOffset));
EnsurePartAddedForSettingsDelimiter ();
return lastOffset;
}
int ParseString (IReadonlyTextDocument document, int currentOffset, int lastOffset)
{
return ParsePart (document, currentOffset, lastOffset, '"');
}
void EnsurePartAddedForSettingsDelimiter ()
{
if (parts.Count != 1)
return;
PaketDependencyRulePart keywordPart = parts[0];
int delimiter = keywordPart.Text.IndexOf (':');
if (delimiter > 0) {
parts.Clear ();
parts.AddRange (keywordPart.SplitByDelimiter (delimiter));
}
}
}
}
<file_sep>// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Threading;
using System.Threading.Tasks;
using NuGet.Protocol.Core.Types;
namespace NuGet.PackageManagement.UI
{
/// <summary>
/// Package feed abstraction providing services of package enumeration with search criteria.
/// Supports pagination and background processing.
/// </summary>
internal interface IPackageFeed
{
bool IsMultiSource { get; }
/// <summary>
/// Starts new search.
/// </summary>
/// <param name="searchText">Optional text to search</param>
/// <param name="filter">Combined search filter</param>
/// <param name="cancellationToken">A cancellation token</param>
/// <returns>Search result. Possible outcome</returns>
Task<SearchResult<IPackageSearchMetadata>> SearchAsync(
string searchText, SearchFilter filter, CancellationToken cancellationToken);
/// <summary>
/// Proceeds with loading of next page using the same search criteria.
/// </summary>
/// <param name="continuationToken">Search state as returned with previous search result</param>
/// <param name="cancellationToken">A cancellation token</param>
/// <returns>Search result</returns>
Task<SearchResult<IPackageSearchMetadata>> ContinueSearchAsync(
ContinuationToken continuationToken, CancellationToken cancellationToken);
/// <summary>
/// Retrieves a search result of a background search operation.
/// </summary>
/// <param name="refreshToken">Search state as returned with previous search result</param>
/// <param name="cancellationToken">A cancellation token</param>
/// <returns>Refreshed search result</returns>
Task<SearchResult<IPackageSearchMetadata>> RefreshSearchAsync(
RefreshToken refreshToken, CancellationToken cancellationToken);
}
}
<file_sep>//
// ProgressMonitorStatusMessageFactory.cs
//
// Author:
// <NAME> <<EMAIL>>
//
// Copyright (c) 2015 <NAME>
//
// 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.
//
using MonoDevelop.Core;
using System.Collections.Generic;
namespace MonoDevelop.Paket
{
static class ProgressMonitorStatusMessageFactory
{
public static ProgressMonitorStatusMessage CreateAddNuGetPackageMessage (string packageId)
{
return new ProgressMonitorStatusMessage (
GetString ("Adding {0} ...", packageId),
GetString ("{0} added successfully.", packageId),
GetString ("Could not add {0}.", packageId),
GetString ("{0} added with warnings.", packageId)
);
}
public static ProgressMonitorStatusMessage CreateAddNuGetPackagesMessage (int count)
{
return new ProgressMonitorStatusMessage (
GetString ("Adding {0} packages ...", count),
GetString ("{0} packages added successfully.", count),
GetString ("Could not add packages."),
GetString ("{0} packages added with warnings.", count)
);
}
public static ProgressMonitorStatusMessage CreateAddNuGetPackagesMessage (IList<NuGetPackageToAdd> packagesToAdd)
{
if (packagesToAdd.Count == 1) {
return CreateAddNuGetPackageMessage (packagesToAdd[0].Id);
}
return CreateAddNuGetPackagesMessage (packagesToAdd.Count);
}
public static ProgressMonitorStatusMessage CreateAutoRestoreOnMessage ()
{
return new ProgressMonitorStatusMessage (
GetString ("Enabling automatic paket restore..."),
GetString ("Automatic paket restore enabled successfully."),
GetString ("Could not enable automatic paket restore."),
GetString ("Automatic paket restore enabled with warnings.")
);
}
public static ProgressMonitorStatusMessage CreateAutoRestoreOffMessage ()
{
return new ProgressMonitorStatusMessage (
GetString ("Disabling automatic paket restore..."),
GetString ("Automatic paket restore disabled successfully."),
GetString ("Could not disable automatic paket restore."),
GetString ("Automatic paket restore disabled with warnings.")
);
}
public static ProgressMonitorStatusMessage CreateConvertFromNuGetMessage ()
{
return new ProgressMonitorStatusMessage (
GetString ("Converting from NuGet to Paket..."),
GetString ("Conversion to Paket completed successfully."),
GetString ("Could not convert from NuGet to Paket."),
GetString ("Conversion to Paket completed with warnings.")
);
}
public static ProgressMonitorStatusMessage CreateInitMessage ()
{
return new ProgressMonitorStatusMessage (
GetString ("Creating paket.dependencies file..."),
GetString ("paket.dependencies created successfully."),
GetString ("Could not create paket.dependencies file."),
GetString ("paket.dependencies created with warnings.")
);
}
public static ProgressMonitorStatusMessage CreateInstallMessage ()
{
return new ProgressMonitorStatusMessage (
GetString ("Install paket dependencies..."),
GetString ("Paket dependencies installed successfully."),
GetString ("Could not install paket dependencies."),
GetString ("Paket dependencies installed with warnings.")
);
}
public static ProgressMonitorStatusMessage CreateOutdatedMessage ()
{
return new ProgressMonitorStatusMessage (
GetString ("Checking for outdated paket dependencies..."),
GetString ("Outdated paket dependencies checked successfully."),
GetString ("Could not check for outdated paket dependencies."),
GetString ("Outdated paket dependencies checked with warnings.")
);
}
public static UpdatedPackagesProgressMonitorStatusMessage CreateUpdatedPackagesMessage ()
{
return new UpdatedPackagesProgressMonitorStatusMessage (
GetString ("Checking for updated paket dependencies..."),
GetString ("Updated- paket dependencies checked successfully."),
GetString ("Could not check for updated paket dependencies."),
GetString ("Updated paket dependencies checked with warnings.")
);
}
public static ProgressMonitorStatusMessage CreateRemoveNuGetPackageMessage (string packageId)
{
return new ProgressMonitorStatusMessage (
GetString ("Removing {0} ...", packageId),
GetString ("{0} removed successfully.", packageId),
GetString ("Could not remove {0}.", packageId),
GetString ("{0} removed with warnings.", packageId)
);
}
public static ProgressMonitorStatusMessage CreateUpdateNuGetPackageMessage (string packageId)
{
return new ProgressMonitorStatusMessage (
GetString ("Updating {0} ...", packageId),
GetString ("{0} updated successfully.", packageId),
GetString ("Could not update {0}.", packageId),
GetString ("{0} updated with warnings.", packageId)
);
}
public static ProgressMonitorStatusMessage CreateUpdateMessage ()
{
return new ProgressMonitorStatusMessage (
GetString ("Updating paket dependencies..."),
GetString ("Paket dependencies updated successfully."),
GetString ("Could not update paket dependencies."),
GetString ("Paket dependencies updated with warnings.")
);
}
public static ProgressMonitorStatusMessage CreateRestoreMessage ()
{
return new ProgressMonitorStatusMessage (
GetString ("Restoring paket dependencies..."),
GetString ("Paket dependencies restored successfully."),
GetString ("Could not restore paket dependencies."),
GetString ("Paket dependencies restored with warnings.")
);
}
public static ProgressMonitorStatusMessage CreateSimplifyMessage ()
{
return new ProgressMonitorStatusMessage (
GetString ("Simplifying paket dependencies..."),
GetString ("Paket dependencies simplified successfully."),
GetString ("Could not simplify paket dependencies."),
GetString ("Paket dependencies simplified with warnings.")
);
}
static string GetString (string phrase)
{
return GettextCatalog.GetString (phrase);
}
static string GetString (string phrase, object arg0)
{
return GettextCatalog.GetString (phrase, arg0);
}
}
}
<file_sep>//
// PaketCommandRunner.cs
//
// Author:
// <NAME> <<EMAIL>>
//
// Copyright (c) 2015 <NAME>
//
// 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.
//
using System;
using MonoDevelop.Core;
using MonoDevelop.Core.Execution;
using MonoDevelop.Core.ProgressMonitoring;
namespace MonoDevelop.Paket
{
public class PaketCommandRunner
{
static Action defaultAfterRun = () => { };
public void Run (PaketCommandLine command, ProgressMonitorStatusMessage progressMessage)
{
Run (command, progressMessage, defaultAfterRun);
}
public void Run (
PaketCommandLine command,
ProgressMonitorStatusMessage progressMessage,
Action afterRun)
{
AggregatedProgressMonitor progressMonitor = CreateProgressMonitor (progressMessage);
Run (command, progressMessage, progressMonitor, afterRun);
}
public void Run (
PaketCommandLine command,
ProgressMonitorStatusMessage progressMessage,
AggregatedProgressMonitor progressMonitor)
{
Run (command, progressMessage, progressMonitor, defaultAfterRun);
}
public void Run (
PaketCommandLine command,
ProgressMonitorStatusMessage progressMessage,
AggregatedProgressMonitor progressMonitor,
Action afterRun)
{
try {
Run (command, progressMonitor, progressMessage, afterRun);
} catch (Exception ex) {
LoggingService.LogError ("Error running paket command", ex);
progressMonitor.Log.WriteLine (ex.Message);
progressMonitor.ReportError (progressMessage.Error, null);
PaketConsolePad.Show (progressMonitor);
progressMonitor.Dispose ();
}
}
AggregatedProgressMonitor CreateProgressMonitor (ProgressMonitorStatusMessage progressMessage)
{
var factory = new ProgressMonitorFactory ();
return (AggregatedProgressMonitor)factory.CreateProgressMonitor (progressMessage.Status);
}
void Run (
PaketCommandLine commandLine,
AggregatedProgressMonitor progressMonitor,
ProgressMonitorStatusMessage progressMessage,
Action afterRun)
{
progressMonitor.Log.WriteLine (commandLine);
var outputProgressMonitor = progressMonitor.LeaderMonitor as OutputProgressMonitor;
var operationConsole = new OperationConsoleWrapper (outputProgressMonitor.Console);
operationConsole.DisposeWrappedOperationConsole = true;
Runtime.ProcessService.StartConsoleProcess (
commandLine.Command,
commandLine.Arguments,
commandLine.WorkingDirectory,
operationConsole,
null,
(sender, e) => {
using (progressMonitor) {
OnCommandCompleted ((ProcessAsyncOperation)sender, operationConsole, progressMonitor, progressMessage);
afterRun ();
}
}
);
}
void OnCommandCompleted (
ProcessAsyncOperation operation,
OperationConsoleWrapper operationConsole,
AggregatedProgressMonitor progressMonitor,
ProgressMonitorStatusMessage progressMessage)
{
ReportOutcome (operation, operationConsole, progressMonitor, progressMessage);
}
void ReportOutcome (
ProcessAsyncOperation operation,
OperationConsoleWrapper operationConsole,
AggregatedProgressMonitor progressMonitor,
ProgressMonitorStatusMessage progressMessage)
{
if (!operation.Task.IsFaulted && operation.ExitCode == 0 && !operationConsole.HasWrittenErrors) {
progressMonitor.ReportSuccess (progressMessage.Success);
} else {
progressMonitor.ReportError (progressMessage.Error, null);
PaketConsolePad.Show (progressMonitor);
}
}
}
}
<file_sep>//
// ProjectPaketReferencesFolderNode.cs
//
// Author:
// <NAME> <<EMAIL>>
//
// Copyright (c) 2015 <NAME>
//
// 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.
//
using System.Collections.Generic;
using System.Linq;
using MonoDevelop.Core;
using MonoDevelop.Projects;
using MonoDevelop.Ide.Gui;
using MonoDevelop.Ide.Tasks;
namespace MonoDevelop.Paket.NodeBuilders
{
public class ProjectPaketReferencesFolderNode
{
readonly DotNetProject project;
ProjectPackageInstallSettings installSettings;
public ProjectPaketReferencesFolderNode (DotNetProject project)
{
this.project = project;
}
internal DotNetProject Project {
get { return project; }
}
public IconId Icon {
get { return Stock.OpenReferenceFolder; }
}
public IconId ClosedIcon {
get { return Stock.ClosedReferenceFolder; }
}
public string GetLabel ()
{
return GettextCatalog.GetString ("Paket References");
}
public TaskSeverity? StatusSeverity {
get {
if (InstallSettings.HasError) {
return TaskSeverity.Error;
}
return null;
}
}
public string GetStatusMessage ()
{
if (InstallSettings.HasError) {
return InstallSettings.ErrorMessage;
}
return string.Empty;
}
public void RefreshPackageReferences ()
{
installSettings = project.GetPackageInstallSettings ();
}
public ProjectPackageInstallSettings InstallSettings {
get {
if (installSettings == null) {
RefreshPackageReferences ();
}
return installSettings;
}
}
public IEnumerable<NuGetPackageReferenceNode> GetPackageReferences ()
{
return InstallSettings.InstallSettings
.Select (installSettings => new NuGetPackageReferenceNode (project, installSettings));
}
public void OpenFile ()
{
project.OpenPaketReferencesFile ();
}
}
}
<file_sep>//
// PaketInitSearchCommand.cs
//
// Author:
// <NAME> <<EMAIL>>
//
// Copyright (c) 2015 <NAME>
//
// 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.
//
using System;
using MonoDevelop.Core;
using MonoDevelop.Projects;
namespace MonoDevelop.Paket.Commands
{
public abstract class PaketSearchCommand
{
protected PaketSearchCommand (string name)
{
Name = name;
}
public string Name { get; private set; }
public virtual string GetMarkup ()
{
return string.Format ("paket {0}", Name);
}
public virtual string GetDescriptionMarkup ()
{
return null;
}
public abstract void Run ();
public virtual bool IsMatch (PaketSearchCommandQuery query)
{
if (String.IsNullOrEmpty (query.CommandType))
return true;
return Name.StartsWith (query.CommandType, StringComparison.OrdinalIgnoreCase);
}
protected void NotifyAllPaketAndProjectFilesChangedInSolution ()
{
PaketServices.FileChangedNotifier.NotifyAllPaketAndProjectFilesChangedInSolution ();
}
protected void NotifyPaketFilesChanged (Project project)
{
FileService.NotifyFileChanged (project.FileName);
PaketServices.FileChangedNotifier.NotifyPaketReferencesFileChanged (project);
}
protected void NotifyAllProjectFilesChangedInSolution ()
{
PaketServices.FileChangedNotifier.NotifyAllProjectFilesChangedInSolution ();
}
}
}
<file_sep>//
// RecentNuGetPackagesRepository.cs
//
// Author:
// <NAME> <<EMAIL>>
//
// Copyright (c) 2016 Xamarin Inc. (http://xamarin.com)
//
// 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.
using System;
using System.Collections.Generic;
using System.Linq;
namespace MonoDevelop.PackageManagement
{
internal class RecentNuGetPackagesRepository
{
public const int DefaultMaximumPackagesCount = 20;
int maximumPackagesCount = DefaultMaximumPackagesCount;
List<RecentPackage> packages = new List<RecentPackage> ();
public int MaximumPackagesCount {
get { return maximumPackagesCount; }
set { maximumPackagesCount = value; }
}
public IEnumerable<PackageSearchResultViewModel> GetPackages (string source)
{
return packages
.Where (package => String.Equals (package.Source, source, StringComparison.OrdinalIgnoreCase))
.Select (package => package.PackageViewModel);
}
public void AddPackage (PackageSearchResultViewModel viewModel, string source)
{
var package = new RecentPackage (viewModel, source);
viewModel.IsRecentPackage = true;
RemovePackageIfAlreadyAdded (package);
AddPackageAtBeginning (package);
RemoveLastPackageIfCurrentPackageCountExceedsMaximum ();
}
void RemovePackageIfAlreadyAdded (RecentPackage package)
{
int index = FindPackage (package);
if (index >= 0) {
packages.RemoveAt (index);
}
}
int FindPackage (RecentPackage package)
{
return packages.FindIndex (p => IsMatch (p, package));
}
bool IsMatch (RecentPackage x, RecentPackage y)
{
return PackageSearchResultViewModelComparer.Instance.Equals (x.PackageViewModel, y.PackageViewModel);
}
void AddPackageAtBeginning (RecentPackage package)
{
package.PackageViewModel.Parent = null;
packages.Insert (0, package);
}
void RemoveLastPackageIfCurrentPackageCountExceedsMaximum()
{
if (packages.Count > maximumPackagesCount) {
RemoveLastPackage ();
}
}
void RemoveLastPackage ()
{
packages.RemoveAt (packages.Count - 1);
}
class RecentPackage
{
public RecentPackage (PackageSearchResultViewModel viewModel, string source)
{
PackageViewModel = viewModel;
Source = source;
}
public PackageSearchResultViewModel PackageViewModel { get; set; }
public string Source { get; set; }
}
}
}
<file_sep>// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using NuGet.Frameworks;
using NuGet.ProjectManagement;
using NuGet.Protocol.Core.Types;
namespace NuGet.PackageManagement.UI
{
internal class PackageLoadContext
{
//private readonly Task<PackageCollection> _installedPackagesTask;
public IEnumerable<SourceRepository> SourceRepositories { get; private set; }
public NuGetPackageManager PackageManager { get; private set; }
public NuGetProject[] Projects { get; private set; }
// Indicates whether the loader is created by solution package manager.
public bool IsSolution { get; private set; }
//public IEnumerable<IVsPackageManagerProvider> PackageManagerProviders { get; private set; }
//public PackageSearchMetadataCache CachedPackages { get; set; }
public PackageLoadContext(
IEnumerable<SourceRepository> sourceRepositories,
bool isSolution,
NuGetProject project)
{
SourceRepositories = sourceRepositories;
IsSolution = isSolution;
//PackageManager = uiContext.PackageManager;
if (project != null)
Projects = new [] { project };
else
Projects = new NuGetProject[0];
//PackageManagerProviders = uiContext.PackageManagerProviders;
//_installedPackagesTask = PackageCollection.FromProjectsAsync(Projects, CancellationToken.None);
}
//public Task<PackageCollection> GetInstalledPackagesAsync() =>_installedPackagesTask;
// Returns the list of frameworks that we need to pass to the server during search
public IEnumerable<string> GetSupportedFrameworks()
{
var frameworks = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (var project in Projects)
{
NuGetFramework framework;
if (project.TryGetMetadata(NuGetProjectMetadataKeys.TargetFramework,
out framework))
{
if (framework != null
&& framework.IsAny)
{
// One of the project's target framework is AnyFramework. In this case,
// we don't need to pass the framework filter to the server.
return Enumerable.Empty<string>();
}
if (framework != null
&& framework.IsSpecificFramework)
{
frameworks.Add(framework.DotNetFrameworkName);
}
}
else
{
// we also need to process SupportedFrameworks
IEnumerable<NuGetFramework> supportedFrameworks;
if (project.TryGetMetadata(
NuGetProjectMetadataKeys.SupportedFrameworks,
out supportedFrameworks))
{
foreach (var f in supportedFrameworks)
{
if (f.IsAny)
{
return Enumerable.Empty<string>();
}
frameworks.Add(f.DotNetFrameworkName);
}
}
}
}
return frameworks;
}
}
}
<file_sep># Contributing
Thank you for taking the time to contribute to this project.
# License
The MonoDevelop Paket addin is MIT licensed. By contributing to the project you agree to license your contributions by the same license.<file_sep>//
// DotNetProjectProxy.cs
//
// Author:
// <NAME> <<EMAIL>>
//
// Copyright (c) 2014 Xamarin Inc. (http://xamarin.com)
//
// 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.
using System;
using MonoDevelop.Core.Assemblies;
using MonoDevelop.Projects;
namespace MonoDevelop.PackageManagement
{
internal class DotNetProjectProxy : ProjectProxy, IDotNetProject
{
DotNetProject project;
EventHandler<ProjectModifiedEventArgs> projectModifiedHandler;
EventHandler projectSavedHandler;
public DotNetProjectProxy (DotNetProject project)
: base (project)
{
this.project = project;
}
public DotNetProject DotNetProject {
get { return project; }
}
public TargetFrameworkMoniker TargetFrameworkMoniker {
get { return project.TargetFramework.Id; }
}
public string DefaultNamespace {
get { return project.DefaultNamespace; }
}
public ProjectReferenceCollection References {
get { return project.References; }
}
public ProjectFileCollection Files {
get { return project.Files; }
}
public void AddFile (ProjectFile projectFile)
{
project.AddFile (projectFile);
}
public string GetDefaultBuildAction (string fileName)
{
return project.GetDefaultBuildAction (fileName);
}
public bool IsFileInProject (string fileName)
{
return project.IsFileInProject (fileName);
}
public void AddImportIfMissing (string name, string condition)
{
project.AddImportIfMissing (name, condition);
}
public void RemoveImport (string name)
{
project.RemoveImport (name);
}
public event EventHandler<ProjectModifiedEventArgs> Modified {
add {
if (projectModifiedHandler == null) {
project.Modified += ProjectModified;
}
projectModifiedHandler += value;
}
remove {
projectModifiedHandler -= value;
if (projectModifiedHandler == null) {
project.Modified -= ProjectModified;
}
}
}
void ProjectModified (object sender, SolutionItemModifiedEventArgs e)
{
foreach (ProjectModifiedEventArgs eventArgs in ProjectModifiedEventArgs.Create (e)) {
projectModifiedHandler (this, eventArgs);
}
}
public event EventHandler Saved {
add {
if (projectSavedHandler == null) {
project.Saved += ProjectSaved;
}
projectSavedHandler += value;
}
remove {
projectSavedHandler -= value;
if (projectSavedHandler == null) {
project.Saved -= ProjectSaved;
}
}
}
void ProjectSaved (object sender, SolutionItemEventArgs e)
{
projectSavedHandler (this, new EventArgs ());
}
public bool Equals (IDotNetProject project)
{
return DotNetProject == project.DotNetProject;
}
public void RefreshProjectBuilder ()
{
DotNetProject.RefreshProjectBuilder ();
}
public void DisposeProjectBuilder ()
{
DotNetProject.ReloadProjectBuilder ();
}
public void RefreshReferenceStatus ()
{
DotNetProject.RefreshReferenceStatus ();
}
}
}
<file_sep>// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Threading;
using System.Threading.Tasks;
using NuGet.Protocol.Core.Types;
using NuGet.Protocol.Core.v2;
namespace NuGet.Protocol.VisualStudio
{
public class PackageMetadataResourceLocalProvider : V2ResourceProvider
{
public PackageMetadataResourceLocalProvider()
: base(typeof(PackageMetadataResource),
nameof(PackageMetadataResourceLocalProvider),
NuGetResourceProviderPositions.Last)
{
}
public override async Task<Tuple<bool, INuGetResource>> TryCreate(SourceRepository source, CancellationToken token)
{
PackageMetadataResourceLocal resource = null;
if (FeedTypeUtility.GetFeedType(source.PackageSource) == FeedType.FileSystem)
{
var v2repo = await GetRepository(source, token);
if (v2repo != null)
{
resource = new PackageMetadataResourceLocal(v2repo);
}
}
return new Tuple<bool, INuGetResource>(resource != null, resource);
}
}
}<file_sep>//
// ViewModelBase.cs
//
// Author:
// <NAME> <<EMAIL>>
//
// Copyright (C) 2013 <NAME>
//
// 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.
//
using System;
using System.ComponentModel;
using System.Linq.Expressions;
namespace MonoDevelop.PackageManagement
{
internal abstract class ViewModelBase<TModel> : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public string PropertyChangedFor<TProperty>(Expression<Func<TModel, TProperty>> expression)
{
MemberExpression memberExpression = expression.Body as MemberExpression;
return PropertyChangedFor(memberExpression);
}
string PropertyChangedFor(MemberExpression memberExpression)
{
if (memberExpression != null) {
return memberExpression.Member.Name;
}
return String.Empty;
}
protected void OnPropertyChanged<TProperty>(Expression<Func<TModel, TProperty>> expression)
{
string propertyName = PropertyChangedFor(expression);
OnPropertyChanged(propertyName);
}
protected void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null) {
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
<file_sep>//
// PaketCompletionTextEditorExtension.cs
//
// Author:
// <NAME> <<EMAIL>>
//
// Copyright (c) 2015 <NAME>
//
// 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.
//
using System;
using MonoDevelop.Ide.CodeCompletion;
using MonoDevelop.Ide.Editor;
using MonoDevelop.Ide.Editor.Extension;
using System.Threading;
using System.Threading.Tasks;
namespace MonoDevelop.Paket.Completion
{
[Obsolete]
public class PaketCompletionTextEditorExtension : CompletionTextEditorExtension
{
public override bool IsValidInContext (DocumentContext context)
{
return context is PaketDocumentContext;
}
PaketDependencyFileLineParser parser = new PaketDependencyFileLineParser ();
public override Task<ICompletionDataList> HandleCodeCompletionAsync (CodeCompletionContext completionContext, CompletionTriggerInfo triggerInfo, CancellationToken token)
{
if (triggerInfo.CompletionTriggerReason == CompletionTriggerReason.CompletionCommand) {
return HandleCodeCompletionAsync (completionContext, 0);
}
return HandleCodeCompletionAsync (completionContext, 1);
}
Task<ICompletionDataList> HandleCodeCompletionAsync (CodeCompletionContext completionContext, int triggerWordLength)
{
return Task.FromResult (GetCompletionItems (completionContext, triggerWordLength));
}
ICompletionDataList GetCompletionItems (CodeCompletionContext completionContext, int triggerWordLength)
{
PaketCompletionContext context = GetCompletionContext (completionContext, triggerWordLength);
if (context.CompletionType == PaketCompletionType.Keyword) {
var provider = new PaketKeywordCompletionItemProvider();
return provider.GenerateCompletionItems (triggerWordLength);
} else if (context.CompletionType == PaketCompletionType.NuGetPackageSource) {
var provider = new NuGetPackageSourceCompletionItemProvider();
return provider.GenerateCompletionItems (Editor.FileName);
} else if (context.CompletionType == PaketCompletionType.KeywordValue) {
var provider = new PaketKeywordValueCompletionItemProvider();
return provider.GenerateCompletionItems (context.Keyword, context.TriggerWordLength);
} else if (context.CompletionType == PaketCompletionType.NuGetPackage) {
var provider = new LocalNuGetPackageCacheCompletionItemProvider ();
return provider.GenerateCompletionItems ();
}
return null;
}
PaketCompletionContext GetCompletionContext (CodeCompletionContext completionContext, int triggerWordLength)
{
PaketDependencyFileLineParseResult result = ParseLine (completionContext);
if (result == null)
return PaketCompletionContext.None;
if (result.IsComment)
return PaketCompletionContext.None;
if (result.IsCurrentItemFirstKeywordValue) {
if (result.IsSourceRule ()) {
return new PaketCompletionContext {
CompletionType = PaketCompletionType.NuGetPackageSource
};
} else if (result.IsNuGetRule ()) {
return new PaketCompletionContext {
CompletionType = PaketCompletionType.NuGetPackage
};
} else {
var paketContext = CreatePaketCompletionContext (completionContext, result, PaketCompletionType.KeywordValue);
if (result.TotalItems < result.CurrentItem) {
paketContext.TriggerWordLength = 0;
} else {
paketContext.TriggerWordLength = triggerWordLength;
}
return paketContext;
}
} else if (result.CurrentItem > 1) {
return PaketCompletionContext.None;
}
return CreatePaketCompletionContext (completionContext, result, PaketCompletionType.Keyword);
}
PaketCompletionContext CreatePaketCompletionContext (
CodeCompletionContext completionContext,
PaketDependencyFileLineParseResult result,
PaketCompletionType completionType)
{
return new PaketCompletionContext {
CompletionType = completionType,
Keyword = result.RuleName
};
}
PaketDependencyFileLineParseResult ParseLine (CodeCompletionContext completionContext)
{
IDocumentLine line = Editor.GetLineByOffset (completionContext.TriggerOffset);
if (line == null)
return null;
return parser.Parse (Editor.CreateDocumentSnapshot (), line.Offset, completionContext.TriggerOffset);
}
}
}
<file_sep>//
// NuGetPackageDependencyNodeDescriptor.cs
//
// Author:
// <NAME> <<EMAIL>>
//
// Copyright (c) 2015 <NAME>
//
// 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.
//
using System.Linq;
using MonoDevelop.Core;
using MonoDevelop.DesignerSupport;
using Paket;
namespace MonoDevelop.Paket.NodeBuilders
{
public class NuGetPackageDependencyNodeDescriptor : CustomDescriptor
{
readonly NuGetPackageDependencyNode packageDependencyNode;
readonly Requirements.PackageRequirement packageRequirement;
// string frameworkRestrictions;
public NuGetPackageDependencyNodeDescriptor (NuGetPackageDependencyNode packageDependencyNode)
{
this.packageDependencyNode = packageDependencyNode;
packageRequirement = packageDependencyNode.PackageRequirement;
}
[LocalizedCategory ("Package")]
[LocalizedDisplayName ("Id")]
[LocalizedDescription ("Package Id.")]
public string Id {
get { return packageDependencyNode.Id; }
}
[LocalizedCategory ("Package")]
[LocalizedDisplayName ("Version")]
[LocalizedDescription ("Version.")]
public string Version {
get {
if (packageRequirement.VersionRequirement != null)
return packageRequirement.VersionRequirement.ToString ();
return string.Empty;
}
}
[LocalizedCategory ("Package")]
[LocalizedDisplayName ("Copy Local")]
[LocalizedDescription ("Copy Local.")]
public string CopyLocal {
get {
if (packageRequirement.Settings.ImportTargets != null)
return packageRequirement.Settings.CopyLocal.Value.ToString ();
return string.Empty;
}
}
[LocalizedCategory ("Package")]
[LocalizedDisplayName ("Import Targets")]
[LocalizedDescription ("Import targets.")]
public string ImportTargets {
get {
if (packageRequirement.Settings.ImportTargets != null)
return packageRequirement.Settings.ImportTargets.Value.ToString ();
return string.Empty;
}
}
[LocalizedCategory ("Package")]
[LocalizedDisplayName ("Omit Content")]
[LocalizedDescription ("Omit content.")]
public string OmitContent {
get {
if (packageRequirement.Settings.OmitContent != null)
return packageRequirement.Settings.OmitContent.Value.ToString ();
return string.Empty;
}
}
// [LocalizedCategory ("Package")]
// [LocalizedDisplayName ("Frameworks")]
// [LocalizedDescription ("Framework restrictions.")]
// public string Frameworks {
// get {
// if (frameworkRestrictions == null) {
// frameworkRestrictions = GetFrameworkRestrictions ();
// }
// return frameworkRestrictions;
// }
// }
//
// string GetFrameworkRestrictions ()
// {
// if (!packageRequirement.Settings.FrameworkRestrictions.Any ()) {
// return string.Empty;
// }
//
// return string.Join (", ", packageRequirement.Settings.FrameworkRestrictions);
// }
}
}
<file_sep># Paket Support for MonoDevelop and Xamarin Studio
Provides [Paket](http://fsprojects.github.io/Paket/) support for MonoDevelop and Xamarin Studio.
For more details see the [Paket Support in Xamarin Studio blog post](http://lastexitcode.com/blog/2015/06/09/PaketSupportInXamarinStudio/)
## Build Status
Mono | .NET
---- | ----
[](https://travis-ci.org/mrward/monodevelop-paket-addin) | [](https://ci.appveyor.com/project/mrward/monodevelop-paket-addin)
# Features Overview
* View dependencies and referenced NuGet packages in the Solution window.
* Add, remove, update NuGet packages from the Solution window.
* Install, restore, simplify NuGet packages from the Solution window.
* Check for updated NuGet packages from the Solution window.
* Syntax highlighting for all paket files.
* Code completion whilst editing the paket.dependencies file.
* Integrates with Xamarin Studio's unified search.
* paket.dependencies and paket.template file templates.
# Requirements
* MonoDevelop 7 or Visual Studio for Mac 7
# Installation
## MonoDevelop
The addin is available from the [MonoDevelop addin repository](http://addins.monodevelop.com/). To install the addin:
* Open the **Add-in Manager** dialog.
* Select the **Gallery** tab.
* Select **Xamarin Studio Add-in Repository (Alpha channel)** from the drop down list.
* Expand **IDE extensions**.
* Select **Paket**.
* Click the **Refresh** button if the addin is not visible.
* Click **Install...** to install the addin.

## Visual Studio for Mac
The addin is available from my [MonoDevelop Addins](https://github.com/mrward/monodevelop-addins). To install the addin:
* Open the **Add-in Manager** dialog.
* Select the **Gallery** tab.
* Open the Repository drop down list and select **Manage Repositories**.
* Click the **Add** button.
* Enter the **url** for the Visual Studio for Mac version.
* Click **OK**.
* Expand **IDE extensions**.
* Select **Paket**.
* Click the **Refresh** button if the addin is not visible.
* Click **Install...** to install the addin.
# Features
In the following sections the features are covered in more detail.
## Adding a NuGet Package
To add a NuGet package using Paket, right click the project in the Solution window, and select **Add** - **Add NuGet Packages using Paket**.
The **Add NuGet Packages using Paket** menu is also available from the main Project menu.
## Paket Dependencies Folder
The Paket Dependencies folder is shown in the Solution window if Xamarin Studio finds a paket.dependencies file in the same directory as the solution. The NuGet packages that are in the paket.dependencies file are shown under this folder.

Double clicking the folder will open the paket.dependencies file into the text editor. The Paket Dependencies folder also has a context menu where you can run Paket commands. From the context menu you can Add a NuGet Package as a dependency, install, restore, update, and simplify your dependencies, or check for updates.
To update a single NuGet package you can right click it and select Update. To remove the NuGet package as a dependency you can right click it and select Remove or press delete.
## Paket References Folder
The Paket References folder is shown in the Solution window if Xamarin Studio finds a paket.references file in the same directory as the project. The NuGet packages that are in the paket.references file are shown under this folder. Double clicking the folder will open the paket.references file into the text editor.

Right clicking the Paket References folder allows you to add a NuGet package to the project. A NuGet package can be removed by right clicking it and selecting Remove or by pressing Delete.
## Code Completion
When editing the paket.dependencies file you will get code completion as you type. You can also bring up the code completion list by pressing Ctrl+Enter.

## Running Paket Commands
Paket commands can be run from the Unified search. If you type in paket you will see some of the Paket commands.

## Syntax Highlighting
Syntax highlighting is available for all paket files - paket.dependencies, paket.references, paket.lock and paket.template.

<file_sep>using Mono.Addins;
[assembly:Addin ("Paket",
Namespace = "MonoDevelop",
Version = "0.6",
Category = "IDE extensions")]
[assembly:AddinName ("Paket")]
[assembly:AddinDescription ("Adds Paket support.")]
[assembly:AddinDependency ("Core", "8.1")]
[assembly:AddinDependency ("Ide", "8.1")]
[assembly:AddinDependency ("SourceEditor2", "8.1")]
[assembly:AddinDependency ("DesignerSupport", "8.1")]<file_sep>// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace NuGet.PackageManagement.UI
{
/// <summary>
/// Contains task execution strategies, such as parallel throttled execution.
/// </summary>
internal static class TaskCombinators
{
public const int MaxDegreeOfParallelism = 16;
public static async Task<IEnumerable<TValue>> ThrottledAsync<TSource, TValue>(
IEnumerable<TSource> sources,
Func<TSource, CancellationToken, Task<TValue>> valueSelector,
CancellationToken cancellationToken)
{
var bag = new ConcurrentBag<TSource>(sources);
var values = new ConcurrentQueue<TValue>();
Func<Task> taskBody = async () =>
{
TSource source;
while (bag.TryTake(out source))
{
var value = await valueSelector(source, cancellationToken);
values.Enqueue(value);
}
};
var tasks = Enumerable
.Repeat(0, MaxDegreeOfParallelism)
.Select(_ => Task.Run(taskBody));
await Task.WhenAll(tasks);
return values;
}
public static IDictionary<string, Task<TValue>> ObserveErrorsAsync<TSource, TValue>(
IEnumerable<TSource> sources,
Func<TSource, string> keySelector,
Func<TSource, CancellationToken, Task<TValue>> valueSelector,
Action<Task, object> observeErrorAction,
CancellationToken cancellationToken)
{
var tasks = sources
.ToDictionary(
s => keySelector(s),
s =>
{
var valueTask = valueSelector(s, cancellationToken);
var ignored = valueTask.ContinueWith(
observeErrorAction,
s,
cancellationToken,
TaskContinuationOptions.OnlyOnFaulted,
TaskScheduler.Current);
return valueTask;
});
return tasks;
}
}
}
<file_sep>//
// BuildIntegratedProjectSystem.cs
//
// Author:
// <NAME> <<EMAIL>>
//
// based on NuGet.Clients
// src/NuGet.Clients/PackageManagement.VisualStudio/ProjectSystems/BuildIntegratedProjectSystem.cs
//
// Copyright (c) 2016 Xamarin Inc.
// Copyright (c) .NET Foundation. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using MonoDevelop.Core;
using MonoDevelop.Projects;
using NuGet.Common;
using NuGet.Configuration;
using NuGet.PackageManagement;
using NuGet.Packaging;
using NuGet.Packaging.Core;
using NuGet.ProjectManagement;
using NuGet.ProjectManagement.Projects;
using NuGet.ProjectModel;
namespace MonoDevelop.PackageManagement
{
internal class BuildIntegratedProjectSystem : BuildIntegratedNuGetProject, IBuildIntegratedNuGetProject
{
IDotNetProject dotNetProject;
// PackageManagementEvents packageManagementEvents;
VersionFolderPathResolver packagePathResolver;
public BuildIntegratedProjectSystem (
string jsonConfigPath,
string msbuildProjectFilePath,
DotNetProject dotNetProject,
IMSBuildNuGetProjectSystem msbuildProjectSystem,
string uniqueName,
ISettings settings)
: base (jsonConfigPath, msbuildProjectFilePath, msbuildProjectSystem)
{
this.dotNetProject = new DotNetProjectProxy (dotNetProject);
// packageManagementEvents = new PackageManagementEvents ();
string path = SettingsUtility.GetGlobalPackagesFolder (settings);
packagePathResolver = new VersionFolderPathResolver (path, normalizePackageId: false);
}
public override Task<bool> ExecuteInitScriptAsync (PackageIdentity identity, string packageInstallPath, INuGetProjectContext projectContext, bool throwOnFailure)
{
// Not supported. This gets called for every NuGet package
// even if they do not have an init.ps1 so do not report this.
return Task.FromResult (false);
}
public override Task PostProcessAsync (INuGetProjectContext nuGetProjectContext, System.Threading.CancellationToken token)
{
// packageManagementEvents.OnFileChanged (JsonConfigPath);
return base.PostProcessAsync (nuGetProjectContext, token);
}
public void OnAfterExecuteActions (IEnumerable<NuGetProjectAction> actions)
{
ProcessActions (actions, OnPackageInstalled, OnPackageUninstalled);
}
public void OnBeforeUninstall (IEnumerable<NuGetProjectAction> actions)
{
ProcessActions (actions, identity => {}, OnPackageUninstalling);
}
void ProcessActions (
IEnumerable<NuGetProjectAction> actions,
Action<PackageIdentity> installAction,
Action<PackageIdentity> uninstallAction)
{
foreach (var action in actions) {
if (action.NuGetProjectActionType == NuGetProjectActionType.Install) {
installAction (action.PackageIdentity);
} else if (action.NuGetProjectActionType == NuGetProjectActionType.Uninstall) {
uninstallAction (action.PackageIdentity);
}
}
}
void OnPackageInstalled (PackageIdentity identity)
{
var eventArgs = CreatePackageEventArgs (identity);
// packageManagementEvents.OnPackageInstalled (dotNetProject, eventArgs);
}
PackageEventArgs CreatePackageEventArgs (PackageIdentity identity)
{
string installPath = packagePathResolver.GetInstallPath (identity.Id, identity.Version);
return new PackageEventArgs (this, identity, installPath);
}
void OnPackageUninstalling (PackageIdentity identity)
{
var eventArgs = CreatePackageEventArgs (identity);
// packageManagementEvents.OnPackageUninstalling (dotNetProject, eventArgs);
}
void OnPackageUninstalled (PackageIdentity identity)
{
var eventArgs = CreatePackageEventArgs (identity);
// packageManagementEvents.OnPackageUninstalled (dotNetProject, eventArgs);
}
public override Task<IReadOnlyList<ExternalProjectReference>> GetProjectReferenceClosureAsync (ExternalProjectReferenceContext context)
{
return Runtime.RunInMainThread (() => {
return GetExternalProjectReferenceClosureAsync (context);
});
}
/// <summary>
/// Returns the closure of all project to project references below this project.
/// The code is a port of src/NuGet.Clients/PackageManagement.VisualStudio/ProjectSystems/BuildIntegratedProjectSystem.cs
/// </summary>
Task<IReadOnlyList<ExternalProjectReference>> GetExternalProjectReferenceClosureAsync (ExternalProjectReferenceContext context)
{
var logger = context.Logger;
var cache = context.Cache;
var results = new HashSet<ExternalProjectReference> ();
// projects to walk - DFS
var toProcess = new Stack<DotNetProjectReference> ();
// keep track of found projects to avoid duplicates
string rootProjectPath = dotNetProject.FileName;
// start with the current project
toProcess.Push (new DotNetProjectReference (dotNetProject.DotNetProject, rootProjectPath));
var uniqueNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
// continue walking all project references until we run out
while (toProcess.Count > 0) {
var reference = toProcess.Pop ();
// Find the path of the current project
string projectFileFullPath = reference.Path;
var project = reference.Project;
if (string.IsNullOrEmpty(projectFileFullPath) || !uniqueNames.Add (projectFileFullPath)) {
// This has already been processed or does not exist
continue;
}
IReadOnlyList<ExternalProjectReference> cacheReferences;
if (cache.TryGetValue (projectFileFullPath, out cacheReferences)) {
// The cached value contains the entire closure, add it to the results and skip
// all child references.
results.UnionWith (cacheReferences);
} else {
// Get direct references
var projectResult = GetDirectProjectReferences (
reference.Project,
projectFileFullPath,
context,
rootProjectPath);
// Add results to the closure
results.UnionWith (projectResult.Processed);
// Continue processing
foreach (var item in projectResult.ToProcess) {
toProcess.Push (item);
}
}
}
// Cache the results for this project and every child project which has not been cached
foreach (var project in results) {
if (!context.Cache.ContainsKey (project.UniqueName)) {
var closure = BuildIntegratedRestoreUtility.GetExternalClosure (project.UniqueName, results);
context.Cache.Add(project.UniqueName, closure.ToList ());
}
}
var result = cache[rootProjectPath];
return Task.FromResult (result);
}
/// <summary>
/// Get only the direct dependencies from a project
/// </summary>
private DirectReferences GetDirectProjectReferences(
DotNetProject project,
string projectFileFullPath,
ExternalProjectReferenceContext context,
string rootProjectPath)
{
var logger = context.Logger;
var cache = context.Cache;
var result = new DirectReferences ();
// Find a project.json in the project
// This checks for files on disk to match how BuildIntegratedProjectSystem checks at creation time.
// NuGet.exe also uses disk paths and not the project file.
var projectName = Path.GetFileNameWithoutExtension (projectFileFullPath);
var projectDirectory = Path.GetDirectoryName (projectFileFullPath);
// Check for projectName.project.json and project.json
string jsonConfigItem =
ProjectJsonPathUtilities.GetProjectConfigPath (
directoryPath: projectDirectory,
projectName: projectName);
var hasProjectJson = true;
// Verify the file exists, otherwise clear it
if (!File.Exists(jsonConfigItem)) {
jsonConfigItem = null;
hasProjectJson = false;
}
// Verify ReferenceOutputAssembly
var excludedProjects = GetExcludedReferences (project);
var childReferences = new HashSet<string> (StringComparer.Ordinal);
var hasMissingReferences = false;
// find all references in the project
foreach (var childReference in project.References) {
try {
if (!childReference.IsValid) {
// Skip missing references and show a warning
hasMissingReferences = true;
continue;
}
// Skip missing references
DotNetProject sourceProject = null;
if (childReference.ReferenceType == ReferenceType.Project) {
sourceProject = childReference.ResolveProject (project.ParentSolution) as DotNetProject;
}
if (sourceProject != null) {
string childName = sourceProject.FileName;
// Skip projects which have ReferenceOutputAssembly=false
if (!string.IsNullOrEmpty (childName)
&& !excludedProjects.Contains (childName, StringComparer.OrdinalIgnoreCase)) {
childReferences.Add (childName);
result.ToProcess.Add (new DotNetProjectReference (sourceProject, childName));
}
} else if (hasProjectJson) {
// SDK references do not have a SourceProject or child references,
// but they can contain project.json files, and should be part of the closure
// SDKs are not projects, only the project.json name is checked here
//var possibleSdkPath = childReference.Path;
//if (!string.IsNullOrEmpty (possibleSdkPath)
// && !possibleSdkPath.EndsWith (".dll", StringComparison.OrdinalIgnoreCase)
// && Directory.Exists(possibleSdkPath)) {
// var possibleProjectJson = Path.Combine (
// possibleSdkPath,
// ProjectJsonPathUtilities.ProjectConfigFileName);
// if (File.Exists (possibleProjectJson)) {
// childReferences.Add (possibleProjectJson);
// // add the sdk to the results here
// result.Processed.Add (new ExternalProjectReference (
// possibleProjectJson,
// childReference.Name,
// possibleProjectJson,
// msbuildProjectPath: null,
// projectReferences: Enumerable.Empty<string> ()));
// }
//}
}
} catch (Exception ex) {
// Exceptions are expected in some scenarios for native projects,
// ignore them and show a warning
hasMissingReferences = true;
logger.LogDebug (ex.Message);
LoggingService.LogError ("Unable to find project closure.", ex);
}
}
if (hasMissingReferences) {
// Log a warning message once per project
// This warning contains only the names of the root project and the project with the
// broken reference. Attempting to display more details on the actual reference
// that has the problem may lead to another exception being thrown.
var warning = GettextCatalog.GetString ("Failed to resolve all project references for '{0}'. The package restore result for '{1}' may be incomplete.",
projectName,
rootProjectPath);
logger.LogWarning (warning);
}
// Only set a package spec project name if a package spec exists
var packageSpecProjectName = jsonConfigItem == null ? null : projectName;
// Add the parent project to the results
result.Processed.Add (new ExternalProjectReference (
projectFileFullPath,
packageSpecProjectName,
jsonConfigItem,
projectFileFullPath,
childReferences));
return result;
}
/// <summary>
/// Get the unique names of all references which have ReferenceOutputAssembly set to false.
/// </summary>
static List<string> GetExcludedReferences (DotNetProject project)
{
var excludedReferences = new List<string> ();
foreach (var reference in project.References) {
// 1. Verify that this is a project reference
// 2. Check that it is valid and resolved
// 3. Follow the reference to the DotNetProject and get the unique name
if (!reference.ReferenceOutputAssembly &&
reference.IsValid &&
reference.ReferenceType == ReferenceType.Project) {
var sourceProject = reference.ResolveProject (project.ParentSolution);
if (sourceProject != null) {
string childPath = sourceProject.FileName;
excludedReferences.Add (childPath);
}
}
}
return excludedReferences;
}
/// <summary>
/// Top level references
/// </summary>
class DirectReferences
{
public HashSet<DotNetProjectReference> ToProcess { get; } = new HashSet<DotNetProjectReference> ();
public HashSet<ExternalProjectReference> Processed { get; } = new HashSet<ExternalProjectReference> ();
}
/// <summary>
/// Holds the full path to a project and the project.
/// </summary>
private class DotNetProjectReference : IEquatable<DotNetProjectReference>, IComparable<DotNetProjectReference>
{
public DotNetProjectReference (DotNetProject project, string path)
{
Project = project;
Path = path;
}
public DotNetProject Project { get; }
public string Path { get; }
public bool Equals (DotNetProjectReference other)
{
return StringComparer.Ordinal.Equals (Path, other.Path);
}
public int CompareTo (DotNetProjectReference other)
{
return StringComparer.Ordinal.Compare (Path, other.Path);
}
public override int GetHashCode ()
{
return StringComparer.Ordinal.GetHashCode (Path);
}
public override bool Equals (object obj)
{
return Equals (obj as DotNetProjectReference);
}
}
}
}
<file_sep>//
// PaketDependencyFileLineParseResult.cs
//
// Author:
// <NAME> <<EMAIL>>
//
// Copyright (c) 2015 <NAME>
//
// 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.
//
using System;
using System.Collections.Generic;
using System.Linq;
namespace MonoDevelop.Paket.Completion
{
public class PaketDependencyFileLineParseResult
{
readonly List<PaketDependencyRulePart> parts;
public PaketDependencyFileLineParseResult (IEnumerable<PaketDependencyRulePart> parts, int triggerOffset)
{
this.parts = parts.ToList ();
CurrentItem = this.parts.Count;
PaketDependencyRulePart lastPart = parts.LastOrDefault ();
if (lastPart != null) {
if (triggerOffset > lastPart.EndOffset) {
CurrentItem++;
}
}
IsCurrentItemFirstKeywordValue = CheckCurrentItemIsFirstKeywordValue ();
}
bool CheckCurrentItemIsFirstKeywordValue ()
{
return (CurrentItem == 2) ||
((CurrentItem == 3) && (parts[1].Text == ":"));
}
public static readonly PaketDependencyFileLineParseResult CommentLine = new PaketDependencyFileLineParseResult {
IsComment = true
};
PaketDependencyFileLineParseResult ()
{
}
public bool IsComment { get; private set; }
public int TotalItems {
get { return parts.Count; }
}
public int CurrentItem { get; private set; }
public string RuleName {
get {
if (parts.Count > 0)
return parts[0].Text;
return string.Empty;
}
}
public bool IsSourceRule ()
{
return string.Equals (RuleName, "source", StringComparison.OrdinalIgnoreCase);
}
public bool IsNuGetRule ()
{
return string.Equals (RuleName, "nuget", StringComparison.OrdinalIgnoreCase);
}
public bool IsCurrentItemFirstKeywordValue { get; private set; }
}
}
<file_sep>//
// PaketNuGetSearchCommand.cs
//
// Author:
// <NAME> <<EMAIL>>
//
// Copyright (c) 2015 <NAME>
//
// 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.
//
using System;
using MonoDevelop.Core;
using MonoDevelop.Projects;
namespace MonoDevelop.Paket.Commands
{
public abstract class PaketNuGetSearchCommand : PaketSearchCommand
{
PaketNuGetSearchCommandQuery query;
protected PaketNuGetSearchCommand (string commandName, string search, Project project = null)
: base (string.Format ("{0} nuget", commandName))
{
query = new PaketNuGetSearchCommandQuery (search);
query.Parse ();
Project = project;
PaketNuGetCommandName = commandName;
SupportsVersion = true;
}
public override void Run ()
{
var commandLine = PaketCommandLine.CreateCommandLine (GenerateCommandLine ());
ProgressMonitorStatusMessage message = GetProgressMessage (GetPackageIdToDisplay ());
PaketServices.CommandRunner.Run (commandLine, message, NotifyPaketFilesChanged);
}
protected abstract ProgressMonitorStatusMessage GetProgressMessage (string packageId);
/// <summary>
/// The 'to', 'from' part of the message shown in the unified search window.
/// (to project foo)
/// (from project foo)
/// </summary>
/// <value>The project name markup start.</value>
protected abstract string ProjectNameMarkupStart { get; }
protected bool SupportsVersion { get; set; }
protected Project Project { get; set; }
string GetPackageIdToDisplay ()
{
if (string.IsNullOrEmpty (query.PackageId))
return "NuGet package";
return query.PackageId;
}
string PaketNuGetCommandName { get; set; }
string GenerateCommandLine ()
{
return string.Format (
"{0} {1}{2}{3}",
PaketNuGetCommandName,
query.PackageId,
GetPackageVersionCommandLineArgument (),
GetProjectCommandLineArgument ());
}
string GetPackageVersionCommandLineArgument ()
{
if (SupportsVersion && query.HasVersion ())
return " --version " + query.PackageVersion;
return string.Empty;
}
string GetProjectCommandLineArgument ()
{
if (Project != null)
return string.Format (" --project \"{0}\"", Project.FileName);
return string.Empty;
}
public override string GetMarkup ()
{
return GettextCatalog.GetString (
"paket {0} <b>{1}</b>{2}",
PaketNuGetCommandName,
GetPackageIdAndVersionMarkup (),
GetProjectNameMarkup ());
}
string GetPackageIdAndVersionMarkup ()
{
return string.Format ("{0} {1}",
GetPackageIdMarkup (),
GetPackageVersionMarkup ())
.TrimEnd ();
}
string GetPackageIdMarkup ()
{
if (query.HasPackageId ())
return query.PackageId;
return "PackageId";
}
string GetPackageVersionMarkup ()
{
if (!SupportsVersion)
return String.Empty;
if (query.HasPackageId ())
return query.PackageVersion;
return "[Version]";
}
string GetProjectNameMarkup ()
{
if (Project != null)
return string.Format (" ({0} project {1})", ProjectNameMarkupStart, Project.Name);
return string.Empty;
}
protected virtual void NotifyPaketFilesChanged ()
{
if (Project != null) {
NotifyPaketFilesChanged (Project);
FileService.NotifyFileChanged (Project.FileName);
}
PaketServices.FileChangedNotifier.NotifyPaketDependenciesFileChanged ();
PaketServices.FileChangedNotifier.NotifyPaketLockFileChanged ();
}
}
}
<file_sep>//
// UpdatedPackagesInSolution.cs
//
// Author:
// <NAME> <<EMAIL>>
//
// Copyright (c) 2015 <NAME>
//
// 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.
//
using System;
using System.Collections.Generic;
using System.Linq;
using MonoDevelop.Ide;
using MonoDevelop.Projects;
namespace MonoDevelop.Paket
{
public class UpdatedPackagesInSolution
{
public UpdatedPackagesInSolution ()
{
IdeApp.Workspace.SolutionUnloaded += SolutionUnloaded;
}
void SolutionUnloaded (object sender, SolutionEventArgs e)
{
Clear ();
}
public void Clear ()
{
updates = new List<NuGetPackageUpdate> ();
}
List<NuGetPackageUpdate> updates = new List<NuGetPackageUpdate> ();
public void RefreshUpdatedPackages (IEnumerable<NuGetPackageUpdate> updates)
{
this.updates = updates.ToList ();
}
public int UpdatedPackagesCount {
get { return updates.Count; }
}
public NuGetPackageUpdate FindUpdatedPackage (string id)
{
return updates.FirstOrDefault (update => update.IsMatch (id));
}
public void Remove (string packageId)
{
updates.RemoveAll (update => update.IsMatch (packageId));
}
}
}
<file_sep>//
// PaketDocumentContext.cs
//
// Author:
// <NAME> <<EMAIL>>
//
// Copyright (c) 2019 Microsoft
//
// 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.
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using MonoDevelop.Core;
using MonoDevelop.Ide.Editor;
using MonoDevelop.Ide.Gui.Documents;
using MonoDevelop.Ide.TypeSystem;
using MonoDevelop.Projects;
namespace MonoDevelop.Paket
{
class PaketDocumentContext : DocumentContext
{
FileDocumentController controller;
public PaketDocumentContext (FileDocumentController controller)
{
this.controller = controller;
}
public override string Name {
get { return controller.DocumentTitle; }
}
public FilePath FileName {
get { return controller.FilePath; }
}
public override Project Project {
get { return controller.Owner as Project; }
}
[Obsolete]
public override Microsoft.CodeAnalysis.Document AnalysisDocument { get; }
[Obsolete]
public override ParsedDocument ParsedDocument { get; }
public override void AttachToProject (Project project)
{
}
public override Microsoft.CodeAnalysis.Options.OptionSet GetOptionSet ()
{
return null;
}
[Obsolete]
public override void ReparseDocument ()
{
}
[Obsolete]
public override Task<ParsedDocument> UpdateParseDocument ()
{
ParsedDocument document = null;
return Task.FromResult (document);
}
public override T GetContent<T> ()
{
return controller.GetContent<T> ();
}
public override IEnumerable<T> GetContents<T> ()
{
return controller.GetContents<T> ();
}
}
}
<file_sep>// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using NuGet.Packaging.Core;
using NuGet.Protocol.Core.Types;
namespace NuGet.PackageManagement.UI
{
/// <summary>
/// Contract for a generalized package metadata provider associated with a package source(s).
/// </summary>
internal interface IPackageMetadataProvider
{
/// <summary>
/// Retrieves a package metadata of a specific version along with list of all available versions
/// </summary>
/// <param name="identity">Desired package id with version</param>
/// <param name="includePrerelease">Filters pre-release versions</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns>Package metadata</returns>
Task<IPackageSearchMetadata> GetPackageMetadataAsync(PackageIdentity identity,
bool includePrerelease, CancellationToken cancellationToken);
/// <summary>
/// Retrieves a package metadata of a highest available version along with list of all available versions
/// </summary>
/// <param name="identity">Desired package identity</param>
/// <param name="includePrerelease">Filters pre-release versions</param>
/// <param name="cancellationToken">A cancellation token</param>
/// <returns>Package metadata</returns>
Task<IPackageSearchMetadata> GetLatestPackageMetadataAsync(PackageIdentity identity,
bool includePrerelease, CancellationToken cancellationToken);
/// <summary>
/// Retrieves a list of metadata objects of all available versions for given package id.
/// </summary>
/// <param name="packageId">Desired package Id</param>
/// <param name="includePrerelease">Filters pre-release versions</param>
/// <param name="includeUnlisted">Filters unlisted versions</param>
/// <param name="cancellationToken">A cancellation token</param>
/// <returns>Collection of packages matching query parameters</returns>
Task<IEnumerable<IPackageSearchMetadata>> GetPackageMetadataListAsync(string packageId,
bool includePrerelease, bool includeUnlisted, CancellationToken cancellationToken);
/// <summary>
/// Retrieves a package metadata of a specific version along with list of all available versions
/// </summary>
/// <param name="identity">Desired package id with version</param>
/// <param name="includePrerelease">Filters pre-release versions</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns>Package metadata</returns>
Task<IPackageSearchMetadata> GetLocalPackageMetadataAsync(PackageIdentity identity,
bool includePrerelease, CancellationToken cancellationToken);
}
}<file_sep>// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections;
using System.Collections.Generic;
namespace NuGet.PackageManagement.UI
{
/// <summary>
/// Feed specific data describing current position to continue search from.
/// It's opaque to external consumer.
/// </summary>
internal class ContinuationToken { }
/// <summary>
/// Feed specific state of current search operation to retrieve search results.
/// Used for polling results of prolonged search. Opaque to external consumer.
/// </summary>
internal class RefreshToken
{
public TimeSpan RetryAfter { get; set; }
}
/// <summary>
/// Generic search result as returned by a feed including actual items and current search
/// state including but not limited to continuation token and refresh token.
/// </summary>
/// <typeparam name="T"></typeparam>
internal class SearchResult<T> : IEnumerable<T>
{
public IReadOnlyList<T> Items { get; set; }
public ContinuationToken NextToken { get; set; }
public RefreshToken RefreshToken { get; set; }
public IEnumerator<T> GetEnumerator() => Items.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => Items.GetEnumerator();
public IDictionary<string, LoadingStatus> SourceSearchStatus { get; set; }
// total number of unmerged items found
public int RawItemsCount { get; set; }
}
/// <summary>
/// Helper class providing shortcuts to create new result instance
/// </summary>
internal static class SearchResult
{
public static SearchResult<T> FromItems<T>(params T[] items) => new SearchResult<T>
{
Items = items,
RawItemsCount = items.Length
};
public static SearchResult<T> FromItems<T>(IReadOnlyList<T> items) => new SearchResult<T>
{
Items = items,
RawItemsCount = items.Count
};
public static SearchResult<T> Empty<T>() => new SearchResult<T>
{
Items = new T[] { },
SourceSearchStatus = new Dictionary<string, LoadingStatus> { }
};
}
}
<file_sep>// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace NuGet.PackageManagement.UI
{
/// <summary>
/// List of possible statuses of items loading operation (search).
/// Utilized by item loader and UI for progress tracking.
/// </summary>
public enum LoadingStatus
{
Unknown, // not initialized
Cancelled, // loading cancelled
ErrorOccurred, // error occured
Loading, // loading is running in background
NoItemsFound, // loading complete, no items found
NoMoreItems, // loading complete, no more items discovered beyond current page
Ready // loading of current page is done, next page is available
}
}
<file_sep>// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using NuGet.Packaging.Core;
using NuGet.ProjectManagement;
using NuGet.ProjectManagement.Projects;
using NuGet.Protocol.Core.Types;
using NuGet.Versioning;
namespace NuGet.PackageManagement.UI
{
/// <summary>
/// The base class of PackageDetailControlModel and PackageSolutionDetailControlModel.
/// When user selects an action, this triggers version list update.
/// </summary>
internal abstract class DetailControlModel : INotifyPropertyChanged
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields")]
protected IEnumerable<NuGetProject> _nugetProjects;
// all versions of the _searchResultPackage
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields")]
protected List<NuGetVersion> _allPackageVersions;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields")]
protected PackageItemListViewModel _searchResultPackage;
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields")]
//protected ItemFilter _filter;
private Dictionary<NuGetVersion, DetailedPackageMetadata> _metadataDict;
protected DetailControlModel(IEnumerable<NuGetProject> nugetProjects)
{
_nugetProjects = nugetProjects;
// _options = new Options();
// Show dependency behavior and file conflict options if any of the projects are non-build integrated
// _options.ShowClassicOptions = nugetProjects.Any(project => !(project is BuildIntegratedNuGetProject));
}
/// <summary>
/// The method is called when the associated DocumentWindow is closed.
/// </summary>
public virtual void CleanUp()
{
}
/// <summary>
/// Returns the list of projects that are selected for the given action
/// </summary>
//public abstract IEnumerable<NuGetProject> GetSelectedProjects(UserAction action);
/// <summary>
/// Sets the package to be displayed in the detail control.
/// </summary>
/// <param name="searchResultPackage">The package to be displayed.</param>
/// <param name="filter">The current filter. This will used to select the default action.</param>
public async virtual Task SetCurrentPackage(
PackageItemListViewModel searchResultPackage)//,
// ItemFilter filter)
{
_searchResultPackage = searchResultPackage;
//_filter = filter;
//OnPropertyChanged(nameof(Id));
//OnPropertyChanged(nameof(IconUrl));
var versions = await searchResultPackage.GetVersionsAsync();
_allPackageVersions = versions.Select(v => v.Version).ToList();
//CreateVersions();
//OnCurrentPackageChanged();
}
/*
protected virtual void OnCurrentPackageChanged()
{
}
public virtual void OnFilterChanged(ItemFilter? previousFilter, ItemFilter currentFilter)
{
_filter = currentFilter;
}
/// <summary>
/// Get all installed packages across all projects (distinct)
/// </summary>
public virtual IEnumerable<PackageIdentity> InstalledPackages
{
get
{
return NuGetUIThreadHelper.JoinableTaskFactory.Run(async delegate
{
var installedPackages = new List<Packaging.PackageReference>();
foreach (var project in _nugetProjects)
{
var projectInstalledPackages = await project.GetInstalledPackagesAsync(CancellationToken.None);
installedPackages.AddRange(projectInstalledPackages);
}
return installedPackages.Select(e => e.PackageIdentity).Distinct(PackageIdentity.Comparer);
});
}
}
/// <summary>
/// Get all installed packages across all projects (distinct)
/// </summary>
public virtual IEnumerable<Packaging.Core.PackageDependency> InstalledPackageDependencies
{
get
{
return NuGetUIThreadHelper.JoinableTaskFactory.Run(async delegate
{
var installedPackages = new HashSet<Packaging.Core.PackageDependency>();
foreach (var project in _nugetProjects)
{
var dependencies = await GetDependencies(project);
installedPackages.UnionWith(dependencies);
}
return installedPackages;
});
}
}
private static async Task<IReadOnlyList<Packaging.Core.PackageDependency>> GetDependencies(NuGetProject project)
{
var results = new List<Packaging.Core.PackageDependency>();
var projectInstalledPackages = await project.GetInstalledPackagesAsync(CancellationToken.None);
var buildIntegratedProject = project as BuildIntegratedNuGetProject;
foreach (var package in projectInstalledPackages)
{
VersionRange range = null;
if (buildIntegratedProject != null && package.HasAllowedVersions)
{
// The actual range is passed as the allowed version range for build integrated projects.
range = package.AllowedVersions;
}
else
{
range = new VersionRange(
minVersion: package.PackageIdentity.Version,
includeMinVersion: true,
maxVersion: package.PackageIdentity.Version,
includeMaxVersion: true);
}
var dependency = new Packaging.Core.PackageDependency(package.PackageIdentity.Id, range);
results.Add(dependency);
}
return results;
}
*/
// Called after package install/uninstall.
public abstract void Refresh();
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
public string Id
{
get { return _searchResultPackage?.Id; }
}
public Uri IconUrl
{
get { return _searchResultPackage?.IconUrl; }
}
private DetailedPackageMetadata _packageMetadata;
public DetailedPackageMetadata PackageMetadata
{
get { return _packageMetadata; }
set
{
if (_packageMetadata != value)
{
_packageMetadata = value;
OnPropertyChanged(nameof(PackageMetadata));
}
}
}
protected abstract void CreateVersions();
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields")]
protected List<DisplayVersion> _versions;
// The list of versions that can be installed
public List<DisplayVersion> Versions
{
get { return _versions; }
}
private DisplayVersion _selectedVersion;
public DisplayVersion SelectedVersion
{
get { return _selectedVersion; }
set
{
if (_selectedVersion != value)
{
_selectedVersion = value;
DetailedPackageMetadata packageMetadata;
if (_metadataDict != null &&
_selectedVersion != null &&
_metadataDict.TryGetValue(_selectedVersion.Version, out packageMetadata))
{
PackageMetadata = packageMetadata;
}
else
{
PackageMetadata = null;
}
OnPropertyChanged(nameof(SelectedVersion));
}
}
}
// Calculate the version to select among _versions and select it
protected void SelectVersion()
{
if (_versions.Count == 0)
{
// there's nothing to select
return;
}
DisplayVersion versionToSelect = _versions
.Where(v => v != null && v.Version.Equals(_searchResultPackage.Version))
.FirstOrDefault();
if (versionToSelect == null)
{
versionToSelect = _versions[0];
}
if (versionToSelect != null)
{
SelectedVersion = versionToSelect;
}
}
internal async Task LoadPackageMetadaAsync(IPackageMetadataProvider metadataProvider, CancellationToken token)
{
var versions = await _searchResultPackage.GetVersionsAsync();
var packages = Enumerable.Empty<IPackageSearchMetadata>();
try
{
// load up the full details for each version
if (metadataProvider != null)
packages = await metadataProvider.GetPackageMetadataListAsync(Id, true, false, token);
}
catch (InvalidOperationException)
{
// Ignore failures.
}
var uniquePackages = packages
.GroupBy(m => m.Identity.Version, (v, ms) => ms.First());
var s = uniquePackages
.GroupJoin(
versions,
m => m.Identity.Version,
d => d.Version,
(m, d) => new DetailedPackageMetadata(m, d.FirstOrDefault()?.DownloadCount));
_metadataDict = s.ToDictionary(m => m.Version);
DetailedPackageMetadata p;
if (SelectedVersion != null
&& _metadataDict.TryGetValue(SelectedVersion.Version, out p))
{
PackageMetadata = p;
}
}
public abstract bool IsSolution { get; }
/*private Options _options;
public Options Options
{
get { return _options; }
set
{
_options = value;
OnPropertyChanged(nameof(Options));
}
}*/
}
}<file_sep>// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using NuGet.Protocol.Core.Types;
using NuGet.Versioning;
namespace NuGet.PackageManagement.UI
{
public class DetailedPackageMetadata
{
public DetailedPackageMetadata()
{
}
public DetailedPackageMetadata(IPackageSearchMetadata serverData, long? downloadCount)
{
Version = serverData.Identity.Version;
Summary = serverData.Summary;
Description = serverData.Description;
Authors = serverData.Authors;
Owners = serverData.Owners;
IconUrl = serverData.IconUrl;
LicenseUrl = serverData.LicenseUrl;
ProjectUrl = serverData.ProjectUrl;
ReportAbuseUrl = serverData.ReportAbuseUrl;
Tags = serverData.Tags;
DownloadCount = downloadCount;
Published = serverData.Published;
DependencySets = serverData.DependencySets?
.Select(e => new PackageDependencySetMetadata(e))
?? new PackageDependencySetMetadata[] { };
HasDependencies = DependencySets.Any(
dependencySet => dependencySet.Dependencies != null && dependencySet.Dependencies.Count > 0);
}
public NuGetVersion Version { get; set; }
public string Summary { get; set; }
public string Description { get; set; }
public string Authors { get; set; }
public string Owners { get; set; }
public Uri IconUrl { get; set; }
public Uri LicenseUrl { get; set; }
public Uri ProjectUrl { get; set; }
public Uri ReportAbuseUrl { get; set; }
public string Tags { get; set; }
public long? DownloadCount { get; set; }
public DateTimeOffset? Published { get; set; }
public IEnumerable<PackageDependencySetMetadata> DependencySets { get; set; }
// This property is used by data binding to display text "No dependencies"
public bool HasDependencies { get; set; }
}
}<file_sep>// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using NuGet.Versioning;
namespace NuGet.PackageManagement.UI
{
/// <summary>
/// Represents a version that will be displayed on the UI.
/// </summary>
internal class DisplayVersion
{
private readonly string _additionalInfo;
private readonly string _toString;
public DisplayVersion(
NuGetVersion version,
string additionalInfo)
: this(GetRange(version), additionalInfo)
{
}
public DisplayVersion(
VersionRange range,
string additionalInfo)
{
Range = range;
_additionalInfo = additionalInfo;
Version = range.MinVersion;
// Display a single version if the range is locked
if (range.HasLowerAndUpperBounds && range.MinVersion == range.MaxVersion)
{
_toString = string.IsNullOrEmpty(_additionalInfo) ?
Version.ToNormalizedString() :
_additionalInfo + " " + Version.ToNormalizedString();
}
else
{
// Display the range, use the original value for floating ranges
_toString = string.IsNullOrEmpty(_additionalInfo) ?
Range.OriginalString :
_additionalInfo + " " + Range.OriginalString;
}
}
public NuGetVersion Version { get; }
public VersionRange Range { get; }
public override string ToString()
{
return _toString;
}
public override bool Equals(object obj)
{
var other = obj as DisplayVersion;
return other != null && other.Version == Version;
}
public override int GetHashCode()
{
return Version.GetHashCode();
}
private static VersionRange GetRange(NuGetVersion version)
{
return new VersionRange(minVersion: version, includeMinVersion: true, maxVersion: version, includeMaxVersion: true);
}
}
}
<file_sep>// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace NuGet.PackageManagement.UI
{
public interface INuGetUILogger
{
void Log(ProjectManagement.MessageLevel level, string message, params object[] args);
}
}
<file_sep>// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using NuGet.Packaging.Core;
using NuGet.Protocol.Core.Types;
using NuGet.Versioning;
namespace NuGet.PackageManagement.UI
{
/// <summary>
/// Helper class encapsulating common scenarios of source repository operations.
/// </summary>
internal static class SourceRepositoryExtensions
{
public static Task<SearchResult<IPackageSearchMetadata>> SearchAsync(this SourceRepository sourceRepository, string searchText, SearchFilter searchFilter, int pageSize, CancellationToken cancellationToken)
{
var searchToken = new FeedSearchContinuationToken
{
SearchString = searchText,
SearchFilter = searchFilter,
StartIndex = 0
};
return sourceRepository.SearchAsync(searchToken, pageSize, cancellationToken);
}
public static async Task<SearchResult<IPackageSearchMetadata>> SearchAsync(
this SourceRepository sourceRepository, ContinuationToken continuationToken, int pageSize, CancellationToken cancellationToken)
{
var searchToken = continuationToken as FeedSearchContinuationToken;
if (searchToken == null)
{
throw new InvalidOperationException("Invalid token");
}
var searchResource = await sourceRepository.GetResourceAsync<PackageSearchResource>(cancellationToken);
IEnumerable<IPackageSearchMetadata> searchResults = null;
if (searchResource != null) {
searchResults = await searchResource.SearchAsync(
searchToken.SearchString,
searchToken.SearchFilter,
searchToken.StartIndex,
pageSize + 1,
Logging.NullLogger.Instance,
cancellationToken);
}
var items = searchResults?.ToArray() ?? new IPackageSearchMetadata[] { };
var hasMoreItems = items.Length > pageSize;
if (hasMoreItems)
{
items = items.Take(items.Length - 1).ToArray();
}
var result = SearchResult.FromItems(items);
var loadingStatus = hasMoreItems
? LoadingStatus.Ready
: items.Length == 0
? LoadingStatus.NoItemsFound
: LoadingStatus.NoMoreItems;
result.SourceSearchStatus = new Dictionary<string, LoadingStatus>
{
{ sourceRepository.PackageSource.Name, loadingStatus }
};
if (hasMoreItems)
{
result.NextToken = new FeedSearchContinuationToken
{
SearchString = searchToken.SearchString,
SearchFilter = searchToken.SearchFilter,
StartIndex = searchToken.StartIndex + items.Length
};
}
return result;
}
public static async Task<IPackageSearchMetadata> GetPackageMetadataAsync(
this SourceRepository sourceRepository, PackageIdentity identity, bool includePrerelease, CancellationToken cancellationToken)
{
var metadataResource = await sourceRepository.GetResourceAsync<PackageMetadataResource>(cancellationToken);
IEnumerable<IPackageSearchMetadata> packages = null;
if (metadataResource != null) {
packages = await metadataResource.GetMetadataAsync(
identity.Id,
includePrerelease: true,
includeUnlisted: false,
log: Logging.NullLogger.Instance,
token: cancellationToken);
}
if (packages?.FirstOrDefault() == null)
{
return null;
}
var packageMetadata = packages
.FirstOrDefault(p => p.Identity.Version == identity.Version)
?? PackageSearchMetadataBuilder.FromIdentity(identity).Build();
return packageMetadata.WithVersions(ToVersionInfo(packages, includePrerelease));
}
public static async Task<IPackageSearchMetadata> GetPackageMetadataFromLocalSourceAsync(
this SourceRepository localRepository, PackageIdentity identity, CancellationToken cancellationToken)
{
var localResource = await localRepository.GetResourceAsync<PackageMetadataResource>(cancellationToken);
IEnumerable<IPackageSearchMetadata> localPackages = null;
if (localResource != null) {
localPackages = await localResource.GetMetadataAsync(
identity.Id,
includePrerelease: true,
includeUnlisted: true,
log: Logging.NullLogger.Instance,
token: cancellationToken);
}
var packageMetadata = localPackages?.FirstOrDefault(p => p.Identity.Version == identity.Version);
var versions = new[]
{
new VersionInfo(identity.Version)
};
return packageMetadata?.WithVersions(versions);
}
public static async Task<IPackageSearchMetadata> GetLatestPackageMetadataAsync(
this SourceRepository sourceRepository, string packageId, bool includePrerelease, CancellationToken cancellationToken)
{
var metadataResource = await sourceRepository.GetResourceAsync<PackageMetadataResource>(cancellationToken);
IEnumerable<IPackageSearchMetadata> packages = null;
if (metadataResource != null) {
packages = await metadataResource.GetMetadataAsync(
packageId,
includePrerelease,
false,
Logging.NullLogger.Instance,
cancellationToken);
}
var highest = packages?
.OrderByDescending(e => e.Identity.Version, VersionComparer.VersionRelease)
.FirstOrDefault();
return highest?.WithVersions(ToVersionInfo(packages, includePrerelease));
}
public static async Task<IEnumerable<IPackageSearchMetadata>> GetPackageMetadataListAsync(
this SourceRepository sourceRepository, string packageId, bool includePrerelease, bool includeUnlisted, CancellationToken cancellationToken)
{
var metadataResource = await sourceRepository.GetResourceAsync<PackageMetadataResource>(cancellationToken);
IEnumerable<IPackageSearchMetadata> packages = null;
if (metadataResource != null) {
packages = await metadataResource.GetMetadataAsync(
packageId,
includePrerelease,
includeUnlisted,
Logging.NullLogger.Instance,
cancellationToken);
}
return packages;
}
private static IEnumerable<VersionInfo> ToVersionInfo(IEnumerable<IPackageSearchMetadata> packages, bool includePrerelease)
{
return packages?
.Where(v => includePrerelease || !v.Identity.Version.IsPrerelease)
.OrderByDescending(m => m.Identity.Version, VersionComparer.VersionRelease)
.Select(m => new VersionInfo(m.Identity.Version, m.DownloadCount));
}
public static async Task<IEnumerable<string>> IdStartsWithAsync(
this SourceRepository sourceRepository, string packageIdPrefix, bool includePrerelease, CancellationToken cancellationToken)
{
var autoCompleteResource = await sourceRepository.GetResourceAsync<AutoCompleteResource>(cancellationToken);
IEnumerable<string> packageIds = null;
if (autoCompleteResource != null) {
packageIds = await autoCompleteResource.IdStartsWith(
packageIdPrefix,
includePrerelease: includePrerelease,
log: Logging.NullLogger.Instance,
token: cancellationToken);
}
return packageIds ?? Enumerable.Empty<string>();
}
public static async Task<IEnumerable<NuGetVersion>> VersionStartsWithAsync(
this SourceRepository sourceRepository, string packageId, string versionPrefix, bool includePrerelease, CancellationToken cancellationToken)
{
var autoCompleteResource = await sourceRepository.GetResourceAsync<AutoCompleteResource>(cancellationToken);
IEnumerable<NuGetVersion> versions = null;
if (autoCompleteResource != null) {
versions = await autoCompleteResource.VersionStartsWith(
packageId,
versionPrefix,
includePrerelease: includePrerelease,
log: Logging.NullLogger.Instance,
token: cancellationToken);
}
return versions ?? Enumerable.Empty<NuGetVersion>();
}
}
}
<file_sep>//
// PackageCellView.cs
//
// Author:
// <NAME> <<EMAIL>>
//
// Copyright (c) 2014 Xamarin Inc. (http://xamarin.com)
//
// 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.
using System;
using MonoDevelop.Core;
using Xwt;
using Xwt.Drawing;
namespace MonoDevelop.PackageManagement
{
internal class PackageCellView : CanvasCellView
{
int packageIdFontSize;
int packageDescriptionFontSize;
public PackageCellView ()
{
CellWidth = 260;
BackgroundColor = Styles.CellBackgroundColor;
StrongSelectionColor = Styles.CellStrongSelectionColor;
SelectionColor = Styles.CellSelectionColor;
UseStrongSelectionColor = true;
if (Platform.IsWindows) {
packageIdFontSize = 10;
packageDescriptionFontSize = 9;
} else {
packageIdFontSize = 12;
packageDescriptionFontSize = 11;
}
}
public IDataField<PackageSearchResultViewModel> PackageField { get; set; }
public IDataField<Image> ImageField { get; set; }
public IDataField<bool> HasBackgroundColorField { get; set; }
public IDataField<double> CheckBoxAlphaField { get; set; }
public double CellWidth { get; set; }
public Color BackgroundColor { get; set; }
public Color StrongSelectionColor { get; set; }
public Color SelectionColor { get; set; }
public bool UseStrongSelectionColor { get; set; }
public event EventHandler<PackageCellViewEventArgs> PackageChecked;
protected override void OnDraw (Context ctx, Rectangle cellArea)
{
PackageSearchResultViewModel packageViewModel = GetValue (PackageField);
if (packageViewModel == null) {
return;
}
FillCellBackground (ctx);
UpdateTextColor (ctx);
DrawCheckBox (ctx, packageViewModel, cellArea);
DrawPackageImage (ctx, cellArea);
double packageIdWidth = cellArea.Width - packageDescriptionPadding.HorizontalSpacing - packageDescriptionLeftOffset;
// Package download count.
if (packageViewModel.HasDownloadCount) {
var downloadCountTextLayout = new TextLayout ();
downloadCountTextLayout.Text = packageViewModel.GetDownloadCountOrVersionDisplayText ();
Size size = downloadCountTextLayout.GetSize ();
Point location = new Point (cellArea.Right - packageDescriptionPadding.Right, cellArea.Top + packageDescriptionPadding.Top);
Point downloadLocation = location.Offset (-size.Width, 0);
ctx.DrawTextLayout (downloadCountTextLayout, downloadLocation);
packageIdWidth = downloadLocation.X - cellArea.Left - packageIdRightHandPaddingWidth - packageDescriptionPadding.HorizontalSpacing - packageDescriptionLeftOffset;
}
// Package Id.
var packageIdTextLayout = new TextLayout ();
packageIdTextLayout.Font = packageIdTextLayout.Font.WithSize (packageIdFontSize);
packageIdTextLayout.Markup = packageViewModel.GetNameMarkup ();
packageIdTextLayout.Trimming = TextTrimming.WordElipsis;
Size packageIdTextSize = packageIdTextLayout.GetSize ();
packageIdTextLayout.Width = packageIdWidth;
ctx.DrawTextLayout (
packageIdTextLayout,
cellArea.Left + packageDescriptionPadding.Left + packageDescriptionLeftOffset,
cellArea.Top + packageDescriptionPadding.Top);
// Package description.
var descriptionTextLayout = new TextLayout ();
descriptionTextLayout.Font = descriptionTextLayout.Font.WithSize (packageDescriptionFontSize);
descriptionTextLayout.Width = cellArea.Width - packageDescriptionPadding.HorizontalSpacing - packageDescriptionLeftOffset;
descriptionTextLayout.Height = cellArea.Height - packageIdTextSize.Height - packageDescriptionPadding.VerticalSpacing;
descriptionTextLayout.Text = packageViewModel.Summary;
descriptionTextLayout.Trimming = TextTrimming.Word;
ctx.DrawTextLayout (
descriptionTextLayout,
cellArea.Left + packageDescriptionPadding.Left + packageDescriptionLeftOffset,
cellArea.Top + packageIdTextSize.Height + packageDescriptionPaddingHeight + packageDescriptionPadding.Top);
}
void UpdateTextColor (Context ctx)
{
if (UseStrongSelectionColor && Selected) {
ctx.SetColor (Styles.CellTextSelectionColor);
} else {
ctx.SetColor (Styles.CellTextColor);
}
}
void FillCellBackground (Context ctx)
{
if (Selected) {
FillCellBackground (ctx, GetSelectedColor ());
} else if (IsBackgroundColorFieldSet ()) {
FillCellBackground (ctx, BackgroundColor);
}
}
Color GetSelectedColor ()
{
if (UseStrongSelectionColor) {
return StrongSelectionColor;
}
return SelectionColor;
}
bool IsBackgroundColorFieldSet ()
{
return GetValue (HasBackgroundColorField, false);
}
void FillCellBackground (Context ctx, Color color)
{
ctx.Rectangle (BackgroundBounds);
ctx.SetColor (color);
ctx.Fill ();
}
void DrawCheckBox (Context ctx, PackageSearchResultViewModel packageViewModel, Rectangle cellArea)
{
CreateCheckboxImages ();
Image image = GetCheckBoxImage (packageViewModel.IsChecked);
double alpha = GetCheckBoxImageAlpha ();
ctx.DrawImage (
image,
cellArea.Left + checkBoxPadding.Left,
cellArea.Top + ((cellArea.Height - checkBoxImageSize.Height - 2) / 2),
alpha);
}
void CreateCheckboxImages ()
{
if (whiteCheckedCheckBoxImage != null)
return;
var widget = Toolkit.CurrentEngine.GetNativeWidget (ParentWidget);
var checkbox = new PackageCellViewCheckBox (ParentWidget.ParentWindow.Screen.ScaleFactor);
checkbox.Container = (Gtk.Widget)widget;
checkbox.Size = (int)checkBoxImageSize.Width + 1;
// White checkbox.
whiteUncheckedCheckBoxImage = checkbox.CreateImage ();
checkbox.Active = true;
whiteCheckedCheckBoxImage = checkbox.CreateImage ();
// Odd numbered checkbox.
checkbox.BackgroundColor = BackgroundColor;
checkedCheckBoxWithBackgroundColorImage = checkbox.CreateImage ();
checkbox.Active = false;
uncheckedCheckBoxWithBackgroundColorImage = checkbox.CreateImage ();
// Grey check box.
checkbox.BackgroundColor = SelectionColor;
greyUncheckedCheckBoxImage = checkbox.CreateImage ();
checkbox.Active = true;
greyCheckedCheckBoxImage = checkbox.CreateImage ();
// Blue check box.
checkbox.BackgroundColor = StrongSelectionColor;
blueCheckedCheckBoxImage = checkbox.CreateImage ();
checkbox.Active = false;
blueUncheckedCheckBoxImage = checkbox.CreateImage ();
}
double GetCheckBoxImageAlpha ()
{
return GetValue (CheckBoxAlphaField, 1);
}
Image GetCheckBoxImage (bool checkBoxActive)
{
if (Selected && UseStrongSelectionColor && checkBoxActive) {
return blueCheckedCheckBoxImage;
} else if (Selected && checkBoxActive) {
return greyCheckedCheckBoxImage;
} else if (Selected && UseStrongSelectionColor) {
return blueUncheckedCheckBoxImage;
} else if (Selected) {
return greyUncheckedCheckBoxImage;
} else if (checkBoxActive && IsBackgroundColorFieldSet ()) {
return checkedCheckBoxWithBackgroundColorImage;
} else if (checkBoxActive) {
return whiteCheckedCheckBoxImage;
} else if (IsBackgroundColorFieldSet ()) {
return uncheckedCheckBoxWithBackgroundColorImage;
} else {
return whiteUncheckedCheckBoxImage;
}
}
void DrawPackageImage (Context ctx, Rectangle cellArea)
{
Image image = GetValue (ImageField);
if (image == null) {
image = defaultPackageImage;
}
if (Selected)
image = image.WithStyles ("sel");
if (PackageImageNeedsResizing (image)) {
Point imageLocation = GetPackageImageLocation (maxPackageImageSize, cellArea);
ctx.DrawImage (
image,
cellArea.Left + packageImagePadding.Left + checkBoxAreaWidth + imageLocation.X,
Math.Round( cellArea.Top + packageImagePadding.Top + imageLocation.Y),
maxPackageImageSize.Width,
maxPackageImageSize.Height);
} else {
Point imageLocation = GetPackageImageLocation (image.Size, cellArea);
ctx.DrawImage (
image,
cellArea.Left + packageImagePadding.Left + checkBoxAreaWidth + imageLocation.X,
Math.Round (cellArea.Top + packageImagePadding.Top + imageLocation.Y));
}
}
bool PackageImageNeedsResizing (Image image)
{
return (image.Width > maxPackageImageSize.Width) || (image.Height > maxPackageImageSize.Height);
}
Point GetPackageImageLocation (Size imageSize, Rectangle cellArea)
{
double width = (packageImageAreaWidth - imageSize.Width) / 2;
double height = (cellArea.Height - imageSize.Height - packageImagePadding.Bottom) / 2;
return new Point (width, height);
}
protected override Size OnGetRequiredSize ()
{
var layout = new TextLayout ();
layout.Text = "W";
layout.Font = layout.Font.WithSize (packageDescriptionFontSize);
Size size = layout.GetSize ();
return new Size (CellWidth, size.Height * linesDisplayedCount + packageDescriptionPaddingHeight + packageDescriptionPadding.VerticalSpacing);
}
protected override void OnButtonPressed (ButtonEventArgs args)
{
PackageSearchResultViewModel packageViewModel = GetValue (PackageField);
if (packageViewModel == null) {
base.OnButtonPressed (args);
return;
}
double x = args.X - Bounds.X;
double y = args.Y - Bounds.Y;
if (checkBoxImageClickableRectangle.Contains (x, y)) {
packageViewModel.IsChecked = !packageViewModel.IsChecked;
OnPackageChecked (packageViewModel);
}
}
void OnPackageChecked (PackageSearchResultViewModel packageViewModel)
{
if (PackageChecked != null) {
PackageChecked (this, new PackageCellViewEventArgs (packageViewModel));
}
}
const int packageDescriptionPaddingHeight = 5;
const int packageIdRightHandPaddingWidth = 5;
const int linesDisplayedCount = 4;
const int checkBoxAreaWidth = 36;
const int packageImageAreaWidth = 54;
const int packageDescriptionLeftOffset = checkBoxAreaWidth + packageImageAreaWidth + 8;
WidgetSpacing packageDescriptionPadding = new WidgetSpacing (5, 5, 5, 10);
WidgetSpacing packageImagePadding = new WidgetSpacing (0, 0, 0, 5);
WidgetSpacing checkBoxPadding = new WidgetSpacing (10, 0, 0, 10);
Size maxPackageImageSize = new Size (48, 48);
Size checkBoxImageSize = new Size (16, 16);
Rectangle checkBoxImageClickableRectangle = new Rectangle (0, 10, 40, 50);
Image whiteCheckedCheckBoxImage;
Image whiteUncheckedCheckBoxImage;
Image greyCheckedCheckBoxImage;
Image greyUncheckedCheckBoxImage;
Image blueCheckedCheckBoxImage;
Image blueUncheckedCheckBoxImage;
Image checkedCheckBoxWithBackgroundColorImage;
Image uncheckedCheckBoxWithBackgroundColorImage;
static readonly Image defaultPackageImage = Image.FromResource (typeof(PackageCellView), "package-48.png");
}
}
<file_sep>//
// NuGetPackageReferenceNodeDescriptor.cs
//
// Author:
// <NAME> <<EMAIL>>
//
// Copyright (c) 2015 <NAME>
//
// 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.
//
using MonoDevelop.Core;
using MonoDevelop.DesignerSupport;
using Paket;
namespace MonoDevelop.Paket.NodeBuilders
{
public class NuGetPackageReferenceNodeDescriptor : CustomDescriptor
{
readonly NuGetPackageReferenceNode packageReferenceNode;
readonly Requirements.InstallSettings installSettings;
public NuGetPackageReferenceNodeDescriptor (NuGetPackageReferenceNode packageReferenceNode)
{
this.packageReferenceNode = packageReferenceNode;
installSettings = packageReferenceNode.InstallSettings.Settings;
}
[LocalizedCategory ("Package")]
[LocalizedDisplayName ("Id")]
[LocalizedDescription ("Package Id.")]
public string Id {
get { return packageReferenceNode.Id; }
}
[LocalizedCategory ("Package")]
[LocalizedDisplayName ("Copy Local")]
[LocalizedDescription ("Copy Local.")]
public string CopyLocal {
get {
if (installSettings.CopyLocal != null)
return installSettings.CopyLocal.Value.ToString ();
return string.Empty;
}
}
[LocalizedCategory ("Package")]
[LocalizedDisplayName ("Import Targets")]
[LocalizedDescription ("Import targets.")]
public string ImportTargets {
get {
if (installSettings.ImportTargets != null)
return installSettings.ImportTargets.Value.ToString ();
return string.Empty;
}
}
[LocalizedCategory ("Package")]
[LocalizedDisplayName ("Omit Content")]
[LocalizedDescription ("Omit content.")]
public string OmitContent {
get {
if (installSettings.OmitContent != null)
return installSettings.OmitContent.Value.ToString ();
return string.Empty;
}
}
}
}
<file_sep>// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Linq;
using NuGet.Frameworks;
using NuGet.Packaging;
namespace NuGet.PackageManagement.UI
{
public class PackageDependencySetMetadata
{
public PackageDependencySetMetadata(PackageDependencyGroup dependencyGroup)
{
TargetFramework = dependencyGroup.TargetFramework;
Dependencies = dependencyGroup.Packages
.Select(d => new PackageDependencyMetadata(d))
.ToList()
.AsReadOnly();
}
public NuGetFramework TargetFramework { get; private set; }
public IReadOnlyCollection<PackageDependencyMetadata> Dependencies { get; private set; }
}
}<file_sep>// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using NuGet.Common;
using NuGet.Packaging.Core;
using NuGet.Protocol.Core.Types;
using NuGet.Versioning;
namespace NuGet.PackageManagement.UI
{
// This is the model class behind the package items in the infinite scroll list.
// Some of its properties, such as Latest Version, Status, are fetched on-demand in the background.
internal class PackageItemListViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public string Id { get; set; }
public NuGetVersion Version { get; set; }
private string _author;
public string Author
{
get
{
return _author;
}
set
{
_author = value;
OnPropertyChanged(nameof(Author));
}
}
// The installed version of the package.
private NuGetVersion _installedVersion;
public NuGetVersion InstalledVersion
{
get
{
return _installedVersion;
}
set
{
if (!VersionEquals(_installedVersion, value))
{
_installedVersion = value;
OnPropertyChanged(nameof(InstalledVersion));
}
}
}
// The version that can be installed or updated to. It is null
// if the installed version is already the latest.
private NuGetVersion _latestVersion;
public NuGetVersion LatestVersion
{
get
{
return _latestVersion;
}
set
{
if (!VersionEquals(_latestVersion, value))
{
_latestVersion = value;
OnPropertyChanged(nameof(LatestVersion));
// update tool tip
if (_latestVersion != null)
{
var displayVersion = new DisplayVersion(_latestVersion, string.Empty);
LatestVersionToolTip = string.Format(
CultureInfo.CurrentCulture,
"Latest version: {0}",
displayVersion);
}
else
{
LatestVersionToolTip = null;
}
}
}
}
private string _latestVersionToolTip;
public string LatestVersionToolTip
{
get
{
return _latestVersionToolTip;
}
set
{
_latestVersionToolTip = value;
OnPropertyChanged(nameof(LatestVersionToolTip));
}
}
private bool _selected;
public bool Selected
{
get { return _selected; }
set
{
if (_selected != value)
{
_selected = value;
OnPropertyChanged(nameof(Selected));
}
}
}
private bool VersionEquals(NuGetVersion v1, NuGetVersion v2)
{
if (v1 == null && v2 == null)
{
return true;
}
if (v1 == null)
{
return false;
}
return v1.Equals(v2, VersionComparison.Default);
}
private long? _downloadCount;
public long? DownloadCount
{
get
{
return _downloadCount;
}
set
{
_downloadCount = value;
OnPropertyChanged(nameof(DownloadCount));
}
}
public string Summary { get; set; }
private PackageStatus _status = PackageStatus.NotInstalled;
public PackageStatus Status
{
get
{
//TriggerStatusLoader();
return _status;
}
private set
{
bool refresh = _status != value;
_status = value;
if (refresh)
{
OnPropertyChanged(nameof(Status));
}
}
}
/*private bool _providersLoaderStarted;
private AlternativePackageManagerProviders _providers;
public AlternativePackageManagerProviders Providers
{
get
{
if (!_providersLoaderStarted && ProvidersLoader != null)
{
_providersLoaderStarted = true;
Task.Run(async () =>
{
var result = await ProvidersLoader.Value;
await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
Providers = result;
});
}
return _providers;
}
private set
{
_providers = value;
OnPropertyChanged(nameof(Providers));
}
}
private Lazy<Task<AlternativePackageManagerProviders>> _providersLoader;
internal Lazy<Task<AlternativePackageManagerProviders>> ProvidersLoader
{
get
{
return _providersLoader;
}
set
{
if (_providersLoader != value)
{
_providersLoaderStarted = false;
}
_providersLoader = value;
OnPropertyChanged(nameof(Providers));
}
}*/
public Uri IconUrl { get; set; }
public Lazy<Task<IEnumerable<VersionInfo>>> Versions { get; set; }
public Task<IEnumerable<VersionInfo>> GetVersionsAsync() => Versions.Value;
/*private Lazy<Task<NuGetVersion>> _backgroundLoader;
private void TriggerStatusLoader()
{
if (!_backgroundLoader.IsValueCreated)
{
Task.Run(async () =>
{
var result = await _backgroundLoader.Value;
await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
LatestVersion = result;
Status = GetPackageStatus(LatestVersion, InstalledVersion);
});
}
}
public void UpdatePackageStatus(IEnumerable<PackageIdentity> installedPackages)
{
// Get the minimum version installed in any target project/solution
InstalledVersion = installedPackages
.GetPackageVersions(Id)
.MinOrDefault();
_backgroundLoader = AsyncLazy.New(
async () =>
{
var packageVersions = await GetVersionsAsync();
var latestAvailableVersion = packageVersions
.Select(p => p.Version)
.MaxOrDefault();
return latestAvailableVersion;
});
OnPropertyChanged(nameof(Status));
}
private static PackageStatus GetPackageStatus(NuGetVersion latestAvailableVersion, NuGetVersion installedVersion)
{
var status = PackageStatus.NotInstalled;
if (installedVersion != null)
{
status = PackageStatus.Installed;
if (VersionComparer.VersionRelease.Compare(installedVersion, latestAvailableVersion) < 0)
{
status = PackageStatus.UpdateAvailable;
}
}
return status;
}*/
protected void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
var e = new PropertyChangedEventArgs(propertyName);
PropertyChanged(this, e);
}
}
public override string ToString()
{
return Id;
}
public string Title { get; set; }
public Uri LicenseUrl { get; set; }
public Uri ProjectUrl { get; set; }
public DateTimeOffset? Published { get; set; }
public string Description { get; set; }
}
}
<file_sep>//
// ProjectModifiedEventArgs.cs
//
// Author:
// <NAME> <<EMAIL>>
//
// Copyright (c) 2014 Xamarin Inc. (http://xamarin.com)
//
// 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.
using System;
using System.Collections.Generic;
using MonoDevelop.Projects;
namespace MonoDevelop.PackageManagement
{
internal class ProjectModifiedEventArgs : EventArgs
{
public ProjectModifiedEventArgs (IDotNetProject project, string propertyName)
{
Project = project;
PropertyName = propertyName;
}
public ProjectModifiedEventArgs (DotNetProject project, string propertyName)
: this (new DotNetProjectProxy (project), propertyName)
{
}
public IDotNetProject Project { get; private set; }
public string PropertyName { get; private set; }
public bool IsTargetFramework ()
{
return String.Equals ("TargetFramework", PropertyName, StringComparison.OrdinalIgnoreCase);
}
public static IEnumerable<ProjectModifiedEventArgs> Create (SolutionItemModifiedEventArgs e)
{
foreach (SolutionItemModifiedEventInfo eventInfo in e) {
var project = eventInfo.SolutionItem as DotNetProject;
if (project != null) {
yield return new ProjectModifiedEventArgs (project, eventInfo.Hint);
}
}
}
}
}
<file_sep>//
// PaketDocumentControllerExtension.cs
//
// Author:
// <NAME> <<EMAIL>>
//
// Copyright (c) 2019 Microsoft
//
// 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.
using System;
using System.Threading.Tasks;
using MonoDevelop.Core;
using MonoDevelop.Ide.Editor;
using MonoDevelop.Ide.Gui.Documents;
namespace MonoDevelop.Paket
{
class PaketDocumentControllerExtension : DocumentControllerExtension
{
PaketDocumentContext context;
public override Task<bool> SupportsController (DocumentController controller)
{
bool supported = false;
if (controller is FileDocumentController fileDocumentController) {
FilePath filePath = fileDocumentController.FilePath;
if (filePath.IsNotNull)
supported = StringComparer.OrdinalIgnoreCase.Equals (filePath.FileName, "paket.dependencies");
}
return Task.FromResult (supported);
}
public override Task Initialize (Properties status)
{
var fileController = Controller as FileDocumentController;
if (fileController != null) {
return Initialize (fileController, status);
}
return base.Initialize (status);
}
async Task Initialize (FileDocumentController fileController, Properties status)
{
await base.Initialize (status);
context = new PaketDocumentContext (fileController);
}
protected override object OnGetContent (Type type)
{
if (typeof (DocumentContext).IsAssignableFrom (type))
return context;
return base.OnGetContent (type);
}
public override void Dispose ()
{
if (context != null) {
context.Dispose ();
}
base.Dispose ();
}
}
}
<file_sep>// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Threading;
using System.Threading.Tasks;
using NuGet.Protocol.Core.Types;
using NuGet.Protocol.Core.v2;
namespace NuGet.Protocol.VisualStudio
{
public class PackageSearchResourceLocalProvider : V2ResourceProvider
{
public PackageSearchResourceLocalProvider()
: base(typeof(PackageSearchResource), nameof(PackageSearchResourceLocalProvider), NuGetResourceProviderPositions.Last)
{
}
public override async Task<Tuple<bool, INuGetResource>> TryCreate(SourceRepository source,
CancellationToken token)
{
PackageSearchResourceLocal resource = null;
if (FeedTypeUtility.GetFeedType(source.PackageSource) == FeedType.FileSystem)
{
var v2repo = await GetRepository(source, token);
if (v2repo != null)
{
resource = new PackageSearchResourceLocal(v2repo);
}
}
return new Tuple<bool, INuGetResource>(resource != null, resource);
}
}
}<file_sep>//
// ProjectTargetFramework.cs
//
// Author:
// <NAME> <<EMAIL>>
//
// Copyright (C) 2012 <NAME>
//
// 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.
//
using System;
using System.Runtime.Versioning;
using MonoDevelop.Core.Assemblies;
using MonoDevelop.PackageManagement;
using MonoDevelop.Projects;
namespace MonoDevelop.PackageManagement
{
internal class ProjectTargetFramework
{
IDotNetProject project;
FrameworkName targetFramework;
public ProjectTargetFramework (IDotNetProject project)
{
this.project = project;
GetTargetFramework();
}
void GetTargetFramework()
{
string identifier = GetTargetFrameworkIdentifier();
string version = GetTargetFrameworkVersion();
string profile = GetTargetFrameworkProfile();
GetTargetFramework(identifier, version, profile);
}
void GetTargetFramework(string identifier, string version, string profile)
{
string name = String.Format("{0}, Version={1}, Profile={2}", identifier, version, profile);
targetFramework = new FrameworkName(name);
}
string GetTargetFrameworkIdentifier()
{
return UseDefaultIfNullOrEmpty(TargetFrameworkMoniker.Identifier, ".NETFramework");
}
TargetFrameworkMoniker TargetFrameworkMoniker {
get { return project.TargetFrameworkMoniker; }
}
string UseDefaultIfNullOrEmpty(string value, string defaultValue)
{
if (String.IsNullOrEmpty(value)) {
return defaultValue;
}
return value;
}
string GetTargetFrameworkVersion()
{
return TargetFrameworkMoniker.Version;
}
string GetTargetFrameworkProfile()
{
return UseDefaultIfNullOrEmpty(TargetFrameworkMoniker.Profile, String.Empty);
}
public FrameworkName TargetFrameworkName {
get { return targetFramework; }
}
}
}
<file_sep>// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace NuGet.PackageManagement.UI
{
internal interface IItemLoaderState
{
LoadingStatus LoadingStatus { get; }
int ItemsCount { get; }
IDictionary<string, LoadingStatus> SourceLoadingStatus { get; }
}
/// <summary>
/// Represents stateful item loader contract that supports pagination and background loading
/// </summary>
/// <typeparam name="T"></typeparam>
internal interface IItemLoader<T>
{
bool IsMultiSource { get; }
IItemLoaderState State { get; }
IEnumerable<T> GetCurrent();
Task LoadNextAsync(IProgress<IItemLoaderState> progress, CancellationToken cancellationToken);
Task UpdateStateAsync(IProgress<IItemLoaderState> progress, CancellationToken cancellationToken);
void Reset();
Task<int> GetTotalCountAsync(int maxCount, CancellationToken cancellationToken);
}
}
<file_sep>//
// PaketSearchCommandQuery.cs
//
// Author:
// <NAME> <<EMAIL>>
//
// Copyright (c) 2015 <NAME>
//
// 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.
//
using System;
namespace MonoDevelop.Paket
{
public class PaketSearchCommandQuery
{
string search;
string[] arguments;
public PaketSearchCommandQuery (string search)
{
this.search = search;
IsPaketSearchCommand = false;
}
public void Parse ()
{
if (String.IsNullOrWhiteSpace (search)) {
arguments = new string [0];
} else {
arguments = search.Trim ().Split (new [] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
}
CheckIfPaketCommand ();
CommandType = GetArgument (1);
}
public bool IsPaketSearchCommand { get; private set; }
public string CommandType { get; private set; }
public string GetArgument (int index)
{
if (index < arguments.Length) {
return arguments [index];
}
return String.Empty;
}
static readonly string paketCommand = "paket";
void CheckIfPaketCommand ()
{
if (arguments.Length < 1)
return;
string firstPart = arguments [0];
if (firstPart.Length > paketCommand.Length)
return;
IsPaketSearchCommand = paketCommand.StartsWith (firstPart, StringComparison.OrdinalIgnoreCase);
}
}
}
<file_sep>// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using NuGet.Packaging.Core;
using NuGet.Protocol.Core.Types;
using NuGet.Versioning;
namespace NuGet.PackageManagement.UI
{
/// <summary>
/// Implements a consolidated metadata provider for multiple package sources
/// with optional local repository as a fallback metadata source.
/// </summary>
internal class MultiSourcePackageMetadataProvider : IPackageMetadataProvider
{
private readonly IEnumerable<SourceRepository> _sourceRepositories;
private readonly SourceRepository _localRepository;
private readonly SourceRepository _globalLocalRepository;
private readonly Logging.ILogger _logger;
public MultiSourcePackageMetadataProvider(
IEnumerable<SourceRepository> sourceRepositories,
SourceRepository optionalLocalRepository,
SourceRepository optionalGlobalLocalRepository,
Logging.ILogger logger)
{
if (sourceRepositories == null)
{
throw new ArgumentNullException(nameof(sourceRepositories));
}
_sourceRepositories = sourceRepositories;
_localRepository = optionalLocalRepository;
_globalLocalRepository = optionalGlobalLocalRepository;
if (logger == null)
{
throw new ArgumentNullException(nameof(logger));
}
_logger = logger;
}
public async Task<IPackageSearchMetadata> GetPackageMetadataAsync(PackageIdentity identity, bool includePrerelease, CancellationToken cancellationToken)
{
var tasks = _sourceRepositories
.Select(r => r.GetPackageMetadataAsync(identity, includePrerelease, cancellationToken))
.ToList();
if (_localRepository != null)
{
tasks.Add(_localRepository.GetPackageMetadataFromLocalSourceAsync(identity, cancellationToken));
}
var ignored = tasks
.Select(task => task.ContinueWith(LogError, TaskContinuationOptions.OnlyOnFaulted))
.ToArray();
var completed = (await Task.WhenAll(tasks))
.Where(m => m != null);
var master = completed.FirstOrDefault(m => !string.IsNullOrEmpty(m.Summary))
?? completed.FirstOrDefault()
?? PackageSearchMetadataBuilder.FromIdentity(identity).Build();
return master.WithVersions(
asyncValueFactory: () => MergeVersionsAsync(identity, completed));
}
public async Task<IPackageSearchMetadata> GetLatestPackageMetadataAsync(PackageIdentity identity,
bool includePrerelease, CancellationToken cancellationToken)
{
var tasks = _sourceRepositories
.Select(r => r.GetLatestPackageMetadataAsync(identity.Id, includePrerelease, cancellationToken))
.ToArray();
var ignored = tasks
.Select(task => task.ContinueWith(LogError, TaskContinuationOptions.OnlyOnFaulted))
.ToArray();
var completed = (await Task.WhenAll(tasks))
.Where(m => m != null);
var highest = completed
.OrderByDescending(e => e.Identity.Version, VersionComparer.VersionRelease)
.FirstOrDefault();
return highest?.WithVersions(
asyncValueFactory: () => MergeVersionsAsync(identity, completed));
}
public async Task<IEnumerable<IPackageSearchMetadata>> GetPackageMetadataListAsync(string packageId, bool includePrerelease, bool includeUnlisted, CancellationToken cancellationToken)
{
var tasks = _sourceRepositories
.Select(r => r.GetPackageMetadataListAsync(packageId, includePrerelease, includeUnlisted, cancellationToken))
.ToArray();
var ignored = tasks
.Select(task => task.ContinueWith(LogError, TaskContinuationOptions.OnlyOnFaulted))
.ToArray();
var completed = (await Task.WhenAll(tasks))
.Where(m => m != null);
return completed.SelectMany(p => p);
}
public async Task<IPackageSearchMetadata> GetLocalPackageMetadataAsync(PackageIdentity identity, bool includePrerelease, CancellationToken cancellationToken)
{
var result = await _localRepository.GetPackageMetadataFromLocalSourceAsync(identity, cancellationToken);
if (result == null)
{
if (_globalLocalRepository != null)
result = await _globalLocalRepository.GetPackageMetadataFromLocalSourceAsync(identity, cancellationToken);
if (result == null)
{
return null;
}
}
return result.WithVersions(asyncValueFactory: () => FetchAndMergeVersionsAsync(identity, includePrerelease, cancellationToken));
}
private static async Task<IEnumerable<VersionInfo>> MergeVersionsAsync(PackageIdentity identity, IEnumerable<IPackageSearchMetadata> packages)
{
var versions = await Task.WhenAll(packages.Select(m => m.GetVersionsAsync()));
var allVersions = versions
.SelectMany(v => v)
.Concat(new[] { new VersionInfo(identity.Version) });
return allVersions
.GroupBy(v => v.Version, v => v.DownloadCount)
.Select(g => new VersionInfo(g.Key, g.Max()))
.ToArray();
}
private async Task<IEnumerable<VersionInfo>> FetchAndMergeVersionsAsync(PackageIdentity identity, bool includePrerelease, CancellationToken cancellationToken)
{
var tasks = _sourceRepositories
.Select(r => r.GetPackageMetadataAsync(identity, includePrerelease, cancellationToken))
.ToList();
if (_localRepository != null)
{
tasks.Add(_localRepository.GetPackageMetadataFromLocalSourceAsync(identity, cancellationToken));
}
var ignored = tasks
.Select(task => task.ContinueWith(LogError, TaskContinuationOptions.OnlyOnFaulted))
.ToArray();
var completed = (await Task.WhenAll(tasks))
.Where(m => m != null);
return await MergeVersionsAsync(identity, completed);
}
private void LogError(Task task)
{
foreach (var ex in task.Exception.Flatten().InnerExceptions)
{
_logger.LogError(ex.ToString());
}
}
}
}<file_sep>// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using NuGet.Packaging.Core;
using NuGet.Protocol.Core.Types;
using NuGet.Protocol.Core.v2;
using NuGet.Versioning;
namespace NuGet.Protocol.VisualStudio
{
public class PackageMetadataResourceLocal : PackageMetadataResource
{
private readonly IPackageRepository V2Client;
public PackageMetadataResourceLocal(V2Resource resource)
{
V2Client = resource.V2Client;
}
public override async Task<IEnumerable<IPackageSearchMetadata>> GetMetadataAsync(
string packageId,
bool includePrerelease,
bool includeUnlisted,
Logging.ILogger log,
CancellationToken token)
{
return await Task.Run(() =>
{
return V2Client.FindPackagesById(packageId)
.Where(p => includeUnlisted || !p.Published.HasValue || p.Published.Value.Year > 1901)
.Where(p => includePrerelease || String.IsNullOrEmpty(p.Version.SpecialVersion))
.Select(GetPackageMetadata);
},
token);
}
private static IPackageSearchMetadata GetPackageMetadata(IPackage package) => new PackageSearchMetadata(package);
}
}<file_sep>// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using NuGet.Common;
//using NuGet.Indexing;
using NuGet.Protocol.Core.Types;
namespace NuGet.PackageManagement.UI
{
/// <summary>
/// Consolidated live sources package feed enumerating packages and aggregating search results.
/// </summary>
internal class MultiSourcePackageFeed : IPackageFeed
{
private static readonly TimeSpan DefaultTimeout = TimeSpan.FromSeconds(5);
private const int PageSize = 25;
private readonly SourceRepository[] _sourceRepositories;
private readonly INuGetUILogger _logger;
public bool IsMultiSource => _sourceRepositories.Length > 1;
private class AggregatedContinuationToken : ContinuationToken
{
public string SearchString { get; set; }
public IDictionary<string, ContinuationToken> SourceSearchCursors { get; set; } = new Dictionary<string, ContinuationToken>();
}
private class AggregatedRefreshToken : RefreshToken
{
public string SearchString { get; set; }
public IDictionary<string, Task<SearchResult<IPackageSearchMetadata>>> SearchTasks { get; set; }
public IDictionary<string, LoadingStatus> SourceSearchStatus { get; set; }
}
public MultiSourcePackageFeed(IEnumerable<SourceRepository> sourceRepositories, INuGetUILogger logger)
{
if (sourceRepositories == null)
{
throw new ArgumentNullException(nameof(sourceRepositories));
}
if (!sourceRepositories.Any())
{
throw new ArgumentException("Collection of source repositories cannot be empty", nameof(sourceRepositories));
}
_sourceRepositories = sourceRepositories.ToArray();
_logger = logger;
}
public async Task<SearchResult<IPackageSearchMetadata>> SearchAsync(string searchText, SearchFilter filter, CancellationToken cancellationToken)
{
var searchTasks = TaskCombinators.ObserveErrorsAsync(
_sourceRepositories,
r => r.PackageSource.Name,
(r, t) => r.SearchAsync(searchText, filter, PageSize, t),
LogError,
cancellationToken);
return await WaitForCompletionOrBailOutAsync(searchText, searchTasks, cancellationToken);
}
public async Task<SearchResult<IPackageSearchMetadata>> ContinueSearchAsync(ContinuationToken continuationToken, CancellationToken cancellationToken)
{
var searchToken = continuationToken as AggregatedContinuationToken;
if (searchToken?.SourceSearchCursors == null)
{
throw new InvalidOperationException("Invalid token");
}
var searchTokens = _sourceRepositories
.Join(searchToken.SourceSearchCursors,
r => r.PackageSource.Name,
c => c.Key,
(r, c) => new { Repository = r, NextToken = c.Value });
var searchTasks = TaskCombinators.ObserveErrorsAsync(
searchTokens,
j => j.Repository.PackageSource.Name,
(j, t) => j.Repository.SearchAsync(j.NextToken, PageSize, t),
LogError,
cancellationToken);
return await WaitForCompletionOrBailOutAsync(searchToken.SearchString, searchTasks, cancellationToken);
}
public async Task<SearchResult<IPackageSearchMetadata>> RefreshSearchAsync(RefreshToken refreshToken, CancellationToken cancellationToken)
{
var searchToken = refreshToken as AggregatedRefreshToken;
if (searchToken == null)
{
throw new InvalidOperationException("Invalid token");
}
return await WaitForCompletionOrBailOutAsync(searchToken.SearchString, searchToken.SearchTasks, cancellationToken);
}
private async Task<SearchResult<IPackageSearchMetadata>> WaitForCompletionOrBailOutAsync(
string searchText,
IDictionary<string, Task<SearchResult<IPackageSearchMetadata>>> searchTasks,
CancellationToken cancellationToken)
{
if (searchTasks.Count == 0)
{
return SearchResult.Empty<IPackageSearchMetadata>();
}
var aggregatedTask = Task.WhenAll(searchTasks.Values);
RefreshToken refreshToken = null;
if (aggregatedTask != await Task.WhenAny(aggregatedTask, Task.Delay(DefaultTimeout)))
{
refreshToken = new AggregatedRefreshToken
{
SearchString = searchText,
SearchTasks = searchTasks,
RetryAfter = DefaultTimeout
};
}
var partitionedTasks = searchTasks
.ToLookup(t => t.Value.Status == TaskStatus.RanToCompletion);
var completedOnly = partitionedTasks[true];
SearchResult<IPackageSearchMetadata> aggregated;
if (completedOnly.Any())
{
var results = await Task.WhenAll(completedOnly.Select(kv => kv.Value));
aggregated = await AggregateSearchResultsAsync(searchText, results);
}
else
{
aggregated = SearchResult.Empty<IPackageSearchMetadata>();
}
aggregated.RefreshToken = refreshToken;
var notCompleted = partitionedTasks[false];
if (notCompleted.Any())
{
aggregated.SourceSearchStatus
.AddRange(notCompleted
.ToDictionary(kv => kv.Key, kv => GetLoadingStatus(kv.Value.Status)));
}
return aggregated;
}
private static LoadingStatus GetLoadingStatus(TaskStatus taskStatus)
{
switch(taskStatus)
{
case TaskStatus.Canceled:
return LoadingStatus.Cancelled;
case TaskStatus.Created:
case TaskStatus.RanToCompletion:
case TaskStatus.Running:
case TaskStatus.WaitingForActivation:
case TaskStatus.WaitingForChildrenToComplete:
case TaskStatus.WaitingToRun:
return LoadingStatus.Loading;
case TaskStatus.Faulted:
return LoadingStatus.ErrorOccurred;
default:
return LoadingStatus.Unknown;
}
}
private async Task<SearchResult<IPackageSearchMetadata>> AggregateSearchResultsAsync(
string searchText,
IEnumerable<SearchResult<IPackageSearchMetadata>> results)
{
SearchResult<IPackageSearchMetadata> result;
var nonEmptyResults = results.Where(r => r.Any()).ToArray();
if (nonEmptyResults.Length == 0)
{
result = SearchResult.Empty<IPackageSearchMetadata>();
}
else if (nonEmptyResults.Length == 1)
{
result = SearchResult.FromItems(nonEmptyResults[0].Items);
}
else
{
throw new NotImplementedException ();
//var items = nonEmptyResults.Select(r => r.Items).ToArray();
//var indexer = new RelevanceSearchResultsIndexer();
//var aggregator = new SearchResultsAggregator(indexer);
//var aggregatedItems = await aggregator.AggregateAsync(
// searchText, items);
//result = SearchResult.FromItems(aggregatedItems.ToArray());
//// set correct count of unmerged items
//result.RawItemsCount = items.Aggregate(0, (r, next) => r + next.Count);
}
result.SourceSearchStatus = results
.SelectMany(r => r.SourceSearchStatus)
.ToDictionary(kv => kv.Key, kv => kv.Value);
var cursors = results
.Where(r => r.NextToken != null)
.ToDictionary(r => r.SourceSearchStatus.Single().Key, r => r.NextToken);
if (cursors.Keys.Any())
{
result.NextToken = new AggregatedContinuationToken
{
SearchString = searchText,
SourceSearchCursors = cursors
};
}
return result;
}
private void LogError(Task task, object state)
{
if (_logger == null)
{
// observe the task exception when no UI logger provided.
Trace.WriteLine(ExceptionUtilities.DisplayMessage(task.Exception));
return;
}
// UI logger only can be engaged from the main thread
MonoDevelop.Core.Runtime.RunInMainThread(() =>
{
var errorMessage = ExceptionUtilities.DisplayMessage(task.Exception);
_logger.Log(
ProjectManagement.MessageLevel.Error,
$"[{state.ToString()}] {errorMessage}");
});
}
}
}
<file_sep>//
// AggregatePackageSourceErrorMessage.cs
//
// Author:
// <NAME> <<EMAIL>>
//
// Copyright (c) 2016 Xamarin Inc. (http://xamarin.com)
//
// 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.
using System;
using System.Text;
using MonoDevelop.Core;
namespace MonoDevelop.PackageManagement
{
class AggregatePackageSourceErrorMessage
{
int totalPackageSources;
int failedPackageSourcesCount;
StringBuilder errorBuilder = new StringBuilder ();
public AggregatePackageSourceErrorMessage (int totalPackageSources)
{
this.totalPackageSources = totalPackageSources;
ErrorMessage = String.Empty;
}
public string ErrorMessage { get; private set; }
public void AddError (string message)
{
failedPackageSourcesCount++;
AppendErrorMessage (message);
if (!MultiplePackageSources) {
ErrorMessage = errorBuilder.ToString ();
} else if (AllFailed) {
ErrorMessage = GetAllPackageSourcesCouldNotBeReachedErrorMessage ();
} else {
ErrorMessage = GetSomePackageSourcesCouldNotBeReachedErrorMessage ();
}
}
bool MultiplePackageSources {
get { return totalPackageSources > 1; }
}
bool AllFailed {
get { return failedPackageSourcesCount >= totalPackageSources; }
}
void AppendErrorMessage (string message)
{
if (errorBuilder.Length == 0) {
errorBuilder.Append (message);
} else {
errorBuilder.AppendLine ();
errorBuilder.AppendLine ();
errorBuilder.Append (message);
}
}
string GetAllPackageSourcesCouldNotBeReachedErrorMessage ()
{
return GettextCatalog.GetString ("All package sources could not be reached.") +
Environment.NewLine +
errorBuilder.ToString ();
}
string GetSomePackageSourcesCouldNotBeReachedErrorMessage ()
{
return GettextCatalog.GetString ("Some package sources could not be reached.") +
Environment.NewLine +
errorBuilder.ToString ();
}
}
}
<file_sep>// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using NuGet.Common;
using NuGet.Protocol.Core.Types;
namespace NuGet.PackageManagement.UI
{
internal class PackageItemLoader : IItemLoader<PackageItemListViewModel>
{
private readonly PackageLoadContext _context;
private readonly string _searchText;
private readonly bool _includePrerelease;
private readonly IPackageFeed _packageFeed;
//private PackageCollection _installedPackages;
private SearchFilter SearchFilter => new SearchFilter
{
IncludePrerelease = _includePrerelease,
SupportedFrameworks = _context.GetSupportedFrameworks()
};
// Never null
private PackageFeedSearchState _state = new PackageFeedSearchState();
public IItemLoaderState State => _state;
public bool IsMultiSource => _packageFeed.IsMultiSource;
private class PackageFeedSearchState : IItemLoaderState
{
private readonly SearchResult<IPackageSearchMetadata> _results;
public PackageFeedSearchState()
{
}
public PackageFeedSearchState(SearchResult<IPackageSearchMetadata> results)
{
if (results == null)
{
throw new ArgumentNullException(nameof(results));
}
_results = results;
}
public SearchResult<IPackageSearchMetadata> Results => _results;
public LoadingStatus LoadingStatus
{
get
{
if (_results == null)
{
// initial status when no load called before
return LoadingStatus.Unknown;
}
return AggregateLoadingStatus(SourceLoadingStatus?.Values);
}
}
// returns the "raw" counter which is not the same as _results.Items.Count
// simply because it correlates to un-merged items
public int ItemsCount => _results?.RawItemsCount ?? 0;
public IDictionary<string, LoadingStatus> SourceLoadingStatus => _results?.SourceSearchStatus;
private static LoadingStatus AggregateLoadingStatus(IEnumerable<LoadingStatus> statuses)
{
var count = statuses?.Count() ?? 0;
if (count == 0)
{
return LoadingStatus.Loading;
}
var first = statuses.First();
if (count == 1 || statuses.All(x => x == first))
{
return first;
}
if (statuses.Contains(LoadingStatus.Loading))
{
return LoadingStatus.Loading;
}
if (statuses.Contains(LoadingStatus.ErrorOccurred))
{
return LoadingStatus.ErrorOccurred;
}
if (statuses.Contains(LoadingStatus.Cancelled))
{
return LoadingStatus.Cancelled;
}
if (statuses.Contains(LoadingStatus.Ready))
{
return LoadingStatus.Ready;
}
if (statuses.Contains(LoadingStatus.NoMoreItems))
{
return LoadingStatus.NoMoreItems;
}
if (statuses.Contains(LoadingStatus.NoItemsFound))
{
return LoadingStatus.NoItemsFound;
}
return first;
}
}
public PackageItemLoader(
PackageLoadContext context,
IPackageFeed packageFeed,
string searchText = null,
bool includePrerelease = true)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
_context = context;
if (packageFeed == null)
{
throw new ArgumentNullException(nameof(packageFeed));
}
_packageFeed = packageFeed;
_searchText = searchText ?? string.Empty;
_includePrerelease = includePrerelease;
}
public async Task<int> GetTotalCountAsync(int maxCount, CancellationToken cancellationToken)
{
// Go off the UI thread to perform non-UI operations
//await TaskScheduler.Default;
int totalCount = 0;
ContinuationToken nextToken = null;
do
{
var searchResult = await SearchAsync(nextToken, cancellationToken);
while (searchResult.RefreshToken != null)
{
searchResult = await _packageFeed.RefreshSearchAsync(searchResult.RefreshToken, cancellationToken);
}
totalCount += searchResult.Items?.Count() ?? 0;
nextToken = searchResult.NextToken;
} while (nextToken != null && totalCount <= maxCount);
return totalCount;
}
public async Task<IReadOnlyList<IPackageSearchMetadata>> GetAllPackagesAsync(CancellationToken cancellationToken)
{
// Go off the UI thread to perform non-UI operations
//await TaskScheduler.Default;
var packages = new List<IPackageSearchMetadata>();
ContinuationToken nextToken = null;
do
{
var searchResult = await SearchAsync(nextToken, cancellationToken);
while (searchResult.RefreshToken != null)
{
searchResult = await _packageFeed.RefreshSearchAsync(searchResult.RefreshToken, cancellationToken);
}
nextToken = searchResult.NextToken;
packages.AddRange(searchResult.Items);
} while (nextToken != null);
return packages;
}
public async Task LoadNextAsync(IProgress<IItemLoaderState> progress, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
NuGetEventTrigger.Instance.TriggerEvent(NuGetEvent.PackageLoadBegin);
var nextToken = _state.Results?.NextToken;
var cleanState = SearchResult.Empty<IPackageSearchMetadata>();
cleanState.NextToken = nextToken;
await UpdateStateAndReportAsync(cleanState, progress);
var searchResult = await SearchAsync(nextToken, cancellationToken);
cancellationToken.ThrowIfCancellationRequested();
await UpdateStateAndReportAsync(searchResult, progress);
NuGetEventTrigger.Instance.TriggerEvent(NuGetEvent.PackageLoadEnd);
}
public async Task UpdateStateAsync(IProgress<IItemLoaderState> progress, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
NuGetEventTrigger.Instance.TriggerEvent(NuGetEvent.PackageLoadBegin);
progress?.Report(_state);
var refreshToken = _state.Results?.RefreshToken;
if (refreshToken != null)
{
var searchResult = await _packageFeed.RefreshSearchAsync(refreshToken, cancellationToken);
cancellationToken.ThrowIfCancellationRequested();
await UpdateStateAndReportAsync(searchResult, progress);
}
NuGetEventTrigger.Instance.TriggerEvent(NuGetEvent.PackageLoadEnd);
}
private async Task<SearchResult<IPackageSearchMetadata>> SearchAsync(ContinuationToken continuationToken, CancellationToken cancellationToken)
{
if (continuationToken != null)
{
return await _packageFeed.ContinueSearchAsync(continuationToken, cancellationToken);
}
return await _packageFeed.SearchAsync(_searchText, SearchFilter, cancellationToken);
}
private async Task UpdateStateAndReportAsync(SearchResult<IPackageSearchMetadata> searchResult, IProgress<IItemLoaderState> progress)
{
// cache installed packages here for future use
//_installedPackages = await _context.GetInstalledPackagesAsync();
var state = new PackageFeedSearchState(searchResult);
_state = state;
progress?.Report(state);
}
public void Reset()
{
_state = new PackageFeedSearchState();
}
public IEnumerable<PackageItemListViewModel> GetCurrent()
{
if (_state.ItemsCount == 0)
{
return Enumerable.Empty<PackageItemListViewModel>();
}
var listItems = _state.Results
.Select(metadata =>
{
var listItem = new PackageItemListViewModel
{
Id = metadata.Identity.Id,
Version = metadata.Identity.Version,
IconUrl = metadata.IconUrl,
Author = metadata.Authors,
DownloadCount = metadata.DownloadCount,
Summary = metadata.Summary,
Description = metadata.Description,
Title = metadata.Title,
LicenseUrl = metadata.LicenseUrl,
ProjectUrl = metadata.ProjectUrl,
Published = metadata.Published,
Versions = AsyncLazy.New(() => metadata.GetVersionsAsync())
};
/*listItem.UpdatePackageStatus(_installedPackages);
if (!_context.IsSolution && _context.PackageManagerProviders.Any())
{
listItem.ProvidersLoader = AsyncLazy.New(
() => AlternativePackageManagerProviders.CalculateAlternativePackageManagersAsync(
_context.PackageManagerProviders,
listItem.Id,
_context.Projects[0]));
}*/
return listItem;
});
return listItems.ToArray();
}
}
}<file_sep>//
// AddPackagesDialog.UI.cs
//
// Author:
// <NAME> <<EMAIL>>
//
// Copyright (c) 2014 Xamarin Inc. (http://xamarin.com)
//
// 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.
using System;
using ExtendedTitleBarDialog = MonoDevelop.Components.ExtendedTitleBarDialog;
using MonoDevelop.Core;
using MonoDevelop.Ide;
using Xwt;
using Xwt.Drawing;
namespace MonoDevelop.PackageManagement
{
internal partial class AddPackagesDialog : ExtendedTitleBarDialog
{
ComboBox packageSourceComboBox;
SearchTextEntry packageSearchEntry;
ListView packagesListView;
VBox packageInfoVBox;
Label packageNameLabel;
LinkLabel packageIdLink;
Label packageDescription;
Label packageAuthor;
Label packagePublishedDate;
Label packageDownloads;
LinkLabel packageLicenseLink;
LinkLabel packageProjectPageLink;
Label packageDependenciesList;
HBox packageDependenciesHBox;
HBox packageDependenciesListHBox;
Label packageDependenciesNoneLabel;
CheckBox showPrereleaseCheckBox;
Label packageId;
Button addPackagesButton;
FrameBox loadingSpinnerFrame;
HBox errorMessageHBox;
Label errorMessageLabel;
Label loadingSpinnerLabel;
FrameBox noPackagesFoundFrame;
ComboBox packageVersionComboBox;
HBox packageVersionsHBox;
int packageInfoFontSize = 11;
void Build ()
{
Title = GettextCatalog.GetString ("Add Packages");
Width = 820;
Height = 520;
Padding = new WidgetSpacing ();
if (Platform.IsWindows) {
packageInfoFontSize = 9;
}
// Top part of dialog:
// Package sources and search.
var topHBox = new HBox ();
topHBox.Margin = new WidgetSpacing (8, 5, 6, 5);
packageSourceComboBox = new ComboBox ();
packageSourceComboBox.Name = "packageSourceComboBox";
packageSourceComboBox.MinWidth = 200;
topHBox.PackStart (packageSourceComboBox);
packageSearchEntry = new SearchTextEntry ();
packageSearchEntry.WidthRequest = 187;
topHBox.PackEnd (packageSearchEntry);
this.HeaderContent = topHBox;
// Middle of dialog:
// Packages and package information.
var mainVBox = new VBox ();
Content = mainVBox;
var middleHBox = new HBox ();
middleHBox.Spacing = 0;
var middleFrame = new FrameBox ();
middleFrame.Content = middleHBox;
middleFrame.BorderWidth = new WidgetSpacing (0, 0, 0, 1);
middleFrame.BorderColor = Styles.LineBorderColor;
mainVBox.PackStart (middleFrame, true, true);
// Error information.
var packagesListVBox = new VBox ();
packagesListVBox.Spacing = 0;
errorMessageHBox = new HBox ();
errorMessageHBox.Margin = new WidgetSpacing ();
errorMessageHBox.BackgroundColor = Styles.ErrorBackgroundColor;
errorMessageHBox.Visible = false;
var errorImage = new ImageView ();
errorImage.Margin = new WidgetSpacing (10, 0, 0, 0);
errorImage.Image = ImageService.GetIcon (MonoDevelop.Ide.Gui.Stock.Warning, Gtk.IconSize.Menu);
errorImage.HorizontalPlacement = WidgetPlacement.End;
errorMessageHBox.PackStart (errorImage);
errorMessageLabel = new Label ();
errorMessageLabel.TextColor = Styles.ErrorForegroundColor;
errorMessageLabel.Margin = new WidgetSpacing (5, 5, 5, 5);
errorMessageLabel.Wrap = WrapMode.Word;
errorMessageHBox.PackStart (errorMessageLabel, true);
packagesListVBox.PackStart (errorMessageHBox);
// Packages list.
middleHBox.PackStart (packagesListVBox, true, true);
packagesListView = new ListView ();
packagesListView.BorderVisible = false;
packagesListView.HeadersVisible = false;
packagesListVBox.PackStart (packagesListView, true, true);
// Loading spinner.
var loadingSpinnerHBox = new HBox ();
loadingSpinnerHBox.HorizontalPlacement = WidgetPlacement.Center;
var loadingSpinner = new Spinner ();
loadingSpinner.Animate = true;
loadingSpinner.MinWidth = 20;
loadingSpinnerHBox.PackStart (loadingSpinner);
loadingSpinnerLabel = new Label ();
loadingSpinnerLabel.Text = GettextCatalog.GetString ("Loading package list...");
loadingSpinnerHBox.PackEnd (loadingSpinnerLabel);
loadingSpinnerFrame = new FrameBox ();
loadingSpinnerFrame.Visible = false;
loadingSpinnerFrame.BackgroundColor = Styles.BackgroundColor;
loadingSpinnerFrame.Content = loadingSpinnerHBox;
loadingSpinnerFrame.BorderWidth = new WidgetSpacing ();
packagesListVBox.PackStart (loadingSpinnerFrame, true, true);
// No packages found label.
var noPackagesFoundHBox = new HBox ();
noPackagesFoundHBox.HorizontalPlacement = WidgetPlacement.Center;
var noPackagesFoundLabel = new Label ();
noPackagesFoundLabel.Text = GettextCatalog.GetString ("No matching packages found.");
noPackagesFoundHBox.PackEnd (noPackagesFoundLabel);
noPackagesFoundFrame = new FrameBox ();
noPackagesFoundFrame.Visible = false;
noPackagesFoundFrame.BackgroundColor = Styles.BackgroundColor;
noPackagesFoundFrame.Content = noPackagesFoundHBox;
noPackagesFoundFrame.BorderWidth = new WidgetSpacing ();
packagesListVBox.PackStart (noPackagesFoundFrame, true, true);
// Package information
packageInfoVBox = new VBox ();
var packageInfoFrame = new FrameBox ();
packageInfoFrame.BackgroundColor = Styles.PackageInfoBackgroundColor;
packageInfoFrame.BorderWidth = new WidgetSpacing ();
packageInfoFrame.Content = packageInfoVBox;
packageInfoVBox.Margin = new WidgetSpacing (15, 12, 15, 12);
var packageInfoContainerVBox = new VBox ();
packageInfoContainerVBox.WidthRequest = 240;
packageInfoContainerVBox.PackStart (packageInfoFrame, true, true);
var packageInfoScrollView = new ScrollView ();
packageInfoScrollView.BorderVisible = false;
packageInfoScrollView.HorizontalScrollPolicy = ScrollPolicy.Never;
packageInfoScrollView.Content = packageInfoContainerVBox;
packageInfoScrollView.BackgroundColor = Styles.PackageInfoBackgroundColor;
var packageInfoScrollViewFrame = new FrameBox ();
packageInfoScrollViewFrame.BackgroundColor = Styles.PackageInfoBackgroundColor;
packageInfoScrollViewFrame.BorderWidth = new WidgetSpacing (1, 0, 0, 0);
packageInfoScrollViewFrame.BorderColor = Styles.LineBorderColor;
packageInfoScrollViewFrame.Content = packageInfoScrollView;
// Package name and version.
var packageNameHBox = new HBox ();
packageInfoVBox.PackStart (packageNameHBox);
packageNameLabel = new Label ();
packageNameLabel.Ellipsize = EllipsizeMode.End;
Font packageInfoSmallFont = packageNameLabel.Font.WithSize (packageInfoFontSize);
packageNameLabel.Font = packageInfoSmallFont;
packageNameHBox.PackStart (packageNameLabel, true);
// Package description.
packageDescription = new Label ();
packageDescription.Wrap = WrapMode.Word;
packageDescription.Font = packageNameLabel.Font.WithSize (packageInfoFontSize);
packageDescription.BackgroundColor = Styles.PackageInfoBackgroundColor;
packageInfoVBox.PackStart (packageDescription);
// Package id.
var packageIdHBox = new HBox ();
packageIdHBox.MarginTop = 7;
packageInfoVBox.PackStart (packageIdHBox);
var packageIdLabel = new Label ();
packageIdLabel.Font = packageInfoSmallFont;
packageIdLabel.Markup = GettextCatalog.GetString ("<b>Id</b>");
packageIdHBox.PackStart (packageIdLabel);
packageId = new Label ();
packageId.Ellipsize = EllipsizeMode.End;
packageId.TextAlignment = Alignment.End;
packageId.Font = packageInfoSmallFont;
packageIdLink = new LinkLabel ();
packageIdLink.Ellipsize = EllipsizeMode.End;
packageIdLink.TextAlignment = Alignment.End;
packageIdLink.Font = packageInfoSmallFont;
packageIdHBox.PackEnd (packageIdLink, true);
packageIdHBox.PackEnd (packageId, true);
// Package author
var packageAuthorHBox = new HBox ();
packageInfoVBox.PackStart (packageAuthorHBox);
var packageAuthorLabel = new Label ();
packageAuthorLabel.Markup = GettextCatalog.GetString ("<b>Author</b>");
packageAuthorLabel.Font = packageInfoSmallFont;
packageAuthorHBox.PackStart (packageAuthorLabel);
packageAuthor = new Label ();
packageAuthor.TextAlignment = Alignment.End;
packageAuthor.Ellipsize = EllipsizeMode.End;
packageAuthor.Font = packageInfoSmallFont;
packageAuthorHBox.PackEnd (packageAuthor, true);
// Package published
var packagePublishedHBox = new HBox ();
packageInfoVBox.PackStart (packagePublishedHBox);
var packagePublishedLabel = new Label ();
packagePublishedLabel.Markup = GettextCatalog.GetString ("<b>Published</b>");
packagePublishedLabel.Font = packageInfoSmallFont;
packagePublishedHBox.PackStart (packagePublishedLabel);
packagePublishedDate = new Label ();
packagePublishedDate.Font = packageInfoSmallFont;
packagePublishedHBox.PackEnd (packagePublishedDate);
// Package downloads
var packageDownloadsHBox = new HBox ();
packageInfoVBox.PackStart (packageDownloadsHBox);
var packageDownloadsLabel = new Label ();
packageDownloadsLabel.Markup = GettextCatalog.GetString ("<b>Downloads</b>");
packageDownloadsLabel.Font = packageInfoSmallFont;
packageDownloadsHBox.PackStart (packageDownloadsLabel);
packageDownloads = new Label ();
packageDownloads.Font = packageInfoSmallFont;
packageDownloadsHBox.PackEnd (packageDownloads);
// Package license.
var packageLicenseHBox = new HBox ();
packageInfoVBox.PackStart (packageLicenseHBox);
var packageLicenseLabel = new Label ();
packageLicenseLabel.Markup = GettextCatalog.GetString ("<b>License</b>");
packageLicenseLabel.Font = packageInfoSmallFont;
packageLicenseHBox.PackStart (packageLicenseLabel);
packageLicenseLink = new LinkLabel ();
packageLicenseLink.Text = GettextCatalog.GetString ("View License");
packageLicenseLink.Font = packageInfoSmallFont;
packageLicenseHBox.PackEnd (packageLicenseLink);
// Package project page.
var packageProjectPageHBox = new HBox ();
packageInfoVBox.PackStart (packageProjectPageHBox);
var packageProjectPageLabel = new Label ();
packageProjectPageLabel.Markup = GettextCatalog.GetString ("<b>Project Page</b>");
packageProjectPageLabel.Font = packageInfoSmallFont;
packageProjectPageHBox.PackStart (packageProjectPageLabel);
packageProjectPageLink = new LinkLabel ();
packageProjectPageLink.Text = GettextCatalog.GetString ("Visit Page");
packageProjectPageLink.Font = packageInfoSmallFont;
packageProjectPageHBox.PackEnd (packageProjectPageLink);
// Package dependencies
packageDependenciesHBox = new HBox ();
packageInfoVBox.PackStart (packageDependenciesHBox);
var packageDependenciesLabel = new Label ();
packageDependenciesLabel.Markup = GettextCatalog.GetString ("<b>Dependencies</b>");
packageDependenciesLabel.Font = packageInfoSmallFont;
packageDependenciesHBox.PackStart (packageDependenciesLabel);
packageDependenciesNoneLabel = new Label ();
packageDependenciesNoneLabel.Text = GettextCatalog.GetString ("None");
packageDependenciesNoneLabel.Font = packageInfoSmallFont;
packageDependenciesHBox.PackEnd (packageDependenciesNoneLabel);
// Package dependencies list.
packageDependenciesListHBox = new HBox ();
packageDependenciesListHBox.Visible = false;
packageInfoVBox.PackStart (packageDependenciesListHBox);
packageDependenciesList = new Label ();
packageDependenciesList.Wrap = WrapMode.WordAndCharacter;
packageDependenciesList.Margin = new WidgetSpacing (5);
packageDependenciesList.Font = packageInfoSmallFont;
packageDependenciesListHBox.PackStart (packageDependenciesList, true);
// Package versions.
packageVersionsHBox = new HBox ();
packageVersionsHBox.Visible = false;
packageVersionsHBox.BackgroundColor = Styles.PackageInfoBackgroundColor;
packageVersionsHBox.Margin = new WidgetSpacing (15, 0, 15, 12);
var packageVersionsLabel = new Label ();
packageVersionsLabel.Font = packageInfoSmallFont;
packageVersionsLabel.Markup = GettextCatalog.GetString ("<b>Version</b>");
packageVersionsHBox.PackStart (packageVersionsLabel);
packageVersionComboBox = new ComboBox ();
packageVersionComboBox.Name = "packageVersionComboBox";
packageVersionsHBox.Spacing = 15;
packageVersionsHBox.PackStart (packageVersionComboBox, true, true);
var packageInfoAndVersionsVBox = new VBox ();
packageInfoAndVersionsVBox.Margin = new WidgetSpacing ();
packageInfoAndVersionsVBox.BackgroundColor = Styles.PackageInfoBackgroundColor;
packageInfoAndVersionsVBox.PackStart (packageInfoScrollViewFrame, true, true);
packageInfoAndVersionsVBox.PackStart (packageVersionsHBox, false, false);
middleHBox.PackEnd (packageInfoAndVersionsVBox);
// Bottom part of dialog:
// Show pre-release packages and Close/Add to Project buttons.
var bottomHBox = new HBox ();
bottomHBox.Margin = new WidgetSpacing (8, 5, 14, 10);
bottomHBox.Spacing = 5;
mainVBox.PackStart (bottomHBox);
showPrereleaseCheckBox = new CheckBox ();
showPrereleaseCheckBox.Label = GettextCatalog.GetString ("Show pre-release packages");
bottomHBox.PackStart (showPrereleaseCheckBox);
addPackagesButton = new Button ();
addPackagesButton.MinWidth = 120;
addPackagesButton.MinHeight = 25;
addPackagesButton.Label = GettextCatalog.GetString ("Add Package");
bottomHBox.PackEnd (addPackagesButton);
var closeButton = new Button ();
closeButton.MinWidth = 120;
closeButton.MinHeight = 25;
closeButton.Label = GettextCatalog.GetString ("Close");
closeButton.Clicked += (sender, e) => Close ();
bottomHBox.PackEnd (closeButton);
packageSearchEntry.SetFocus ();
packageInfoVBox.Visible = false;
}
}
}
<file_sep>//
// AddPackagesDialog.cs
//
// Author:
// <NAME> <<EMAIL>>
//
// Copyright (c) 2014 Xamarin Inc. (http://xamarin.com)
//
// 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.
using System;
using System.Collections.Generic;
using System.Linq;
using MonoDevelop.Core;
using MonoDevelop.Ide;
using MonoDevelop.Paket;
using MonoDevelop.Projects;
using NuGet.Versioning;
using Xwt;
using Xwt.Drawing;
using PropertyChangedEventArgs = System.ComponentModel.PropertyChangedEventArgs;
namespace MonoDevelop.PackageManagement
{
internal partial class AddPackagesDialog
{
public static readonly string AddPackageDependenciesTitle =
GettextCatalog.GetString ("Add NuGet Package Dependencies");
public static readonly string AddPackageReferencesTitle =
GettextCatalog.GetString ("Add NuGet Package References");
AllPackagesViewModel viewModel;
List<SourceRepositoryViewModel> packageSources;
DataField<bool> packageHasBackgroundColorField = new DataField<bool> ();
DataField<PackageSearchResultViewModel> packageViewModelField = new DataField<PackageSearchResultViewModel> ();
DataField<Image> packageImageField = new DataField<Image> ();
DataField<double> packageCheckBoxAlphaField = new DataField<double> ();
const double packageCheckBoxSemiTransarentAlpha = 0.6;
ListStore packageStore;
PackageCellView packageCellView;
TimeSpan searchDelayTimeSpan = TimeSpan.FromMilliseconds (500);
IDisposable searchTimer;
SourceRepositoryViewModel dummyPackageSourceRepresentingConfigureSettingsItem =
new SourceRepositoryViewModel (GettextCatalog.GetString ("Configure Sources..."));
ImageLoader imageLoader = new ImageLoader ();
bool loadingMessageVisible;
bool ignorePackageVersionChanges;
const string IncludePrereleaseUserPreferenceName = "NuGet.AddPackagesDialog.IncludePrerelease";
TimeSpan populatePackageVersionsDelayTimeSpan = TimeSpan.FromMilliseconds (500);
int packageVersionsAddedCount;
IDisposable populatePackageVersionsTimer;
const int MaxVersionsToPopulate = 100;
List<NuGetPackageToAdd> packagesToAdd = new List<NuGetPackageToAdd> ();
public AddPackagesDialog (
AllPackagesViewModel viewModel,
string title,
string initialSearch)
{
this.viewModel = viewModel;
Build ();
Title = title;
UpdatePackageSearchEntryWithInitialText (initialSearch);
InitializeListView ();
UpdateAddPackagesButton ();
ShowLoadingMessage ();
LoadViewModel (initialSearch);
this.showPrereleaseCheckBox.Clicked += ShowPrereleaseCheckBoxClicked;
this.packageSourceComboBox.SelectionChanged += PackageSourceChanged;
this.addPackagesButton.Clicked += AddPackagesButtonClicked;
this.packageSearchEntry.Changed += PackageSearchEntryChanged;
this.packageSearchEntry.Activated += PackageSearchEntryActivated;
this.packageVersionComboBox.SelectionChanged += PackageVersionChanged;
imageLoader.Loaded += ImageLoaded;
}
public bool ShowPreferencesForPackageSources { get; private set; }
public IEnumerable<NuGetPackageToAdd> PackagesToAdd {
get { return packagesToAdd; }
}
protected override void Dispose (bool disposing)
{
imageLoader.Loaded -= ImageLoaded;
imageLoader.Dispose ();
RemoveSelectedPackagePropertyChangedEventHandler ();
viewModel.PropertyChanged -= ViewModelPropertyChanged;
viewModel.Dispose ();
DisposeExistingTimer ();
DisposePopulatePackageVersionsTimer ();
packageStore.Clear ();
viewModel = null;
base.Dispose (disposing);
}
void UpdatePackageSearchEntryWithInitialText (string initialSearch)
{
packageSearchEntry.Text = initialSearch;
if (!String.IsNullOrEmpty (initialSearch)) {
packageSearchEntry.CursorPosition = initialSearch.Length;
}
}
public string SearchText {
get { return packageSearchEntry.Text; }
}
void InitializeListView ()
{
packageStore = new ListStore (packageHasBackgroundColorField, packageCheckBoxAlphaField, packageImageField, packageViewModelField);
packagesListView.DataSource = packageStore;
AddPackageCellViewToListView ();
packagesListView.SelectionChanged += PackagesListViewSelectionChanged;
packagesListView.RowActivated += PackagesListRowActivated;
packagesListView.VerticalScrollControl.ValueChanged += PackagesListViewScrollValueChanged;
}
void AddPackageCellViewToListView ()
{
packageCellView = new PackageCellView {
PackageField = packageViewModelField,
HasBackgroundColorField = packageHasBackgroundColorField,
CheckBoxAlphaField = packageCheckBoxAlphaField,
ImageField = packageImageField,
CellWidth = 535
};
var textColumn = new ListViewColumn ("Package", packageCellView);
packagesListView.Columns.Add (textColumn);
packageCellView.PackageChecked += PackageCellViewPackageChecked;
}
void ShowLoadingMessage ()
{
UpdateSpinnerLabel ();
noPackagesFoundFrame.Visible = false;
packagesListView.Visible = false;
loadingSpinnerFrame.Visible = true;
loadingMessageVisible = true;
}
void HideLoadingMessage ()
{
loadingSpinnerFrame.Visible = false;
packagesListView.Visible = true;
noPackagesFoundFrame.Visible = false;
loadingMessageVisible = false;
}
void UpdateSpinnerLabel ()
{
if (String.IsNullOrWhiteSpace (packageSearchEntry.Text)) {
loadingSpinnerLabel.Text = GettextCatalog.GetString ("Loading package list...");
} else {
loadingSpinnerLabel.Text = GettextCatalog.GetString ("Searching packages...");
}
}
void ShowNoPackagesFoundMessage ()
{
if (!String.IsNullOrWhiteSpace (packageSearchEntry.Text)) {
packagesListView.Visible = false;
noPackagesFoundFrame.Visible = true;
}
}
void ShowPrereleaseCheckBoxClicked (object sender, EventArgs e)
{
viewModel.IncludePrerelease = !viewModel.IncludePrerelease;
SaveIncludePrereleaseUserPreference ();
}
void SaveIncludePrereleaseUserPreference ()
{
Solution solution = IdeApp.ProjectOperations.CurrentSelectedSolution;
if (solution != null) {
if (viewModel.IncludePrerelease) {
solution.UserProperties.SetValue (IncludePrereleaseUserPreferenceName, viewModel.IncludePrerelease);
} else {
solution.UserProperties.RemoveValue (IncludePrereleaseUserPreferenceName);
}
solution.SaveUserProperties ();
}
}
bool GetIncludePrereleaseUserPreference ()
{
Solution solution = IdeApp.ProjectOperations.CurrentSelectedSolution;
if (solution != null) {
return solution.UserProperties.GetValue (IncludePrereleaseUserPreferenceName, false);
}
return false;
}
void LoadViewModel (string initialSearch)
{
viewModel.SearchTerms = initialSearch;
viewModel.IncludePrerelease = GetIncludePrereleaseUserPreference ();
showPrereleaseCheckBox.Active = viewModel.IncludePrerelease;
ClearSelectedPackageInformation ();
PopulatePackageSources ();
viewModel.PropertyChanged += ViewModelPropertyChanged;
if (viewModel.SelectedPackageSource != null) {
viewModel.ReadPackages ();
} else {
HideLoadingMessage ();
}
}
void ClearSelectedPackageInformation ()
{
this.packageInfoVBox.Visible = false;
this.packageVersionsHBox.Visible = false;
}
void RemoveSelectedPackagePropertyChangedEventHandler ()
{
if (viewModel.SelectedPackage != null) {
viewModel.SelectedPackage.PropertyChanged -= SelectedPackageViewModelChanged;
viewModel.SelectedPackage = null;
}
}
List<SourceRepositoryViewModel> PackageSources {
get {
if (packageSources == null) {
packageSources = viewModel.PackageSources.ToList ();
}
return packageSources;
}
}
void PopulatePackageSources ()
{
foreach (SourceRepositoryViewModel packageSource in PackageSources) {
AddPackageSourceToComboBox (packageSource);
}
AddPackageSourceToComboBox (dummyPackageSourceRepresentingConfigureSettingsItem);
packageSourceComboBox.SelectedItem = viewModel.SelectedPackageSource;
}
void AddPackageSourceToComboBox (SourceRepositoryViewModel packageSource)
{
packageSourceComboBox.Items.Add (packageSource, packageSource.Name);
}
void PackageSourceChanged (object sender, EventArgs e)
{
var selectedPackageSource = (SourceRepositoryViewModel)packageSourceComboBox.SelectedItem;
if (selectedPackageSource == dummyPackageSourceRepresentingConfigureSettingsItem) {
ShowPreferencesForPackageSources = true;
Close ();
} else {
viewModel.SelectedPackageSource = selectedPackageSource;
}
}
void PackagesListViewSelectionChanged (object sender, EventArgs e)
{
try {
ShowSelectedPackage ();
} catch (Exception ex) {
LoggingService.LogError ("Error showing selected package.", ex);
ShowErrorMessage (ex.Message);
}
}
void ShowSelectedPackage ()
{
RemoveSelectedPackagePropertyChangedEventHandler ();
PackageSearchResultViewModel packageViewModel = GetSelectedPackageViewModel ();
if (packageViewModel != null) {
ShowPackageInformation (packageViewModel);
} else {
ClearSelectedPackageInformation ();
}
viewModel.SelectedPackage = packageViewModel;
UpdateAddPackagesButton ();
}
PackageSearchResultViewModel GetSelectedPackageViewModel ()
{
if (packagesListView.SelectedRow != -1) {
return packageStore.GetValue (packagesListView.SelectedRow, packageViewModelField);
}
return null;
}
void ShowPackageInformation (PackageSearchResultViewModel packageViewModel)
{
this.packageNameLabel.Markup = packageViewModel.GetNameMarkup ();
this.packageAuthor.Text = packageViewModel.Author;
this.packagePublishedDate.Text = packageViewModel.GetLastPublishedDisplayText ();
this.packageDownloads.Text = packageViewModel.GetDownloadCountDisplayText ();
this.packageDescription.Text = packageViewModel.Description;
this.packageId.Text = packageViewModel.Id;
this.packageId.Visible = packageViewModel.HasNoGalleryUrl;
ShowUri (this.packageIdLink, packageViewModel.GalleryUrl, packageViewModel.Id);
ShowUri (this.packageProjectPageLink, packageViewModel.ProjectUrl);
ShowUri (this.packageLicenseLink, packageViewModel.LicenseUrl);
PopulatePackageDependencies (packageViewModel);
PopulatePackageVersions (packageViewModel);
this.packageInfoVBox.Visible = true;
this.packageVersionsHBox.Visible = true;
packageViewModel.PropertyChanged += SelectedPackageViewModelChanged;
viewModel.LoadPackageMetadata (packageViewModel);
}
void ShowUri (LinkLabel linkLabel, Uri uri, string label)
{
linkLabel.Text = label;
ShowUri (linkLabel, uri);
}
void ShowUri (LinkLabel linkLabel, Uri uri)
{
if (uri == null) {
linkLabel.Visible = false;
} else {
linkLabel.Visible = true;
linkLabel.Uri = uri;
}
}
void ViewModelPropertyChanged (object sender, PropertyChangedEventArgs e)
{
try {
ShowPackages ();
} catch (Exception ex) {
LoggingService.LogError ("Error showing packages.", ex);
ShowErrorMessage (ex.Message);
}
}
void ShowPackages ()
{
if (viewModel.HasError) {
ShowErrorMessage (viewModel.ErrorMessage);
} else {
ClearErrorMessage ();
}
if (viewModel.IsLoadingNextPage) {
// Show spinner?
} else if (viewModel.IsReadingPackages) {
ClearPackages ();
} else {
HideLoadingMessage ();
}
if (!viewModel.IsLoadingNextPage) {
AppendPackagesToListView ();
}
UpdateAddPackagesButton ();
}
void ClearPackages ()
{
packageStore.Clear ();
ResetPackagesListViewScroll ();
UpdatePackageListViewSelectionColor ();
ShowLoadingMessage ();
ShrinkImageCache ();
DisposePopulatePackageVersionsTimer ();
}
void ResetPackagesListViewScroll ()
{
packagesListView.VerticalScrollControl.Value = 0;
}
void ShowErrorMessage (string message)
{
errorMessageLabel.Text = message;
errorMessageHBox.Visible = true;
}
void ClearErrorMessage ()
{
errorMessageHBox.Visible = false;
errorMessageLabel.Text = "";
}
void ShrinkImageCache ()
{
imageLoader.ShrinkImageCache ();
}
void AppendPackagesToListView ()
{
bool packagesListViewWasEmpty = (packageStore.RowCount == 0);
for (int row = packageStore.RowCount; row < viewModel.PackageViewModels.Count; ++row) {
PackageSearchResultViewModel packageViewModel = viewModel.PackageViewModels [row];
AppendPackageToListView (packageViewModel);
LoadPackageImage (row, packageViewModel);
}
if (packagesListViewWasEmpty && (packageStore.RowCount > 0)) {
packagesListView.SelectRow (0);
}
if (!viewModel.IsReadingPackages && (packageStore.RowCount == 0)) {
ShowNoPackagesFoundMessage ();
}
}
void AppendPackageToListView (PackageSearchResultViewModel packageViewModel)
{
int row = packageStore.AddRow ();
packageStore.SetValue (row, packageHasBackgroundColorField, IsOddRow (row));
packageStore.SetValue (row, packageCheckBoxAlphaField, GetPackageCheckBoxAlpha ());
packageStore.SetValue (row, packageViewModelField, packageViewModel);
}
void LoadPackageImage (int row, PackageSearchResultViewModel packageViewModel)
{
if (packageViewModel.HasIconUrl) {
imageLoader.LoadFrom (packageViewModel.IconUrl, row);
}
}
bool IsOddRow (int row)
{
return (row % 2) == 0;
}
double GetPackageCheckBoxAlpha ()
{
if (PackagesCheckedCount == 0) {
return packageCheckBoxSemiTransarentAlpha;
}
return 1;
}
void ImageLoaded (object sender, ImageLoadedEventArgs e)
{
if (!e.HasError) {
int row = (int)e.State;
if (IsValidRowAndUrl (row, e.Uri)) {
packageStore.SetValue (row, packageImageField, e.Image);
}
}
}
bool IsValidRowAndUrl (int row, Uri uri)
{
if (row < packageStore.RowCount) {
PackageSearchResultViewModel packageViewModel = packageStore.GetValue (row, packageViewModelField);
if (packageViewModel != null) {
return uri == packageViewModel.IconUrl;
}
}
return false;
}
void AddPackagesButtonClicked (object sender, EventArgs e)
{
try {
packagesToAdd = GetPackagesToAdd ();
Close ();
} catch (Exception ex) {
LoggingService.LogError ("Adding packages failed.", ex);
ShowErrorMessage (ex.Message);
}
}
List<NuGetPackageToAdd> GetPackagesToAdd ()
{
List<PackageSearchResultViewModel> packageViewModels = GetSelectedPackageViewModels ();
if (packageViewModels.Count > 0) {
return GetPackagesToAdd (packageViewModels);
}
return new List<NuGetPackageToAdd> ();
}
List<PackageSearchResultViewModel> GetSelectedPackageViewModels ()
{
List<PackageSearchResultViewModel> packageViewModels = viewModel.CheckedPackageViewModels.ToList ();
if (packageViewModels.Count > 0) {
return packageViewModels;
}
PackageSearchResultViewModel selectedPackageViewModel = GetSelectedPackageViewModel ();
if (selectedPackageViewModel != null) {
packageViewModels.Add (selectedPackageViewModel);
}
return packageViewModels;
}
List<NuGetPackageToAdd> GetPackagesToAdd (IEnumerable<PackageSearchResultViewModel> packageViewModels)
{
return packageViewModels.Select (viewModel => new NuGetPackageToAdd (viewModel))
.ToList ();
}
void PackageSearchEntryChanged (object sender, EventArgs e)
{
ClearErrorMessage ();
ClearPackages ();
UpdateAddPackagesButton ();
SearchAfterDelay ();
}
void SearchAfterDelay ()
{
DisposeExistingTimer ();
searchTimer = Application.TimeoutInvoke (searchDelayTimeSpan, Search);
}
void DisposeExistingTimer ()
{
if (searchTimer != null) {
searchTimer.Dispose ();
}
}
bool Search ()
{
viewModel.SearchTerms = this.packageSearchEntry.Text;
viewModel.Search ();
return false;
}
void PackagesListRowActivated (object sender, ListViewRowEventArgs e)
{
if (PackagesCheckedCount > 0) {
AddPackagesButtonClicked (sender, e);
} else {
PackageSearchResultViewModel packageViewModel = packageStore.GetValue (e.RowIndex, packageViewModelField);
packagesToAdd = GetPackagesToAdd (new [] { packageViewModel });
Close ();
}
}
void PackageSearchEntryActivated (object sender, EventArgs e)
{
if (loadingMessageVisible)
return;
if (PackagesCheckedCount > 0) {
AddPackagesButtonClicked (sender, e);
} else {
PackageSearchResultViewModel selectedPackageViewModel = GetSelectedPackageViewModel ();
packagesToAdd = GetPackagesToAdd (new [] { selectedPackageViewModel });
Close ();
}
}
void PackagesListViewScrollValueChanged (object sender, EventArgs e)
{
if (viewModel.IsLoadingNextPage) {
return;
}
if (IsScrollBarNearEnd (packagesListView.VerticalScrollControl)) {
if (viewModel.HasNextPage) {
viewModel.ShowNextPage ();
}
}
}
bool IsScrollBarNearEnd (ScrollControl scrollControl)
{
double currentValue = scrollControl.Value;
double maxValue = scrollControl.UpperValue;
double pageSize = scrollControl.PageSize;
return (currentValue / (maxValue - pageSize)) > 0.7;
}
void PackageCellViewPackageChecked (object sender, PackageCellViewEventArgs e)
{
UpdateAddPackagesButton ();
UpdatePackageListViewSelectionColor ();
UpdatePackageListViewCheckBoxAlpha ();
}
void UpdateAddPackagesButton ()
{
string label = GettextCatalog.GetPluralString ("Add Package", "Add Packages", GetPackagesCountForAddPackagesButtonLabel ());
if (PackagesCheckedCount <= 1 && OlderPackageInstalledThanPackageSelected ()) {
label = GettextCatalog.GetString ("Update Package");
}
addPackagesButton.Label = label;
addPackagesButton.Sensitive = IsAddPackagesButtonEnabled ();
}
int GetPackagesCountForAddPackagesButtonLabel ()
{
if (PackagesCheckedCount > 1)
return PackagesCheckedCount;
return 1;
}
void UpdatePackageListViewSelectionColor ()
{
packageCellView.UseStrongSelectionColor = (PackagesCheckedCount == 0);
}
void UpdatePackageListViewCheckBoxAlpha ()
{
if (PackagesCheckedCount > 1)
return;
double alpha = GetPackageCheckBoxAlpha ();
for (int row = 0; row < packageStore.RowCount; ++row) {
packageStore.SetValue (row, packageCheckBoxAlphaField, alpha);
}
}
bool OlderPackageInstalledThanPackageSelected ()
{
if (PackagesCheckedCount != 0) {
return false;
}
PackageSearchResultViewModel selectedPackageViewModel = GetSelectedPackageViewModel ();
if (selectedPackageViewModel != null) {
return selectedPackageViewModel.IsOlderPackageInstalled ();
}
return false;
}
bool IsAddPackagesButtonEnabled ()
{
return !loadingMessageVisible && IsAtLeastOnePackageSelected ();
}
bool IsAtLeastOnePackageSelected ()
{
return (PackagesCheckedCount) >= 1 || (packagesListView.SelectedRow != -1);
}
int PackagesCheckedCount {
get { return viewModel.CheckedPackageViewModels.Count; }
}
void SelectedPackageViewModelChanged (object sender, PropertyChangedEventArgs e)
{
try {
if (e.PropertyName == "Versions") {
PopulatePackageVersions (viewModel.SelectedPackage);
} else {
packagePublishedDate.Text = viewModel.SelectedPackage.GetLastPublishedDisplayText ();
PopulatePackageDependencies (viewModel.SelectedPackage);
}
} catch (Exception ex) {
LoggingService.LogError ("Error loading package versions.", ex);
}
}
void PopulatePackageVersions (PackageSearchResultViewModel packageViewModel)
{
DisposePopulatePackageVersionsTimer ();
ignorePackageVersionChanges = true;
try {
packageVersionComboBox.Items.Clear ();
AddLatestPackageVersionToComboBox ();
if (packageViewModel.Versions.Any ()) {
int count = 0;
foreach (NuGetVersion version in packageViewModel.Versions) {
count++;
if (count > MaxVersionsToPopulate) {
packageVersionsAddedCount = count - 1;
if (version >= packageViewModel.SelectedVersion) {
AddPackageVersionToComboBox (packageViewModel.SelectedVersion);
}
PopulatePackageVersionsAfterDelay ();
break;
}
AddPackageVersionToComboBox (version);
}
} else {
AddPackageVersionToComboBox (packageViewModel.Version);
}
if (packageViewModel.IsLatestVersionSelected) {
SelectLatestPackageVersion ();
} else {
packageVersionComboBox.SelectedItem = packageViewModel.SelectedVersion;
}
} finally {
ignorePackageVersionChanges = false;
}
}
void AddPackageVersionToComboBox (NuGetVersion version)
{
packageVersionComboBox.Items.Add (version, version.ToString ());
}
void AddLatestPackageVersionToComboBox ()
{
var latestVersion = new LatestNuGetVersion ();
packageVersionComboBox.Items.Add (latestVersion, GettextCatalog.GetString ("Latest"));
}
void SelectLatestPackageVersion ()
{
packageVersionComboBox.SelectedItem = new LatestNuGetVersion ();
}
void PackageVersionChanged (object sender, EventArgs e)
{
if (ignorePackageVersionChanges || viewModel.SelectedPackage == null)
return;
viewModel.SelectedPackage.SelectedVersion = (NuGetVersion)packageVersionComboBox.SelectedItem;
UpdateAddPackagesButton ();
}
void PopulatePackageDependencies (PackageSearchResultViewModel packageViewModel)
{
if (packageViewModel.IsDependencyInformationAvailable) {
this.packageDependenciesHBox.Visible = true;
this.packageDependenciesListHBox.Visible = packageViewModel.HasDependencies;
this.packageDependenciesNoneLabel.Visible = !packageViewModel.HasDependencies;
this.packageDependenciesList.Text = packageViewModel.GetPackageDependenciesDisplayText ();
} else {
this.packageDependenciesHBox.Visible = false;
this.packageDependenciesListHBox.Visible = false;
this.packageDependenciesNoneLabel.Visible = false;
this.packageDependenciesList.Text = String.Empty;
}
}
void PopulatePackageVersionsAfterDelay ()
{
populatePackageVersionsTimer = Application.TimeoutInvoke (populatePackageVersionsDelayTimeSpan, PopulateMorePackageVersions);
}
void DisposePopulatePackageVersionsTimer ()
{
if (populatePackageVersionsTimer != null) {
populatePackageVersionsTimer.Dispose ();
populatePackageVersionsTimer = null;
}
}
bool PopulateMorePackageVersions ()
{
PackageSearchResultViewModel packageViewModel = viewModel?.SelectedPackage;
if (populatePackageVersionsTimer == null || packageViewModel == null) {
return false;
}
int count = 0;
foreach (NuGetVersion version in packageViewModel.Versions.Skip (packageVersionsAddedCount)) {
count++;
if (count > MaxVersionsToPopulate) {
packageVersionsAddedCount += count - 1;
return true;
}
AddPackageVersionToComboBox (version);
}
return false;
}
}
}<file_sep>// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using NuGet.Protocol.Core.Types;
namespace NuGet.PackageManagement.UI
{
/// <summary>
/// Most commonly used continuation token for plain package feeds.
/// </summary>
internal class FeedSearchContinuationToken : ContinuationToken
{
public int StartIndex { get; set; }
public string SearchString { get; set; }
public SearchFilter SearchFilter { get; set; }
}
}<file_sep>//
// OperationConsoleWrapper.cs
//
// Author:
// <NAME> <<EMAIL>>
//
// Copyright (c) 2017 Xamarin Inc. (http://xamarin.com)
//
// 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.
using System.IO;
using MonoDevelop.Core.Execution;
namespace MonoDevelop.Paket
{
public class OperationConsoleWrapper : OperationConsole
{
OperationConsole console;
WrappedTextWriter errorTextWriter;
public OperationConsoleWrapper (OperationConsole console)
{
this.console = console;
errorTextWriter = new WrappedTextWriter (console.Error);
}
public bool DisposeWrappedOperationConsole { get; set; }
public bool HasWrittenErrors {
get { return errorTextWriter.WasWritten; }
}
public override TextReader In {
get { return console.In; }
}
public override TextWriter Out {
get { return console.Out; }
}
public override TextWriter Error {
get { return errorTextWriter; }
}
public override TextWriter Log {
get { return console.Log; }
}
public override void Dispose ()
{
if (DisposeWrappedOperationConsole) {
console.Dispose ();
} else {
// Do not dispose. This prevents a null reference exception when the
// console is used after the external process has finished.
// The console will be disposed later on.
}
}
}
}
<file_sep>//
// SettingsLoader.cs
//
// Author:
// <NAME> <<EMAIL>>
//
// Copyright (c) 2016 Xamarin Inc. (http://xamarin.com)
//
// 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.
using System;
using System.Security.Cryptography;
using MonoDevelop.Core;
using NuGet.Configuration;
namespace MonoDevelop.PackageManagement
{
internal static class SettingsLoader
{
public static ISettings LoadDefaultSettings (bool reportError = false)
{
return LoadDefaultSettings (null, reportError);
}
public static ISettings LoadDefaultSettings (string rootDirectory, bool reportError = false)
{
try {
return Settings.LoadDefaultSettings (rootDirectory, null, null);
} catch (Exception ex) {
if (reportError) {
ShowReadNuGetConfigFileError (ex);
} else {
LoggingService.LogError ("Unable to load global NuGet.Config.", ex);
}
}
return NullSettings.Instance;
}
static void ShowReadNuGetConfigFileError (Exception ex)
{
Ide.MessageService.ShowError (
GettextCatalog.GetString ("Unable to read the NuGet.Config file"),
String.Format (GetReadNuGetConfigFileErrorMessage (ex),
ex.Message),
ex);
}
static string GetReadNuGetConfigFileErrorMessage (Exception ex)
{
if (ex is CryptographicException) {
return GettextCatalog.GetString ("Unable to decrypt passwords stored in the NuGet.Config file. The NuGet.Config file will be treated as read-only.");
}
return GettextCatalog.GetString ("An error occurred when trying to read the NuGet.Config file. The NuGet.Config file will be treated as read-only.\n\n{0}");
}
}
}
<file_sep>//
// SolutionPaketDependenciesNodeBuilderExtension.cs
//
// Author:
// <NAME> <<EMAIL>>
//
// Copyright (c) 2015 <NAME>
//
// 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.
//
using System;
using System.Collections.Generic;
using System.Linq;
using MonoDevelop.Ide.Gui.Components;
using MonoDevelop.Projects;
using MonoDevelop.Core;
using MonoDevelop.Ide;
namespace MonoDevelop.Paket.NodeBuilders
{
public class SolutionPaketDependenciesNodeBuilderExtension : NodeBuilderExtension
{
public SolutionPaketDependenciesNodeBuilderExtension ()
{
FileService.FileChanged += FileChanged;
}
public override void Dispose ()
{
FileService.FileChanged -= FileChanged;
}
public override bool CanBuildNode (Type dataType)
{
return typeof(Solution).IsAssignableFrom (dataType);
}
public override bool HasChildNodes (ITreeBuilder builder, object dataObject)
{
return SolutionHasDependencies (dataObject);
}
bool SolutionHasDependencies (object dataObject)
{
var solution = (Solution) dataObject;
return solution.HasPaketDependencies ();
}
public override void BuildChildNodes (ITreeBuilder treeBuilder, object dataObject)
{
var solution = (Solution)dataObject;
if (SolutionHasDependencies (solution)) {
treeBuilder.AddChild (new SolutionPaketDependenciesFolderNode (solution));
}
}
void FileChanged (object sender, FileEventArgs e)
{
List<FilePath> paketDependencyFiles = GetPaketDependencyFilesChanged (e).ToList ();
if (paketDependencyFiles.Any ()) {
RefreshAllChildNodes (paketDependencyFiles);
}
}
IEnumerable<FilePath> GetPaketDependencyFilesChanged (FileEventArgs fileEventArgs)
{
return fileEventArgs
.Where (file => file.FileName.IsPaketDependenciesFileName ())
.Select (file => file.FileName);
}
void RefreshAllChildNodes (ICollection<FilePath> dependencyFiles)
{
foreach (Solution solution in IdeApp.Workspace.GetAllSolutions ()) {
FilePath solutionPaketDependenciesFile = solution.GetPaketDependenciesFile ();
if (dependencyFiles.Any (file => file.Equals (solutionPaketDependenciesFile))) {
Context.UpdateChildrenFor (solution);
}
}
}
}
}
<file_sep>//
// PackageSearchCommands.cs
//
// Author:
// <NAME> <<EMAIL>>
//
// Copyright (c) 2015 <NAME>
//
// 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.
//
using System.Collections.Generic;
using System.Linq;
namespace MonoDevelop.Paket.Commands
{
public static class PaketSearchCommands
{
static IEnumerable<PaketSearchCommand> CreateCommands (string search)
{
return new PaketSearchCommand [] {
new PaketInitSearchCommand (),
new PaketInstallSearchCommand (),
new PaketUpdateSearchCommand (),
new PaketRestoreSearchCommand (),
new PaketAddNuGetSearchCommand (search),
new PaketRemoveNuGetSearchCommand (search),
new PaketUpdateNuGetSearchCommand (search),
new PaketSimplifySearchCommand (),
new PaketOutdatedSearchCommand (),
new PaketAddNuGetToProjectSearchCommand (search),
new PaketRemoveNuGetFromProjectSearchCommand (search),
new PaketConvertFromNuGetSearchCommand (),
new PaketAutoRestoreOnSearchCommand (),
new PaketAutoRestoreOffSearchCommand (),
};
}
public static IEnumerable<PaketSearchCommand> FilterCommands (string search)
{
var query = new PaketSearchCommandQuery (search);
query.Parse ();
if (query.IsPaketSearchCommand) {
return CreateCommands (search)
.Where (command => command.IsMatch (query));
}
return Enumerable.Empty <PaketSearchCommand> ();
}
}
}
|
9d286fec3f02499ababcb0c00704b407bba643e3
|
[
"Markdown",
"C#"
] | 62
|
C#
|
mrward/monodevelop-paket-addin
|
1623afb722655ee48f5187b1fc0c3c04f2b412da
|
ebaf457b9f408c9634a1ffbb58acd54a625fe41f
|
refs/heads/master
|
<file_sep>package com.example.jjong.lab6_3;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
EditText editText1, editText2;
ListView listView;
Button btnAdd,btnDel;
SQLiteDatabase db;
DBhelper helper;
String studentName,studentId;
String[]names;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
helper = new DBhelper(getApplicationContext(), "student.db", null, 3);
editText1=findViewById(R.id.name);
editText2=findViewById(R.id.id);
listView=findViewById(R.id.listView);
btnAdd=findViewById(R.id.buttonAdd);
btnDel=findViewById(R.id.buttonDelete);
btnAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(editText1.getText().toString().isEmpty()||editText2.getText().toString().isEmpty()){
Toast.makeText(getApplicationContext(),"Fill all of blank",Toast.LENGTH_LONG).show();
}else{
//add
studentName=editText1.getText().toString();
studentId=editText2.getText().toString();
insert(studentName,studentId);
invalidate();
}
}
});
btnDel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(editText1.getText().toString().isEmpty()&&editText2.getText().toString().isEmpty()){
Toast.makeText(getApplicationContext(),"Fill blank",Toast.LENGTH_LONG).show();
}else if(!editText1.getText().toString().isEmpty()&&editText2.getText().toString().isEmpty()){
studentName=editText1.getText().toString();
deleteName(studentName);
Toast.makeText(getApplicationContext(),"이름으로 삭제",Toast.LENGTH_LONG).show();
invalidate();
}
else if(editText1.getText().toString().isEmpty()&&!editText2.getText().toString().isEmpty()){
studentId=editText2.getText().toString();
deleteId(studentId);
Toast.makeText(getApplicationContext(),"id로 삭제",Toast.LENGTH_LONG).show();
invalidate();
}
else{
studentName=editText1.getText().toString();
deleteName(studentName);
Toast.makeText(getApplicationContext(),"이름으로 삭제",Toast.LENGTH_LONG).show();
invalidate();
}
}
});
}
@Override
public void onResume(){
super.onResume();
}
public void insert(String name, String id){
db=helper.getWritableDatabase();
ContentValues values=new ContentValues();
values.put("studentName",name);
values.put("studentId",id);
db.insert("student",null,values);
Log.i("db1", name + "정상적으로 삽입 되었습니다."+id);
}
public void deleteName (String name) {
db = helper.getWritableDatabase();
db.delete("student", "studentName=?", new String[]{name});
Log.i("db1", name + "정상적으로 삭제 되었습니다.");
}
public void deleteId (String id) {
db = helper.getWritableDatabase();
db.delete("student", "studentId=?", new String[]{id});
Log.i("db1", id + "정상적으로 삭제 되었습니다.");
}
public void select() {
db = helper.getReadableDatabase();
Cursor c = db.query("student", null, null, null, null, null, null);
names=new String[c.getCount()];
int count=0;
while (c.moveToNext()) {
String name = c.getString(c.getColumnIndex("studentName"));
String id = c.getString(c.getColumnIndex("studentId"));
names[count] =name+" "+id;
Log.i("db1", "name : " + name + ", id : " + id);
count++;
}
c.close();
}
private void invalidate(){
select();
ArrayAdapter <String> adapter=new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,names);
listView.setAdapter(adapter);
}
}
|
7ad2de5a82294ee0ffbb44c0f1815b4a905c2a64
|
[
"Java"
] | 1
|
Java
|
whdrjs/LAB6_3
|
2fd399c245865289064d56e62ab2f4efe515b5ad
|
ca4939e06d41407cd249dcedfee56ad9582c84eb
|
refs/heads/master
|
<repo_name>blaiseem/blaiseem.github.io<file_sep>/script_generate_index_files.py
import os
for root, dirs, files in os.walk(r".\charts"):
indexFileText = """{}\n<br>\n<br>\n\n""".format(root.split('\\')[-1].title())
for file in files:
if ('.html' in file) and ('index.html' not in file):
needIndex = True
indexFileText += """<a href="{}">{}</a>\n<br>\n""".format(file,file.replace('.html',''))
if needIndex:
fileHtml = open(root + '\\index.html','w')
fileHtml.write(indexFileText)
fileHtml.close()
print(root + '\\index.html')<file_sep>/README.md
# blaiseem.github.io
This is a repo used to store some static files that I am embedding as iframes in another website.
If interested, this website is https://www.aflalytics.com.
|
4165ef21b9bad3451f4034143070e15721cf45c6
|
[
"Markdown",
"Python"
] | 2
|
Python
|
blaiseem/blaiseem.github.io
|
f3ad29b9444789fe7666d235c414270545c785ae
|
1a52a54dd9d7812195367378f22834d1bb24cd27
|
refs/heads/master
|
<repo_name>gbejarano12/GeoQuiz<file_sep>/app/src/main/java/com/csci448/gbejaran/geoquiz/Question.java
package com.csci448.gbejaran.geoquiz;
/**
* Created by bajafresh12 on 1/19/18.
*/
public class Question {
int mTextResId;
boolean mAnswerTrue;
Question(int qNum, boolean ans){
mTextResId = qNum;
mAnswerTrue = ans;
}
boolean getAnswerTrue() {
return mAnswerTrue;
}
int getTextResId() {
return mTextResId;
}
void setAnswerTrue(boolean ans) {
mAnswerTrue = ans;
}
void setTextResId(int qNum) {
mTextResId = qNum;
}
}
<file_sep>/app/src/main/java/com/csci448/gbejaran/geoquiz/QuizActivity.java
package com.csci448.gbejaran.geoquiz;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import static android.view.Gravity.TOP;
import static android.widget.Toast.*;
public class QuizActivity extends AppCompatActivity {
private Button mTrueButton;
private Button mFalseButton;
private Button mNextButton;
private Button mCheatButton;
private TextView mQuestionView;
private int questionNum = 0;
private static final String TAG = "QuizActivity";
private static final String KEY_INDEX = "index";
private static final int REQUEST_CODE_CHEAT = 0;
private boolean mIsCheater;
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
Log.i(TAG, "onSaveInstanceState");
savedInstanceState.putInt(KEY_INDEX, questionNum);
}
private Question questions[] = new Question[] {
new Question(R.string.question_strikes, true),
new Question(R.string.question_zone, false),
new Question(R.string.question_foul, false),
new Question(R.string.question_bock, true),
new Question(R.string.question_jackie, true)
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
if (savedInstanceState != null) {
questionNum = savedInstanceState.getInt(KEY_INDEX, 0);
}
mQuestionView = (TextView) findViewById(R.id.question_view);
mQuestionView.setText(questions[questionNum].getTextResId());
mTrueButton = (Button) findViewById(R.id.true_button);
mTrueButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast toast;
if (mIsCheater) {
toast = Toast.makeText(QuizActivity.this,
"You Cheated!", LENGTH_SHORT);
} else {
if (questions[questionNum].getAnswerTrue() == true) {
toast = Toast.makeText(QuizActivity.this,
R.string.correct_toast,
LENGTH_SHORT);
} else {
toast = Toast.makeText(QuizActivity.this,
R.string.incorrect_toast,
LENGTH_SHORT);
}
}
toast.setGravity(Gravity.TOP, 10, 180);
toast.show();
}
});
mFalseButton = (Button) findViewById(R.id.false_button);
mFalseButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast toast;
if (mIsCheater) {
toast = Toast.makeText(QuizActivity.this,
"You Cheated!", LENGTH_SHORT);
} else {
if (questions[questionNum].getAnswerTrue() == false) {
toast = Toast.makeText(QuizActivity.this,
R.string.correct_toast,
LENGTH_SHORT);
} else {
toast = Toast.makeText(QuizActivity.this,
R.string.incorrect_toast,
LENGTH_SHORT);
}
}
toast.setGravity(Gravity.TOP, 10, 180);
toast.show();
}
});
mNextButton = (Button) findViewById(R.id.next_button);
mNextButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
questionNum++;
mIsCheater = false;
mQuestionView.setText(questions[questionNum].getTextResId());
}
});
mCheatButton = (Button) findViewById(R.id.cheat_button);
mCheatButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
boolean answerIsTrue = questions[questionNum].getAnswerTrue();
Intent intent = CheatActivity.newIntent(QuizActivity.this,
answerIsTrue);
startActivityForResult(intent, REQUEST_CODE_CHEAT);
}
});
mQuestionView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
questionNum++;
mQuestionView.setText(questions[questionNum].getTextResId());
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != Activity.RESULT_OK) {
return;
}
if (requestCode == REQUEST_CODE_CHEAT) {
if (data == null){
return;
}
mIsCheater = CheatActivity.wasAnswerShown(data);
}
}
}
|
90ba2e8eddc159677f9d5115d8462f199a21143c
|
[
"Java"
] | 2
|
Java
|
gbejarano12/GeoQuiz
|
28d65ccd47a35fa9d8a953503aa2377ea8101e03
|
8a9377637a11c81086975398b747ac98e0be91b7
|
refs/heads/master
|
<repo_name>zhiqiang-series/android-ui<file_sep>/ui-lib/src/main/java/com/coder/zzq/ui/IPlainViewHolder.java
package com.coder.zzq.ui;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.support.annotation.ColorInt;
import android.support.annotation.ColorRes;
import android.support.annotation.DrawableRes;
import android.support.annotation.IdRes;
import android.support.annotation.StringRes;
import android.view.View;
public interface IPlainViewHolder {
void setText(@IdRes int viewId, CharSequence text);
void setText(@IdRes int viewId, @StringRes int text);
void setImg(@IdRes int viewId, Drawable drawable);
void setImg(@IdRes int viewId, Bitmap bitmap);
void setImg(@IdRes int viewId, @DrawableRes int drawableRes);
ViewCaster getView(@IdRes int idRes);
View getViewAsPlain(@IdRes int idRes);
void setVisibility(@IdRes int viewId, int visibility);
View getRootViewAsPlain();
<T> T getRootViewAsTypeOf(Class<T> viewType);
Context getContext();
void setTextColorRes(int viewId, @ColorRes int colorRes);
void setTextColor(int viewId, @ColorInt int color);
String getText(int viewId);
}
<file_sep>/ui-lib/src/main/java/com/coder/zzq/ui/viewpager/SaveFragmentPagerAdapter.java
package com.coder.zzq.ui.viewpager;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
public abstract class SaveFragmentPagerAdapter extends FragmentPagerAdapter {
private List<Fragment> mFragments = new ArrayList<>();
private FragmentManager mFragmentManager;
public SaveFragmentPagerAdapter(FragmentManager fm, int fragmentCount, ViewPager viewPager) {
super(fm);
mFragmentManager = fm;
for (int index = 0; index < fragmentCount; index++) {
mFragments.add(null);
}
viewPager.setOffscreenPageLimit(fragmentCount);
}
@Override
public android.support.v4.app.Fragment getItem(int position) {
Fragment fragment = createFragmentIfNecessary(position);
mFragments.set(position, fragment);
return fragment;
}
public abstract Fragment createFragmentIfNecessary(int position);
@Override
public int getCount() {
return mFragments.size();
}
public List<Fragment> getFragments() {
return mFragments;
}
@Override
public Parcelable saveState() {
Bundle bundle = new Bundle();
for (int index = 0; index < mFragments.size(); index++) {
mFragmentManager.putFragment(bundle, getClass().getSimpleName() + index, mFragments.get(index));
}
mFragments.clear();
return bundle;
}
@Override
public void restoreState(Parcelable state, ClassLoader loader) {
mFragments.clear();
Bundle bundle = (Bundle) state;
bundle.setClassLoader(loader);
Set<String> keys = bundle.keySet();
for (String key : keys) {
Fragment fragment = mFragmentManager.getFragment(bundle, key);
int index = Integer.parseInt(key.substring(getClass().getSimpleName().length()));
while (mFragments.size() <= index) {
mFragments.add(null);
}
mFragments.set(index, fragment);
}
}
}
<file_sep>/ui-lib/src/main/java/com/coder/zzq/ui/viewpager/EmptyFragment.java
package com.coder.zzq.ui.viewpager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.coder.zzq.ui.R;
public class EmptyFragment extends Fragment {
private static final String ARG_TIP = "tip";
private Bundle mArgs;
private TextView mTipView;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mArgs = getArguments();
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.android_ui_fragment_empty_android_ui, container, false);
mTipView = view.findViewById(R.id.tip);
if (mArgs != null) {
mTipView.setText(mArgs.getString(ARG_TIP));
}
return view;
}
public static EmptyFragment newInstance(String tip) {
EmptyFragment emptyFragment = new EmptyFragment();
Bundle args = new Bundle();
args.putString(ARG_TIP, tip);
return emptyFragment;
}
}
<file_sep>/ui-lib/src/main/java/com/coder/zzq/ui/recyclerview/BaseRecyclerViewAdapter.java
package com.coder.zzq.ui.recyclerview;
import android.support.annotation.LayoutRes;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.coder.zzq.ui.R;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Created by 小朱先森 on 2018/5/7.
*/
public abstract class BaseRecyclerViewAdapter<HeaderData, BodyDataItem, FooterData> extends RecyclerView.Adapter<EasyViewHolder> {
public static final int ITEM_TYPE_HEADER = 0;
public static final int ITEM_TYPE_NORMAL_BODY = 1;
public static final int ITEM_TYPE_FOOTER = 2;
private HeaderData mHeaderData;
private List<BodyDataItem> mBodyData;
private FooterData mFooterData;
public BaseRecyclerViewAdapter() {
mBodyData = new ArrayList<>();
}
@LayoutRes
private int itemViewLayout(int viewType) {
switch (viewType) {
case ITEM_TYPE_HEADER:
return provideHeaderViewLayout();
case ITEM_TYPE_FOOTER:
return provideFooterViewLayout();
default:
return provideBodyViewLayout(viewType);
}
}
@LayoutRes
private int provideBodyViewLayout(int viewType) {
switch (viewType) {
case ITEM_TYPE_NORMAL_BODY:
return provideNormalBodyViewLayout();
default:
return provideSpecialBodyViewLayout(viewType);
}
}
@LayoutRes
protected int provideSpecialBodyViewLayout(int viewType) {
return R.layout.android_ui_empty_view;
}
@LayoutRes
protected abstract int provideNormalBodyViewLayout();
protected int provideFooterViewLayout() {
return R.layout.android_ui_empty_view;
}
@LayoutRes
protected int provideHeaderViewLayout() {
return R.layout.android_ui_empty_view;
}
@LayoutRes
protected int provideBodyViewType(int position) {
return ITEM_TYPE_NORMAL_BODY;
}
@Override
public int getItemViewType(int position) {
if (position == 0 && withHeader()) {
return ITEM_TYPE_HEADER;
} else if ((position == getItemCount() - 1) && withFooter()) {
return ITEM_TYPE_FOOTER;
} else {
return provideBodyViewType(position);
}
}
@Override
public EasyViewHolder onCreateViewHolder(ViewGroup parent, final int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(itemViewLayout(viewType), parent, false);
final EasyViewHolder viewHolder = new EasyViewHolder(itemView);
switch (viewType) {
case ITEM_TYPE_HEADER:
initHeaderView(viewHolder.itemView, viewHolder);
break;
case ITEM_TYPE_FOOTER:
initFooterView(viewHolder.itemView, viewHolder);
break;
default:
if (mOnBodyItemClickListener != null) {
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int globalPos = viewHolder.getAdapterPosition();
int bodyPos = withHeader() ? globalPos - 1 : globalPos;
mOnBodyItemClickListener.onBodyItemClick(viewHolder.itemView,
globalPos, bodyPos, mBodyData.get(bodyPos));
}
});
}
initBodyView(viewHolder.itemView, viewHolder, viewType);
break;
}
return viewHolder;
}
protected void initBodyView(View itemView, EasyViewHolder viewHolder, int viewType) {
}
protected void initFooterView(View footerView, EasyViewHolder viewHolder) {
}
protected void initHeaderView(View headerView, EasyViewHolder viewHolder) {
}
@Override
public void onBindViewHolder(EasyViewHolder holder, int position) {
if (position == 0 && withHeader()) {
if (mHeaderData != null) {
onBindHeaderData(holder, mHeaderData);
}
} else if (position == getItemCount() - 1 && withFooter()) {
if (mFooterData != null) {
onBindFooterData(holder, mFooterData);
}
} else {
bindBodyData(holder, position, getItemViewType(position));
}
}
private void bindBodyData(EasyViewHolder holder, int position, int viewType) {
int bodyPos = position;
if (withHeader()) {
bodyPos = position - 1;
}
onBindBodyData(holder, position, bodyPos, mBodyData.get(bodyPos), viewType);
}
protected abstract void onBindBodyData(EasyViewHolder holder, int globalPos, int bodyPos, BodyDataItem bodyDataItem, int itemType);
protected void onBindFooterData(EasyViewHolder viewHolder, FooterData footerData) {
}
protected void onBindHeaderData(EasyViewHolder viewHolder, HeaderData headerData) {
}
@Override
public int getItemCount() {
return mBodyData.size() + (withHeader() ? 1 : 0) + (withFooter() ? 1 : 0);
}
protected boolean withHeader() {
return false;
}
protected boolean withFooter() {
return false;
}
public HeaderData getHeaderData() {
return mHeaderData;
}
public void setHeaderData(HeaderData headerData) {
if (withHeader()) {
mHeaderData = headerData;
notifyItemChanged(0);
}
}
public List<BodyDataItem> getBodyData() {
return mBodyData;
}
public void setBodyData(List<BodyDataItem> bodyData) {
mBodyData.clear();
if (bodyData != null) {
mBodyData.addAll(bodyData);
}
notifyDataSetChanged();
}
public void setBodyData(BodyDataItem[] bodyData) {
List<BodyDataItem> bodyDataItems = bodyData == null ? null : Arrays.asList(bodyData);
setBodyData(bodyDataItems);
}
public void appendBodyData(List<BodyDataItem> bodyData) {
if (bodyData != null && !bodyData.isEmpty()) {
mBodyData.addAll(bodyData);
notifyItemRangeInserted(mBodyData.size(), bodyData.size());
}
}
public void appendBodyData(BodyDataItem[] bodyData) {
List<BodyDataItem> bodyDataItems = bodyData == null ? null : Arrays.asList(bodyData);
appendBodyData(bodyDataItems);
}
public FooterData getFooterData() {
return mFooterData;
}
public void setFooterData(FooterData footerData) {
if (withFooter()) {
mFooterData = footerData;
notifyItemChanged(getItemCount() - 1);
}
}
private OnItemClickListener<BodyDataItem> mOnBodyItemClickListener;
public void setOnBodyItemClickListener(OnItemClickListener<BodyDataItem> onBodyItemClickListener) {
mOnBodyItemClickListener = onBodyItemClickListener;
}
public interface OnItemClickListener<BodyDataItem> {
void onBodyItemClick(View itemView, int globalPos, int bodyPos, BodyDataItem bodyDataItem);
}
}
<file_sep>/README.md
# android-ui
Android UI 库。提供各种自定义View及常见View的功能封装,快速构建界面。
<file_sep>/ui-lib/src/main/java/com/coder/zzq/ui/recyclerview/EasyRefreshRecyclerView.java
package com.coder.zzq.ui.recyclerview;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.FrameLayout;
import com.aspsine.swipetoloadlayout.SwipeToLoadLayout;
import com.coder.zzq.ui.R;
public class EasyRefreshRecyclerView extends FrameLayout {
private SwipeToLoadLayout mRefresher;
private EasyRecyclerView mNestedRecyclerView;
public EasyRefreshRecyclerView(Context context) {
this(context, null);
}
public EasyRefreshRecyclerView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public EasyRefreshRecyclerView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
LayoutInflater.from(context).inflate(R.layout.android_ui_easy_refresh_recycler_view, this, true);
mRefresher = findViewById(R.id.nested_refresher);
mNestedRecyclerView = findViewById(R.id.swipe_target);
}
public SwipeToLoadLayout getRefresher() {
return mRefresher;
}
public EasyRecyclerView getRecyclerView() {
return mNestedRecyclerView;
}
}
<file_sep>/settings.gradle
include ':app', ':ui-lib'
|
d572ee2a3ac68a8771115acd1bceacce13c1c6bc
|
[
"Markdown",
"Java",
"Gradle"
] | 7
|
Java
|
zhiqiang-series/android-ui
|
9eaee76cc3452518bddeabf6e08cf155fe6ae1ae
|
7d3018f613bf3ca905861887bfabaac4caca561b
|
refs/heads/master
|
<repo_name>Caynosadler/cloudspend-expensify<file_sep>/src/main/java/com/cloudspend/accountingsystem/service/ExpensifyService.java
package com.cloudspend.accountingsystem.service;
import net.minidev.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import java.util.ArrayList;
@Service
public class ExpensifyService {
private String reportTemplate = "<#list reports as report><#list report.transactionList as expense><#if expense.modifiedMerchant?has_content><#assign merchant = expense.modifiedMerchant><#else><#assign merchant = expense.merchant></#if><#if expense.convertedAmount?has_content><#assign amount = expense.convertedAmount/100><#elseif expense.modifiedAmount?has_content><#assign amount = expense.modifiedAmount/100><#else><#assign amount = expense.amount/100></#if><#assign reciept = expense.receiptObject.url/100><#assign category = expense.category/100><#if expense.modifiedCreated?has_content><#assign created = expense.modifiedCreated><#else><#assign created = expense.created></#if>${merchant},<#t>${amount},<#t>${created},<#t>${expense.category}/n<#t></#list></#list>";
@Value("${expensify.endpoint}")
private String urlEndpoint;
@Autowired
private RestTemplate restTemplate;
private JSONObject credentials;
public ExpensifyService(){
credentials = new JSONObject();
credentials.appendField("partnerUserID", "aa_livecity505_gmail_com");
credentials.appendField("partnerUserSecret", "<KEY>");
}
public String getTransaction(String date){
ArrayList<String> immediateResponse = new ArrayList<>();
immediateResponse.add("returnRandomFileName");
JSONObject onReceive = new JSONObject()
.appendField("immediateResponse", immediateResponse);
JSONObject inputSettings = new JSONObject()
.appendField("type", "combinedReportData")
.appendField("filters", new JSONObject().appendField("startDate", date));
JSONObject outputSettings = new JSONObject()
.appendField("fileExtension", "json");
JSONObject requestBody = new JSONObject()
.appendField("type", "file")
.appendField("credentials", credentials)
.appendField("onReceive", onReceive)
.appendField("inputSettings", inputSettings)
.appendField("outputSettings", outputSettings);
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", MediaType.APPLICATION_FORM_URLENCODED_VALUE);
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("requestJobDescription", requestBody.toJSONString());
params.add("template", reportTemplate);
HttpEntity<?> entity = new HttpEntity<>(params, headers);
HttpEntity<String> response = restTemplate.exchange(
urlEndpoint,
HttpMethod.POST,
entity,
String.class
);
return downloadExportedReport(response.getBody());
}
private String downloadExportedReport(String filename){
JSONObject requestBody = new JSONObject();
requestBody.appendField("type", "download");
requestBody.appendField("credentials", credentials);
requestBody.appendField("fileName", filename);
requestBody.appendField("fileSystem", "integrationServer");
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", MediaType.APPLICATION_FORM_URLENCODED_VALUE);
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("requestJobDescription", requestBody.toJSONString());
HttpEntity<?> entity = new HttpEntity<>(params, headers);
HttpEntity<String> response = restTemplate.exchange(
urlEndpoint,
HttpMethod.POST,
entity,
String.class
);
return response.getBody();
}
}
<file_sep>/src/main/java/com/cloudspend/accountingsystem/dao/VendorRepository.java
package com.cloudspend.accountingsystem.dao;
import com.cloudspend.accountingsystem.model.Vendor;
import org.springframework.data.mongodb.repository.MongoRepository;
public interface VendorRepository extends MongoRepository<Vendor, String> {
boolean existsByName(String name);
Vendor getByName(String name);
}
<file_sep>/README.md
# cloudspend-expensify
Things to note:
1.) Mongodb is required on localhost to run this project. If Mongodb is running on a different server from the host system, change the address location in application.properties
2.) Each expense info is delimited by char "/n" specified in the report template schema
<file_sep>/src/main/resources/application.properties
spring.application.name = Cloud Spend Accounting System
expensify.endpoint = https://integrations.expensify.com/Integration-Server/ExpensifyIntegrations
expensify.partner.user.id = aa_livecity505_gmail_com
expensify.partner.user.secret = <KEY>
spring.data.mongodb.uri= mongodb://localhost:27017/transactions<file_sep>/src/test/java/com/cloudspend/accountingsystem/AccountingSystemApplicationTests.java
package com.cloudspend.accountingsystem;
import com.cloudspend.accountingsystem.service.Runner;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class AccountingSystemApplicationTests {
@Autowired
Runner runner;
@Test
void contextLoads() {
}
@Test
void testExpensify(){
runner.getVendorAndTransactionInfo();
System.out.println("done");
}
}
|
eb630bab5496e8dfbe63f25b165ccfc91ac35b29
|
[
"Markdown",
"Java",
"INI"
] | 5
|
Java
|
Caynosadler/cloudspend-expensify
|
f35cc8c45f03f2d4e69cd2f06cd631d38b14a94d
|
43ec476e162d1abdb599888d6992f0e551084e9e
|
refs/heads/master
|
<file_sep><?php
/**
* This script is used to setup the conditions needed for a
* performance script. Used on OS X to convert an image to a PDF (1:1
* conversion). This will convert all image files in a directory to
* corresponding PDFs.
*/
printf("Generating PDFs…\n");
$sourceDir = "./source-images";
$targetDir = "./source-pdfs";
$count = 0;
foreach (glob("$sourceDir/*.jpg") as $filename) {
$targetPath = "$targetDir/$count.pdf";
exec("convert $filename $targetPath");
$count += 1;
}
printf(" - $count pdfs generated\n\n");
<file_sep><?php
/**
* This script is used to generate some rough PDF zipping duration values
* for a research task on a Technical Design Document.
*/
printf("Zipping PDFs…\n");
unlink("./results.csv");
$compressionTests = [0, 5, 9];
$sourceDir = "./source-pdfs";
$pdfFileFilter = "$sourceDir/*.pdf";
$files = glob($pdfFileFilter);
// Determine how many iterations we need. We will increase by 2^i, where 'i' is a
// positive integer.
$fileCount = count($files);
$maxCount = ceil(log($fileCount, 2)) + 1;
// Create and append the first line of the results file.
appendToResultsFile("File Count, Compression, Duration (s), Average File Size (mb), Archive File Size (mb)");
// Iterate over all the compression levels we're interested in.
for ($i = 0; $i < count($compressionTests); $i++) {
$compression = $compressionTests[$i];
// Iterate over all the file counts we're interested in for a decent data set.
for ($j = 0; $j < $maxCount; $j++) {
$k = pow(2, $j);
// Bound to the max file count.
if ($k > $fileCount) {
$k = $fileCount;
}
$filesToProcess = array_slice($files, 0, $k);
processFiles($filesToProcess, $compression);
}
}
function appendToResultsFile($data) {
$appendData = $data.PHP_EOL;
file_put_contents("./results.csv", $appendData, FILE_APPEND);
}
function processFiles($files, $compression) {
$archiveName = "./archive.zip";
$totalFileSizeCount = 0;
if (file_exists($archiveName)) {
unlink($archiveName);
}
$startTime = microtime(true);
foreach ($files as $filename) {
$totalFileSizeCount += filesize($filename);
exec("zip -q -$compression $archiveName $filename");
}
$endTime = microtime(true);
$fileCount = count($files);
$averageFileSize = bytesToMegabytes($totalFileSizeCount / $fileCount);
$duration = round($endTime - $startTime, 4);
$archiveFileSize = bytesToMegabytes(filesize($archiveName));
appendToResultsFile("$fileCount, $compression, $duration, $averageFileSize, $archiveFileSize");
}
function bytesToMegabytes($bytes) {
return round($bytes / 1000 / 1000, 2);
}
|
bc3c7a8eba1c9b27427dcb5e3cefea9992583826
|
[
"PHP"
] | 2
|
PHP
|
dbrown428/tdd-zippdf-research
|
2024e608725ec03103da0b3d21b6a8caa174cdfe
|
450c89e7e59975f99354e440d3d07307ac1cc323
|
refs/heads/master
|
<repo_name>Red-French/HeroMe<file_sep>/app/src/main/java/net/redfrench/herome/Fragments/ChoosePowerFragment.java
package net.redfrench.herome.Fragments;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import net.redfrench.herome.Activities.MainActivity;
import net.redfrench.herome.R;
import static net.redfrench.herome.R.drawable.item_selected_btn;
import static net.redfrench.herome.R.drawable.lightning;
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link ChoosePowerFragment.ChoosePowerInteractionListener} interface
* to handle interaction events.
* Use the {@link ChoosePowerFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class ChoosePowerFragment extends Fragment implements View.OnClickListener {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private Button turtleBtn;
private Button lightningBtn;
private Button flightBtn;
private Button webBtn;
private Button laserBtn;
private Button strengthBtn;
private Button backstoryBtn;
int leftDrawable = 0;
private ChoosePowerInteractionListener mListener;
// ************************************************************************
// ************************************************************************
// ************************************************************************
public ChoosePowerFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment ChoosePowerFragment.
*/
// TODO: Rename and change types and number of parameters
public static ChoosePowerFragment newInstance(String param1, String param2) {
ChoosePowerFragment fragment = new ChoosePowerFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_choose_power, container, false);
turtleBtn = (Button)view.findViewById(R.id.turtleBtn);
lightningBtn = (Button)view.findViewById(R.id.lightningBtn);
flightBtn = (Button)view.findViewById(R.id.flightBtn);
webBtn = (Button)view.findViewById(R.id.webBtn);
laserBtn = (Button)view.findViewById(R.id.laserBtn);
strengthBtn = (Button)view.findViewById(R.id.strengthBtn);
backstoryBtn = (Button)view.findViewById(R.id.backstoryBtn);
turtleBtn.setOnClickListener(this); // finds the onClick listener that's part of this class (implemented in the class declaration above)
lightningBtn.setOnClickListener(this);
flightBtn.setOnClickListener(this);
webBtn.setOnClickListener(this);
laserBtn.setOnClickListener(this);
strengthBtn.setOnClickListener(this);
backstoryBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
MainActivity mainActivity = (MainActivity)getActivity();
mainActivity.loadBackstoryScreen();
}
});
// disable and dim 'Choose' button
backstoryBtn.setEnabled(false);
backstoryBtn.getBackground().setAlpha(128); // (255 would be 100% transparent)
// Inflate the layout for this fragment
return view;
}
@Override
public void onClick(View view) {
MainActivity mainActivity = (MainActivity)getActivity();
backstoryBtn.setEnabled(true);
backstoryBtn.getBackground().setAlpha(255);
Button btn = (Button)view; // cast the passed-in view into a button so methods can be performed on it
if (btn == turtleBtn) {
leftDrawable = R.drawable.turtlepower_icon;
lightningBtn.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.lightning_icon,0,0,0);
flightBtn.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.superman_crest,0,0,0);
webBtn.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.spider_web,0,0,0);
laserBtn.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.laservision_icon,0,0,0);
strengthBtn.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.superstrength_icon,0,0,0);
mainActivity.BACKSTORYHDR = "TURTLE POWER";
mainActivity.BACKSTORY = "The secret of turtle power lies in slowness; it's actually patience. Don't be fooled like the silly rabbit. This guy is a hard shell to crack.";
mainActivity.USERSPOWER = "Turtle Power";
mainActivity.WEAKNESS = " A soft underbelly. Gotta keep the sunny side up.";
} else if (btn == lightningBtn) {
turtleBtn.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.turtlepower_icon,0,0,0);
leftDrawable = R.drawable.lightning_icon;
flightBtn.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.superman_crest,0,0,0);
webBtn.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.spider_web,0,0,0);
laserBtn.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.laservision_icon,0,0,0);
strengthBtn.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.superstrength_icon,0,0,0);
mainActivity.BACKSTORYHDR = "LIGHTNING ~~";
mainActivity.BACKSTORY = "This is a story of lightning. I was struck with this power one sunny day.";
mainActivity.USERSPOWER = "Lightning";
mainActivity.WEAKNESS = "Weakness? Come on, it's LIGHTNING.";
} else if (btn == flightBtn) {
turtleBtn.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.turtlepower_icon,0,0,0);
lightningBtn.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.lightning_icon,0,0,0);
leftDrawable = R.drawable.superman_crest;
webBtn.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.spider_web,0,0,0);
laserBtn.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.laservision_icon,0,0,0);
strengthBtn.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.superstrength_icon,0,0,0);
mainActivity.BACKSTORYHDR = "FLIGHT";
mainActivity.BACKSTORY = "Maybe it came from the wRight Bros., but I just as soon keep my boots in the dirt.";
mainActivity.USERSPOWER = "Flight";
mainActivity.WEAKNESS = "Crashing. Crashing. CRASHING. (no thanks)";
} else if (btn == webBtn) {
turtleBtn.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.turtlepower_icon,0,0,0);
lightningBtn.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.lightning_icon,0,0,0);
flightBtn.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.superman_crest,0,0,0);
leftDrawable = R.drawable.spider_web;
laserBtn.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.laservision_icon,0,0,0);
strengthBtn.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.superstrength_icon,0,0,0);
mainActivity.BACKSTORYHDR = "WEB SLINGING";
mainActivity.BACKSTORY = "Well... what can I say? Spinnin' tall tales is my special power. 'nuff said.";
mainActivity.USERSPOWER = "Web Slinging";
mainActivity.WEAKNESS = "Getting caught. Quiet!";
} else if (btn == laserBtn) {
turtleBtn.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.turtlepower_icon,0,0,0);
lightningBtn.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.lightning_icon,0,0,0);
flightBtn.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.superman_crest,0,0,0);
webBtn.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.spider_web,0,0,0);
leftDrawable = R.drawable.laservision_icon;
strengthBtn.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.superstrength_icon,0,0,0);
mainActivity.BACKSTORYHDR = "LASER VISION";
mainActivity.BACKSTORY = "Walking out of a dimly-lit cafe, I bumped into the 6-million dollar man. Since then, well... you know.";
mainActivity.USERSPOWER = "Laser Vision";
mainActivity.WEAKNESS = "Sharp sticks to the orbital area of the skull.";
} else if (btn == strengthBtn) {
turtleBtn.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.turtlepower_icon,0,0,0);
lightningBtn.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.lightning_icon,0,0,0);
flightBtn.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.superman_crest,0,0,0);
webBtn.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.spider_web,0,0,0);
laserBtn.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.laservision_icon,0,0,0);
leftDrawable = R.drawable.superstrength_icon;
mainActivity.BACKSTORYHDR = "SUPER STRENGTH";
mainActivity.BACKSTORY = "Watching The Hulk weekly was great education on becoming strong. Just rip the shirt off.";
mainActivity.USERSPOWER = "Super Strength";
mainActivity.WEAKNESS = "Turning green. That part sucks, strong or not.";
}
// set 'drawableRight' property on button that's clicked
btn.setCompoundDrawablesWithIntrinsicBounds(leftDrawable,0, item_selected_btn,0); // (left, top, right, bottom)
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onChoosePowerFragmentInteraction(uri);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof ChoosePowerInteractionListener) {
mListener = (ChoosePowerInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement ChoosePowerInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface ChoosePowerInteractionListener {
// TODO: Update argument type and name
void onChoosePowerFragmentInteraction(Uri uri);
void onBackstoryFragmentInteraction(Uri uri);
}
}
<file_sep>/app/src/main/java/net/redfrench/herome/Fragments/BackstoryFragment.java
package net.redfrench.herome.Fragments;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import net.redfrench.herome.Activities.MainActivity;
import android.util.Log;
import net.redfrench.herome.R;
import org.w3c.dom.Text;
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link BackstoryFragment.BackstoryFragmentInteractionListener} interface
* to handle interaction events.
* Use the {@link BackstoryFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class BackstoryFragment extends Fragment implements View.OnClickListener {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private Button startOverBtn;
private BackstoryFragmentInteractionListener mListener;
// ************************************************************************
// ************************************************************************
// ************************************************************************
public BackstoryFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment BackstoryFragment.
*/
// TODO: Rename and change types and number of parameters
public static BackstoryFragment newInstance(String param1, String param2) {
BackstoryFragment fragment = new BackstoryFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_backstory, container, false);
MainActivity mainActivity = (MainActivity)getActivity();
String backStoryHdr = mainActivity.BACKSTORYHDR;
String backStory = mainActivity.BACKSTORY;
String usersPower = mainActivity.USERSPOWER;
String gotHow = mainActivity.HOWOBTAINED;
String weakness = mainActivity.WEAKNESS;
startOverBtn = (Button)view.findViewById(R.id.startOverBtn);
startOverBtn.setOnClickListener(this);
TextView hdr = (TextView) view.findViewById(R.id.backStoryHdr);
hdr.setText(backStoryHdr);
TextView story = (TextView) view.findViewById(R.id.backstoryText);
story.setText(backStory);
TextView power = (TextView) view.findViewById(R.id.usersPower);
power.setText(usersPower);
TextView howGot = (TextView) view.findViewById(R.id.howObtained);
howGot.setText(gotHow);
TextView weakStuff = (TextView) view.findViewById(R.id.weakText);
weakStuff.setText(weakness);
switch( backStoryHdr) {
case "TURTLE POWER":
story.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.turtle_power3x,0,0,0);
break;
case "LIGHTNING ~~":
story.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.lightning_icon,0,0,0);
break;
case "FLIGHT":
story.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.big_superman_logo,0,0,0);
break;
case "WEB SLINGING":
story.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.spiderweb3x,0,0,0);
break;
case "LASER VISION":
story.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.laservision3x,0,0,0);
break;
case "SUPER STRENGTH":
story.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.superstrength3x,0,0,0);
break;
};
// Inflate the layout for this fragment
return view;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onBackstoryFragmentInteraction(uri);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof BackstoryFragmentInteractionListener) {
mListener = (BackstoryFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement BackstoryFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
private static final String TAG = "MyActivity";
@Override
public void onClick(View view) {
Button btn = (Button)view; // cast the passed-in view into a button so methods can be performed on it
if (btn == startOverBtn) {
android.util.Log.i(TAG, "Click!");
MainActivity mainActivity = (MainActivity)getActivity();
mainActivity.loadMainScreen();
}
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface BackstoryFragmentInteractionListener {
// TODO: Update argument type and name
void onBackstoryFragmentInteraction(Uri uri);
}
}
<file_sep>/README.md
# Fragments
A Fragment represents a behavior or a portion of user interface in an Activity. You can combine multiple fragments in a single activity to build a multi-pane UI and reuse a fragment in multiple activities. You can think of a fragment as a modular section of an activity, which has its own lifecycle, receives its own input events, and which you can add or remove while the activity is running (sort of like a "sub activity" that you can reuse in different activities).
A fragment must always be embedded in an activity and the fragment's lifecycle is directly affected by the host activity's lifecycle. For example, when the activity is paused, so are all fragments in it, and when the activity is destroyed, so are all fragments. However, while an activity is running (it is in the resumed lifecycle state), you can manipulate each fragment independently, such as add or remove them. When you perform such a fragment transaction, you can also add it to a back stack that's managed by the activity—each back stack entry in the activity is a record of the fragment transaction that occurred. The back stack allows the user to reverse a fragment transaction (navigate backwards), by pressing the Back button.
1. When you add a fragment as a part of your activity layout, it lives in a ViewGroup inside the activity's view hierarchy and the fragment defines its own view layout.
2. You can insert a fragment into your activity layout by declaring the fragment in the activity's layout file, as a <fragment> element, or from your application code by adding it to an existing ViewGroup.
3. However, a fragment is not required to be a part of the activity layout; you may also use a fragment without its own UI as an invisible worker for the activity.
This document describes how to build your application to use fragments, including how fragments can maintain their state when added to the activity's back stack, share events with the activity and other fragments in the activity, contribute to the activity's action bar, and more.
## Design Philosophy
Android introduced fragments in Android 3.0 (API level 11), primarily to support more dynamic and flexible UI designs on large screens, such as tablets. Because a tablet's screen is much larger than that of a handset, there's more room to combine and interchange UI components. Fragments allow such designs without the need for you to manage complex changes to the view hierarchy. By dividing the layout of an activity into fragments, you become able to modify the activity's appearance at runtime and preserve those changes in a back stack that's managed by the activity.
For example, a news application can use one fragment to show a list of articles on the left and another fragment to display an article on the right—both fragments appear in one activity, side by side, and each fragment has its own set of lifecycle callback methods and handle their own user input events. Thus, instead of using one activity to select an article and another activity to read the article, the user can select an article and read it all within the same activity, as illustrated in the tablet layout in figure 1.
You should design each fragment as a modular and reusable activity component. That is, because each fragment defines its own layout and its own behavior with its own lifecycle callbacks, you can include one fragment in multiple activities, so you should design for reuse and avoid directly manipulating one fragment from another fragment. This is especially important because a modular fragment allows you to change your fragment combinations for different screen sizes. When designing your application to support both tablets and handsets, you can reuse your fragments in different layout configurations to optimize the user experience based on the available screen space. For example, on a handset, it might be necessary to separate fragments to provide a single-pane UI when more than one cannot fit within the same activity.
Figure 1. An example of how two UI modules defined by fragments can be combined into one activity for a tablet design, but separated for a handset design.
For example—to continue with the news application example—the application can embed two fragments in Activity A, when running on a tablet-sized device. However, on a handset-sized screen, there's not enough room for both fragments, so Activity A includes only the fragment for the list of articles, and when the user selects an article, it starts Activity B, which includes the second fragment to read the article. Thus, the application supports both tablets and handsets by reusing fragments in different combinations, as illustrated in figure 1.
For more information about designing your application with different fragment combinations for different screen configurations, see the guide to Supporting Tablets and Handsets.
## Creating a Fragment
Figure 2. The lifecycle of a fragment (while its activity is running).
To create a fragment, you must create a subclass of Fragment (or an existing subclass of it). The Fragment class has code that looks a lot like an Activity. It contains callback methods similar to an activity, such as onCreate(), onStart(), onPause(), and onStop(). In fact, if you're converting an existing Android application to use fragments, you might simply move code from your activity's callback methods into the respective callback methods of your fragment.
Usually, you should implement at least the following lifecycle methods:
onCreate()
The system calls this when creating the fragment. Within your implementation, you should initialize essential components of the fragment that you want to retain when the fragment is paused or stopped, then resumed.
onCreateView()
The system calls this when it's time for the fragment to draw its user interface for the first time. To draw a UI for your fragment, you must return a View from this method that is the root of your fragment's layout. You can return null if the fragment does not provide a UI.
onPause()
The system calls this method as the first indication that the user is leaving the fragment (though it does not always mean the fragment is being destroyed). This is usually where you should commit any changes that should be persisted beyond the current user session (because the user might not come back).
Most applications should implement at least these three methods for every fragment, but there are several other callback methods you should also use to handle various stages of the fragment lifecycle. All the lifecycle callback methods are discussed in more detail in the section about Handling the Fragment Lifecycle.
There are also a few subclasses that you might want to extend, instead of the base Fragment class:
#### DialogFragment
Displays a floating dialog. Using this class to create a dialog is a good alternative to using the dialog helper methods in the Activity class, because you can incorporate a fragment dialog into the back stack of fragments managed by the activity, allowing the user to return to a dismissed fragment.
#### ListFragment
Displays a list of items that are managed by an adapter (such as a SimpleCursorAdapter), similar to ListActivity. It provides several methods for managing a list view, such as the onListItemClick() callback to handle click events.
#### PreferenceFragment
Displays a hierarchy of Preference objects as a list, similar to PreferenceActivity. This is useful when creating a "settings" activity for your application.
## Adding a user interface
A fragment is usually used as part of an activity's user interface and contributes its own layout to the activity.
To provide a layout for a fragment, you must implement the onCreateView() callback method, which the Android system calls when it's time for the fragment to draw its layout. Your implementation of this method must return a View that is the root of your fragment's layout.
Note: If your fragment is a subclass of ListFragment, the default implementation returns a ListView from onCreateView(), so you don't need to implement it.
To return a layout from onCreateView(), you can inflate it from a layout resource defined in XML. To help you do so, onCreateView() provides a LayoutInflater object.
For example, here's a subclass of Fragment that loads a layout from the example_fragment.xml file:
public static class ExampleFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.example_fragment, container, false);
}
}
Creating a layout
In the sample above, R.layout.example_fragment is a reference to a layout resource named example_fragment.xml saved in the application resources. For information about how to create a layout in XML, see the User Interface documentation.
The container parameter passed to onCreateView() is the parent ViewGroup (from the activity's layout) in which your fragment layout will be inserted. The savedInstanceState parameter is a Bundle that provides data about the previous instance of the fragment, if the fragment is being resumed (restoring state is discussed more in the section about Handling the Fragment Lifecycle).
The inflate() method takes three arguments:
* The resource ID of the layout you want to inflate.
* The ViewGroup to be the parent of the inflated layout. Passing the container is important in order for the system to apply layout parameters to the root view of the inflated layout, specified by the parent view in which it's going.
* A boolean indicating whether the inflated layout should be attached to the ViewGroup (the second parameter) during inflation. (In this case, this is false because the system is already inserting the inflated layout into the container—passing true would create a redundant view group in the final layout.)
Now you've seen how to create a fragment that provides a layout. Next, you need to add the fragment to your activity.
## Adding a fragment to an activity
Usually, a fragment contributes a portion of UI to the host activity, which is embedded as a part of the activity's overall view hierarchy. There are two ways you can add a fragment to the activity layout:
* Declare the fragment inside the activity's layout file.
In this case, you can specify layout properties for the fragment as if it were a view. For example, here's the layout file for an activity with two fragments:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment android:name="com.example.news.ArticleListFragment"
android:id="@+id/list"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent" />
<fragment android:name="com.example.news.ArticleReaderFragment"
android:id="@+id/viewer"
android:layout_weight="2"
android:layout_width="0dp"
android:layout_height="match_parent" />
</LinearLayout>
The android:name attribute in the <fragment> specifies the Fragment class to instantiate in the layout.
When the system creates this activity layout, it instantiates each fragment specified in the layout and calls the onCreateView() method for each one, to retrieve each fragment's layout. The system inserts the View returned by the fragment directly in place of the <fragment> element.
Note: Each fragment requires a unique identifier that the system can use to restore the fragment if the activity is restarted (and which you can use to capture the fragment to perform transactions, such as remove it). There are three ways to provide an ID for a fragment:
* Supply the android:id attribute with a unique ID.
* Supply the android:tag attribute with a unique string.
* If you provide neither of the previous two, the system uses the ID of the container view.
* Or, programmatically add the fragment to an existing ViewGroup.
At any time while your activity is running, you can add fragments to your activity layout. You simply need to specify a ViewGroup in which to place the fragment.
To make fragment transactions in your activity (such as add, remove, or replace a fragment), you must use APIs from FragmentTransaction. You can get an instance of FragmentTransaction from your Activity like this:
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
You can then add a fragment using the add() method, specifying the fragment to add and the view in which to insert it. For example:
ExampleFragment fragment = new ExampleFragment();
fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.commit();
The first argument passed to add() is the ViewGroup in which the fragment should be placed, specified by resource ID, and the second parameter is the fragment to add.
Once you've made your changes with FragmentTransaction, you must call commit() for the changes to take effect.
Adding a fragment without a UI
The examples above show how to add a fragment to your activity in order to provide a UI. However, you can also use a fragment to provide a background behavior for the activity without presenting additional UI.
To add a fragment without a UI, add the fragment from the activity using add(Fragment, String) (supplying a unique string "tag" for the fragment, rather than a view ID). This adds the fragment, but, because it's not associated with a view in the activity layout, it does not receive a call to onCreateView(). So you don't need to implement that method.
Supplying a string tag for the fragment isn't strictly for non-UI fragments—you can also supply string tags to fragments that do have a UI—but if the fragment does not have a UI, then the string tag is the only way to identify it. If you want to get the fragment from the activity later, you need to use findFragmentByTag().
For an example activity that uses a fragment as a background worker, without a UI, see the FragmentRetainInstance.java sample, which is included in the SDK samples (available through the Android SDK Manager) and located on your system as <sdk_root>/APIDemos/app/src/main/java/com/example/android/apis/app/FragmentRetainInstance.java.
## Managing Fragments
To manage the fragments in your activity, you need to use FragmentManager. To get it, call getFragmentManager() from your activity.
Some things that you can do with FragmentManager include:
* Get fragments that exist in the activity, with findFragmentById() (for fragments that provide a UI in the activity layout) or findFragmentByTag() (for fragments that do or don't provide a UI).
* Pop fragments off the back stack, with popBackStack() (simulating a Back command by the user).
* Register a listener for changes to the back stack, with addOnBackStackChangedListener().
For more information about these methods and others, refer to the FragmentManager class documentation.
As demonstrated in the previous section, you can also use FragmentManager to open a FragmentTransaction, which allows you to perform transactions, such as add and remove fragments.
## Performing Fragment Transactions
A great feature about using fragments in your activity is the ability to add, remove, replace, and perform other actions with them, in response to user interaction. Each set of changes that you commit to the activity is called a transaction and you can perform one using APIs in FragmentTransaction. You can also save each transaction to a back stack managed by the activity, allowing the user to navigate backward through the fragment changes (similar to navigating backward through activities).
You can acquire an instance of FragmentTransaction from the FragmentManager like this:
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Each transaction is a set of changes that you want to perform at the same time. You can set up all the changes you want to perform for a given transaction using methods such as add(), remove(), and replace(). Then, to apply the transaction to the activity, you must call commit().
Before you call commit(), however, you might want to call addToBackStack(), in order to add the transaction to a back stack of fragment transactions. This back stack is managed by the activity and allows the user to return to the previous fragment state, by pressing the Back button.
For example, here's how you can replace one fragment with another, and preserve the previous state in the back stack:
// Create new fragment and transaction
Fragment newFragment = new ExampleFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
In this example, newFragment replaces whatever fragment (if any) is currently in the layout container identified by the R.id.fragment_container ID. By calling addToBackStack(), the replace transaction is saved to the back stack so the user can reverse the transaction and bring back the previous fragment by pressing the Back button.
To retrieve fragments from the back stack, you must override onBackPressed() in the main activity class:
@Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}
If you don't override onBackPressed() and there is a previous activity on the back stack, pressing the Back button causes the app to return to that activity; if there is no previous activity, pressing Back causes the app to close.
If you add multiple changes to the transaction (such as another add() or remove()) and call addToBackStack(), then all changes applied before you call commit() are added to the back stack as a single transaction and the Back button will reverse them all together.
The order in which you add changes to a FragmentTransaction doesn't matter, except:
* You must call commit() last
* If you're adding multiple fragments to the same container, then the order in which you add them determines the order they appear in the view hierarchy
If you do not call addToBackStack() when you perform a transaction that removes a fragment, then that fragment is destroyed when the transaction is committed and the user cannot navigate back to it. Whereas, if you do call addToBackStack() when removing a fragment, then the fragment is stopped and will be resumed if the user navigates back.
Tip: For each fragment transaction, you can apply a transition animation, by calling setTransition() before you commit.
Calling commit() does not perform the transaction immediately. Rather, it schedules it to run on the activity's UI thread (the "main" thread) as soon as the thread is able to do so. If necessary, however, you may call executePendingTransactions() from your UI thread to immediately execute transactions submitted by commit(). Doing so is usually not necessary unless the transaction is a dependency for jobs in other threads.
Caution: You can commit a transaction using commit() only prior to the activity saving its state (when the user leaves the activity). If you attempt to commit after that point, an exception will be thrown. This is because the state after the commit can be lost if the activity needs to be restored. For situations in which its okay that you lose the commit, use commitAllowingStateLoss().
## Communicating with the Activity
Although a Fragment is implemented as an object that's independent from an Activity and can be used inside multiple activities, a given instance of a fragment is directly tied to the activity that contains it.
Specifically, the fragment can access the Activity instance with getActivity() and easily perform tasks such as find a view in the activity layout:
View listView = getActivity().findViewById(R.id.list);
Likewise, your activity can call methods in the fragment by acquiring a reference to the Fragment from FragmentManager, using findFragmentById() or findFragmentByTag(). For example:
ExampleFragment fragment = (ExampleFragment) getFragmentManager().findFragmentById(R.id.example_fragment);
## Creating event callbacks to the activity
In some cases, you might need a fragment to share events with the activity. A good way to do that is to define a callback interface inside the fragment and require that the host activity implement it. When the activity receives a callback through the interface, it can share the information with other fragments in the layout as necessary.
For example, if a news application has two fragments in an activity—one to show a list of articles (fragment A) and another to display an article (fragment B)—then fragment A must tell the activity when a list item is selected so that it can tell fragment B to display the article. In this case, the OnArticleSelectedListener interface is declared inside fragment A:
public static class FragmentA extends ListFragment {
...
// Container Activity must implement this interface
public interface OnArticleSelectedListener {
public void onArticleSelected(Uri articleUri);
}
...
}
Then the activity that hosts the fragment implements the OnArticleSelectedListener interface and overrides onArticleSelected() to notify fragment B of the event from fragment A. To ensure that the host activity implements this interface, fragment A's onAttach() callback method (which the system calls when adding the fragment to the activity) instantiates an instance of OnArticleSelectedListener by casting the Activity that is passed into onAttach():
public static class FragmentA extends ListFragment {
OnArticleSelectedListener mListener;
...
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnArticleSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement OnArticleSelectedListener");
}
}
...
}
If the activity has not implemented the interface, then the fragment throws a ClassCastException. On success, the mListener member holds a reference to activity's implementation of OnArticleSelectedListener, so that fragment A can share events with the activity by calling methods defined by the OnArticleSelectedListener interface. For example, if fragment A is an extension of ListFragment, each time the user clicks a list item, the system calls onListItemClick() in the fragment, which then calls onArticleSelected() to share the event with the activity:
public static class FragmentA extends ListFragment {
OnArticleSelectedListener mListener;
...
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
// Append the clicked item's row ID with the content provider Uri
Uri noteUri = ContentUris.withAppendedId(ArticleColumns.CONTENT_URI, id);
// Send the event and Uri to the host activity
mListener.onArticleSelected(noteUri);
}
...
}
The id parameter passed to onListItemClick() is the row ID of the clicked item, which the activity (or other fragment) uses to fetch the article from the application's ContentProvider.
More information about using a content provider is available in the Content Providers document.
## Adding items to the App Bar
Your fragments can contribute menu items to the activity's Options Menu (and, consequently, the app bar) by implementing onCreateOptionsMenu(). In order for this method to receive calls, however, you must call setHasOptionsMenu() during onCreate(), to indicate that the fragment would like to add items to the Options Menu (otherwise, the fragment will not receive a call to onCreateOptionsMenu()).
Any items that you then add to the Options Menu from the fragment are appended to the existing menu items. The fragment also receives callbacks to onOptionsItemSelected() when a menu item is selected.
You can also register a view in your fragment layout to provide a context menu by calling registerForContextMenu(). When the user opens the context menu, the fragment receives a call to onCreateContextMenu(). When the user selects an item, the fragment receives a call to onContextItemSelected().
Note: Although your fragment receives an on-item-selected callback for each menu item it adds, the activity is first to receive the respective callback when the user selects a menu item. If the activity's implementation of the on-item-selected callback does not handle the selected item, then the event is passed to the fragment's callback. This is true for the Options Menu and context menus.
For more information about menus, see the Menus developer guide and the App Bar training class.
## Handling the Fragment Lifecycle
Figure 3. The effect of the activity lifecycle on the fragment lifecycle.
Managing the lifecycle of a fragment is a lot like managing the lifecycle of an activity. Like an activity, a fragment can exist in three states:
Resumed
The fragment is visible in the running activity.
Paused
Another activity is in the foreground and has focus, but the activity in which this fragment lives is still visible (the foreground activity is partially transparent or doesn't cover the entire screen).
Stopped
The fragment is not visible. Either the host activity has been stopped or the fragment has been removed from the activity but added to the back stack. A stopped fragment is still alive (all state and member information is retained by the system). However, it is no longer visible to the user and will be killed if the activity is killed.
Also like an activity, you can retain the state of a fragment using a Bundle, in case the activity's process is killed and you need to restore the fragment state when the activity is recreated. You can save the state during the fragment's onSaveInstanceState() callback and restore it during either onCreate(), onCreateView(), or onActivityCreated(). For more information about saving state, see the Activities document.
The most significant difference in lifecycle between an activity and a fragment is how one is stored in its respective back stack. An activity is placed into a back stack of activities that's managed by the system when it's stopped, by default (so that the user can navigate back to it with the Back button, as discussed in Tasks and Back Stack). However, a fragment is placed into a back stack managed by the host activity only when you explicitly request that the instance be saved by calling addToBackStack() during a transaction that removes the fragment.
Otherwise, managing the fragment lifecycle is very similar to managing the activity lifecycle. So, the same practices for managing the activity lifecycle also apply to fragments. What you also need to understand, though, is how the life of the activity affects the life of the fragment.
Caution: If you need a Context object within your Fragment, you can call getActivity(). However, be careful to call getActivity() only when the fragment is attached to an activity. When the fragment is not yet attached, or was detached during the end of its lifecycle, getActivity() will return null.
## Coordinating with the activity lifecycle
The lifecycle of the activity in which the fragment lives directly affects the lifecycle of the fragment, such that each lifecycle callback for the activity results in a similar callback for each fragment. For example, when the activity receives onPause(), each fragment in the activity receives onPause().
Fragments have a few extra lifecycle callbacks, however, that handle unique interaction with the activity in order to perform actions such as build and destroy the fragment's UI. These additional callback methods are:
onAttach()
Called when the fragment has been associated with the activity (the Activity is passed in here).
onCreateView()
Called to create the view hierarchy associated with the fragment.
onActivityCreated()
Called when the activity's onCreate() method has returned.
onDestroyView()
Called when the view hierarchy associated with the fragment is being removed.
onDetach()
Called when the fragment is being disassociated from the activity.
The flow of a fragment's lifecycle, as it is affected by its host activity, is illustrated by figure 3. In this figure, you can see how each successive state of the activity determines which callback methods a fragment may receive. For example, when the activity has received its onCreate() callback, a fragment in the activity receives no more than the onActivityCreated() callback.
Once the activity reaches the resumed state, you can freely add and remove fragments to the activity. Thus, only while the activity is in the resumed state can the lifecycle of a fragment change independently.
However, when the activity leaves the resumed state, the fragment again is pushed through its lifecycle by the activity.
## Example
To bring everything discussed in this document together, here's an example of an activity using two fragments to create a two-pane layout. The activity below includes one fragment to show a list of Shakespeare play titles and another to show a summary of the play when selected from the list. It also demonstrates how to provide different configurations of the fragments, based on the screen configuration.
Note: The complete source code for this activity is available in FragmentLayout.java.
The main activity applies a layout in the usual way, during onCreate():
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_layout);
}
The layout applied is fragment_layout.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent" android:layout_height="match_parent">
<fragment class="com.example.android.apis.app.FragmentLayout$TitlesFragment"
android:id="@+id/titles" android:layout_weight="1"
android:layout_width="0px" android:layout_height="match_parent" />
<FrameLayout android:id="@+id/details" android:layout_weight="1"
android:layout_width="0px" android:layout_height="match_parent"
android:background="?android:attr/detailsElementBackground" />
</LinearLayout>
Using this layout, the system instantiates the TitlesFragment (which lists the play titles) as soon as the activity loads the layout, while the FrameLayout (where the fragment for showing the play summary will go) consumes space on the right side of the screen, but remains empty at first. As you'll see below, it's not until the user selects an item from the list that a fragment is placed into the FrameLayout.
However, not all screen configurations are wide enough to show both the list of plays and the summary, side by side. So, the layout above is used only for the landscape screen configuration, by saving it at res/layout-land/fragment_layout.xml.
Thus, when the screen is in portrait orientation, the system applies the following layout, which is saved at res/layout/fragment_layout.xml:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<fragment class="com.example.android.apis.app.FragmentLayout$TitlesFragment"
android:id="@+id/titles"
android:layout_width="match_parent" android:layout_height="match_parent" />
</FrameLayout>
This layout includes only TitlesFragment. This means that, when the device is in portrait orientation, only the list of play titles is visible. So, when the user clicks a list item in this configuration, the application will start a new activity to show the summary, instead of loading a second fragment.
Next, you can see how this is accomplished in the fragment classes. First is TitlesFragment, which shows the list of Shakespeare play titles. This fragment extends ListFragment and relies on it to handle most of the list view work.
As you inspect this code, notice that there are two possible behaviors when the user clicks a list item: depending on which of the two layouts is active, it can either create and display a new fragment to show the details in the same activity (adding the fragment to the FrameLayout), or start a new activity (where the fragment can be shown).
public static class TitlesFragment extends ListFragment {
boolean mDualPane;
int mCurCheckPosition = 0;
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Populate list with our static array of titles.
setListAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_activated_1, Shakespeare.TITLES));
// Check to see if we have a frame in which to embed the details
// fragment directly in the containing UI.
View detailsFrame = getActivity().findViewById(R.id.details);
mDualPane = detailsFrame != null && detailsFrame.getVisibility() == View.VISIBLE;
if (savedInstanceState != null) {
// Restore last state for checked position.
mCurCheckPosition = savedInstanceState.getInt("curChoice", 0);
}
if (mDualPane) {
// In dual-pane mode, the list view highlights the selected item.
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
// Make sure our UI is in the correct state.
showDetails(mCurCheckPosition);
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("curChoice", mCurCheckPosition);
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
showDetails(position);
}
/**
* Helper function to show the details of a selected item, either by
* displaying a fragment in-place in the current UI, or starting a
* whole new activity in which it is displayed.
*/
void showDetails(int index) {
mCurCheckPosition = index;
if (mDualPane) {
// We can display everything in-place with fragments, so update
// the list to highlight the selected item and show the data.
getListView().setItemChecked(index, true);
// Check what fragment is currently shown, replace if needed.
DetailsFragment details = (DetailsFragment)
getFragmentManager().findFragmentById(R.id.details);
if (details == null || details.getShownIndex() != index) {
// Make new fragment to show this selection.
details = DetailsFragment.newInstance(index);
// Execute a transaction, replacing any existing fragment
// with this one inside the frame.
FragmentTransaction ft = getFragmentManager().beginTransaction();
if (index == 0) {
ft.replace(R.id.details, details);
} else {
ft.replace(R.id.a_item, details);
}
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
}
} else {
// Otherwise we need to launch a new activity to display
// the dialog fragment with selected text.
Intent intent = new Intent();
intent.setClass(getActivity(), DetailsActivity.class);
intent.putExtra("index", index);
startActivity(intent);
}
}
}
The second fragment, DetailsFragment shows the play summary for the item selected from the list from TitlesFragment:
public static class DetailsFragment extends Fragment {
/**
* Create a new instance of DetailsFragment, initialized to
* show the text at 'index'.
*/
public static DetailsFragment newInstance(int index) {
DetailsFragment f = new DetailsFragment();
// Supply index input as an argument.
Bundle args = new Bundle();
args.putInt("index", index);
f.setArguments(args);
return f;
}
public int getShownIndex() {
return getArguments().getInt("index", 0);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (container == null) {
// We have different layouts, and in one of them this
// fragment's containing frame doesn't exist. The fragment
// may still be created from its saved state, but there is
// no reason to try to create its view hierarchy because it
// won't be displayed. Note this is not needed -- we could
// just run the code below, where we would create and return
// the view hierarchy; it would just never be used.
return null;
}
ScrollView scroller = new ScrollView(getActivity());
TextView text = new TextView(getActivity());
int padding = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
4, getActivity().getResources().getDisplayMetrics());
text.setPadding(padding, padding, padding, padding);
scroller.addView(text);
text.setText(Shakespeare.DIALOGUE[getShownIndex()]);
return scroller;
}
}
Recall from the TitlesFragment class, that, if the user clicks a list item and the current layout does not include the R.id.details view (which is where the DetailsFragment belongs), then the application starts the DetailsActivity activity to display the content of the item.
Here is the DetailsActivity, which simply embeds the DetailsFragment to display the selected play summary when the screen is in portrait orientation:
public static class DetailsActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getResources().getConfiguration().orientation
== Configuration.ORIENTATION_LANDSCAPE) {
// If the screen is now in landscape mode, we can show the
// dialog in-line with the list so we don't need this activity.
finish();
return;
}
if (savedInstanceState == null) {
// During initial setup, plug in the details fragment.
DetailsFragment details = new DetailsFragment();
details.setArguments(getIntent().getExtras());
getFragmentManager().beginTransaction().add(android.R.id.content, details).commit();
}
}
}
Notice that this activity finishes itself if the configuration is landscape, so that the main activity can take over and display the DetailsFragment alongside the TitlesFragment. This can happen if the user begins the DetailsActivity while in portrait orientation, but then rotates to landscape (which restarts the current activity).
For more samples using fragments (and complete source files for this example), see the API Demos sample app available in ApiDemos (available for download from the Samples SDK component).
|
2c2d5f59bc160672ab75c92b0b330bbe1b53321c
|
[
"Markdown",
"Java"
] | 3
|
Java
|
Red-French/HeroMe
|
b3d59782a48dda926c630b77bcca90210231742e
|
e33d1605ef2d3abf3f4c92412d68bd4949225744
|
refs/heads/master
|
<repo_name>emagallong/MitoPhAST<file_sep>/V3.0/install.sh
path=`pwd`
exe=`echo "$path/exe"`
# clean up previous installations
cd $exe
rm -rf FASconCAT-G_v1.02
rm -rf FingerPRINTScan_3596
rm -rf Gblocks_0.91b
rm -rf hmmer-3.1b2-linux-intel-x86_64
rm -rf iqtree-omp-1.5.5
rm -rf mafft-7.394-with-extensions
rm -rf ncbi-blast-2.6.0+
# install FASconCAT
mkdir FASconCAT-G_v1.02
cd FASconCAT-G_v1.02
ln -s ../FASconCAT-G.zip
unzip FASconCAT-G.zip
cd ..
if [ ! -s $exe/FASconCAT-G_v1.02/FASconCAT-G_v1.02.pl ]
then
echo "ERROR: FASconCAT-G installation failed"
exit
fi
# install FingerPRINTScan
mkdir FingerPRINTScan_3596
cd FingerPRINTScan_3596
ln -s ../fingerPRINTScan.linux fingerPRINTScan
cd ..
if [ ! -s $exe/FingerPRINTScan_3596/fingerPRINTScan ]
then
echo "ERROR: FingerPRINTScan installation failed"
exit
fi
# install Gblocks
zcat Gblocks_Linux64_0.91b.tar.Z | tar -xvf -
if [ ! -s $exe/Gblocks_0.91b/Gblocks ]
then
echo "ERROR: Gblocks installation failed"
exit
fi
# install hmmer
tar -zxvf hmmer-3.1b2-linux-intel-x86_64.tar.gz
cd hmmer-3.1b2-linux-intel-x86_64
./configure --prefix=$exe/hmmer-3.1b2-linux-intel-x86_64/ && make && make install
cd ..
if [ ! -s $exe/hmmer-3.1b2-linux-intel-x86_64/bin/hmmsearch ]
then
echo "ERROR: HMMer installation failed"
exit
fi
# install IQ-TREE
tar -zxvf iqtree-omp-1.5.5-Linux.tar.gz
mv iqtree-omp-1.5.5-Linux iqtree-omp-1.5.5
if [ ! -s $exe/iqtree-omp-1.5.5/bin/iqtree-omp ]
then
echo "ERROR: IQ-TREE installation failed"
exit
fi
# install MAFFT
tar -zxvf mafft-7.394-with-extensions-src.tgz
cd mafft-7.394-with-extensions/core
cp Makefile Makefile.backup
sed -i "s|/usr/local|$exe/mafft-7.394-with-extensions|g" Makefile
make && make install
cd ../../
if [ ! -s $exe/mafft-7.394-with-extensions/bin/mafft ]
then
echo "ERROR: MAFFT installation failed"
exit
fi
# install NCBI BLAST
tar -zxvf ncbi-blast-2.6.0+-x64-linux.tar.gz
if [ ! -s $exe/ncbi-blast-2.6.0+/bin/blastn ]
then
echo "ERROR: BLAST installation failed"
exit
fi
echo "Installation completed successfully."
<file_sep>/V3.0/README.txt
TITLE: MitoPhAST - Mitogenome Phylogenetic Analysis of Sequences Tool
=======
VERSION
=======
3.0
=======
CONTACT
=======
MunHua <<EMAIL>>
============
INTRODUCTION
============
The increased rate at which complete mitogenomes are being sequenced and their increasing use for phylogenetic studies have resulted in a bioinformatics bottleneck in preparing and utilising such data for phylogenetic data analysis. We present, MitoPhAST, an automated tool that:
1) Identifies annotated protein-coding gene (PCG) and ribosomal RNA (rRNA) features directly from complete/partial GenBank/EMBL-format mitogenome files and generates a standardized, concatenated and partitioned nucleotide/amino acid alignments.
2) Incorporates nuclear gene sequences (if supplied by user) into phylogenetic analysis.
2) Generates a maximum likelihood phylogenetic tree using optimized substitution models performed by IQ-TREE.
3) Reports various mitochondrial genes and sequence information in a simple table format.
4) Extracts mitochondrial gene order (MGO) from GenBank files and clusters identical MGOs into groups
=============
PREREQUISITES
=============
Both install and automated run scripts were tested on Ubuntu 16.04 64-bit and MacOS 10.7.5 systems.
Please ensure systems are equipped with working versions of:
- Perl (http://www.perl.org/get.html)
- BioPerl (http://www.bioperl.org/wiki/Getting_BioPerl)
- Bio::DB::EUtilities
- LWP::Protocol::https
- R
============
INSTALLATION
============
1) Decompress the zipped folder, e.g.:
unzip MitoPhAST-master.zip
2) Change into the created directory, e.g.:
cd MitoPhAST-master
3) Run installation script, e.g.:
./install.sh
(for MAC users, run ./install_mac.sh instead)
=====
USAGE
=====
./run_pipeline.pl -h
Usage example: ./run_pipeline.pl -in mitofiles -acc NC_001645.1,NC_008795.1 -out analysis_out --summarize --build_trees -mito_gcode 1 -mode custom -other_pcg H3,H4 -other_pcg_gcode 1 -chars nt --gene_order -ori COX1
Options:
INPUT (at least one REQUIRED):
-in <folder> input directory containing all GenBank and/or EMBL files
-acc <string> string of accession numbers to download from NCBI (comma-separated)
-list <file> file of accession numbers to download from NCBI (one accession/line)
OUTPUT:
-out <folder> output directory to store all results and intermediate files (REQUIRED)
ANALYSIS (at least one REQUIRED):
--summarize to generate summaries for each mitogenome
--extract_only to only extract and group sequences from GenBank and/or EMBL files (no need to invoke if running --build_trees)
--build_trees to run phylogenetic analysis
--gene_order to run gene order comparison analysis
IF --build_trees:
-mito_gcode <int> genetic code for mitogenome sequences (e.g. 1=Standard, 2=Vertebrate Mitochondrial, 5=Invertebrate Mitochondrial, etc) (REQUIRED)
-mode <string> indicate genes used for phylogenetic analyis, default=pcg (modes = pcg/pcg12s16s/12s16s/all/custom)
-pcg <string> if -mode 'custom', list PCG genes (comma-separated) for phylogenetic analysis (or '-pcg all' for all mitogenome PCGs)
-rrna <string> if -mode 'custom', list rRNA genes (comma-separated) for phylogenetic analysis (or '-rrna all' for all mitogenome rRNAs)
-other_pcg <string> if -mode 'custom', list other non-mitogenome PCGs (comma-separated) for phylogenetic analysis (see README)
-other_pcg_gcode <int> genetic code for genes listed at -other_pcg (e.g. 1=Standard, 2=Vertebrate Mitochondrial, 5=Invertebrate Mitochondrial, etc)
-other_nonpcg <string> if -mode 'custom', list other non-mitogenome non-PCGs (comma-separated) for phylogenetic analysis (see README)
-chars <string> indicate type of character used for phylogenetic analysis, default=both (chars = aa/nt/both)
-bb <on/off> to run ultrafast bootstrap - UFBoot (Minh et al, 2013), default=on
-bbrep <int> number of ultrafast bootstrap replicates, default=1000
-alrt <on/off> to run SH-alrt test - SH-aLRT (Guindon et al, 2010), default=on
-alrtrep <int> number of SH-alrt replicates, default=1000
IF --gene_order:
-ori <string> re-orient linear gene orders to this gene (REQUIRED)
OTHER:
-cpu <int> number of threads, default=1
-interactive <on/off> control interactive messages (default=on, recommended)
-h/help for this help message
================
MITOGENOME INPUT
================
MitoPhAST automatically detects GenBank/EMBL files located in the input directory specified at -in.
Users can also provide comma-separated string (-acc) or a list (-list) of accession numbers to be downloaded from NCBI
=============
NUCLEAR INPUT
=============
Users can also perform phylogenetic analysis on combined mitogenome + nuclear datasets.
1) For nuclear PCGs (-other_pcg), have two fasta files per nuclear gene in the input directory (-in).
The fasta file needs to be named all_<gene>.aa.fa or all_<gene>.nt.fa for amino acid and nucleotide sequences, respectively.
For nuclear non-coding genes (-other_nonpcg), you will have only one fasta file per nuclear gene, named all_<gene>.nt.fa.
E.g. -other_pcg H3,H4 will need files all_H3.aa.fa, all_H3.nt.fa, all_H4.aa.fa, all_H4.nt.fa
-other_nonpcg 18S,28S will need files all_18S.nt.fa, all_28S.nt.fa
2) The identifier for each fasta entry will contain accession number and species name in the correct format (>Accession_species).
This helps the pipeline match nuclear sequences to the correct mitogenome sequences extracted from GenBank/EMBL files.
E.g. in all_H3.aa.fa
>NMVJ53370.1_Ibacus_alticrenatus
MARTKQTARKSTGGKAPRKQLATKAARKSAPATGGVKKPHRYRPGTVALREIRRYQKSTELLIRKLPFQRLVREIAQDFKTDLRFQSSAVMALQEASEAYLVGLFEDTNLCAIHAKRVTIMPKDIQLARRIRGERA
>NMVJ55596.1_Puerulus_angulatus
MARTKQTARKSTGGKAPRKQLATKAARKSAPATGGVKKPHRYRPGTVALREIRRYQKSTELLIRKLPFQRLVREIAQDFKTDLRFQSSAVMALQEASEAYLVGLFEDTNLCAIHAKRVTIMPKDIQLARRIRGERA
3) Specify genetic code for nuclear PCGs (typically -other_pcg_gcode is set to 1 for the Standard code)
===============
MGO ORIENTATION
===============
To compare mitochondrial gene orders, linear orders need to be re-oriented to a common gene.
Users can specify the gene of choice at -ori with the following options:
ATP6, ATP8, COX1, COX2, COX3, CYTB, ND1, ND2, ND3, ND4, ND4L, ND5, ND6, rrnL, rrnS, trnA, trnC, trnD, trnE, trnF, trnG, trnH, trnI, trnK, trnL, trnL, trnM, trnN, trnP, trnQ, trnR, trnS, trnS, trnT, trnV, trnW, trnY
=================
BRIEF DESCRIPTION
=================
- Nucleotide and amino acid sequences for 13 PCG and 2 rRNA genes are extracted from each mitogenome GenBank/EMBL file.
- To verify annotation and to compensate for non-standard nomenclature in gene names in existing GenBank/EMBL files, extracted mitogenome PCG sequences are first searched against PFAM/PRINT profiles specific to each of the 13 PCGs. It is recommended that users manually check these files to ensure sequences are correctly assigned. Profiling has worked for the majority of the sequences we have tested. If you find a gene that is unassigned to any group, the workaround is to ensure the gene is named according to standards (see section "Gene ID list" for details). Users will be flagged by the pipeline if it encounters any anomalies.
- Nuclear PCG genes do not undergo any verification process.
- Verified nucleotide or amino acid sequences are then aligned using MAFFT and TranslatorX, respectively, both trimmed with Gblocks to remove ambiguously-aligned regions.
- 'Clean' alignments are concatenated with FASconCAT-G into supermatrices.
- Supermatrices, along with partition information, are provided to IQ-TREE for Maximum-likelihood analysis. PCG (amino acid) and non-coding (nucleotide) alignments are partitioned according to individual genes, whereas PCG nucleotide alignments are partitioned according to individual genes and codon positions (first, second, third).
- The resulting trees with SH-aLRT/ultrafast bootstrap support values constructed by IQ-TREE can be found in the output directory.
- The pipeline also retains mitochondrial gene order (MGO) information from GenBank/EMBL files and performs comparisons within the dataset, providing users fasta format files that can be used as input for CREx and TREx as well as MGOs visualized in PDF files to facilitate further comparative analysis.
======
OUTPUT
======
An output folder is automatically generated based on name specified at -out <folder>
+ <output directory>
|- results
|- 1.mitofiles
|- 2.summaries
|- 3.sequences
|- 4.trees
|- 5.gene_orders
|- work
|- extract
|- gene_orders
|- phylogenetics
|- summaries
$PATH/<OUTPUT_DIR>/results/1.mitofiles/
---------------------------------
Contains all analyzed mitogenome files, including those downloaded from NCBI based on accession numbers provided to the -acc or -list options.
$PATH/<OUTPUT_DIR>/results/2.summaries/
---------------------------------
Contains summary reports generated for each GenBank/EMBL file. The number of PCGs, rRNAs, tRNAs and control regions are counted, followed by a table containing the names, strand, start/stop positions, lengths and intergenic nucleotides for each gene.
$PATH/<OUTPUT_DIR>/results/3.sequences/
----------------------------------
Contains Nucleotide and Amino acid sequences for 13 PCGs and 2 rRNAs compiled from analyzed mitogenome files.
$PATH/<OUTPUT_DIR>/results/4.trees/
----------------------------------
Contains Fasta and Phylip files used for phylogenetic tree construction. Also contains maximum likelihood trees (Newick) with SH-aLRT/UFboot support values at nodes for every alignment.
$PATH/<OUTPUT_DIR>/results/5.gene_orders
----------------------------------
Contains grouping of mitochondrial gene orders (MGOs) in FASTA and PDF output files
$PATH/<OUTPUT_DIR>/work/
----------------------------------
Contains intermediate files including extracted gene sequences from each mitogenome file, raw and trimmed multiple sequence alignments of each gene (nt and aa), output files from IQ-TREE, etc.
============
Gene ID list
============
In the event where a protein-coding gene sequence fails to be identified by its PFAM/PRINT domain, MitoPhAST relies on gene tags in the GenBank/EMBL file to group PCG sequences.
The following are gene IDs recognized by MitoPhAST (case insensitive):
ATP6 / ATPASE6 / ATPASE_6
ATP8 / ATPASE8 / ATPASE_8
COX1 / COI / CO1
COX2 / COII / CO2
COX3 / COIII / CO3
COB / CYTB / CYT_B
NAD1 / ND1 / NADH1
NAD2 / ND2 / NADH2
NAD3 / ND3 / NADH3
NAD4 / ND4 / NADH4
NAD4L / ND4L / NADH4L
NAD5 / ND5 / NADH5
NAD6 / ND6 / NADH6
==================================
Versions of software/programs used
==================================
FASconCAT-G v1.02
FingerPRINTScan v3.596
Gblocks v0.91b
HMMER v3.1b2
IQ-TREE v1.5.5
MAFFT v7.394
BLAST+ v2.6.0
===========
GitHub link
===========
https://github.com/mht85/MitoPhAST
<file_sep>/V3.0/bin/plot_order.R
#usr/bin/R
args=(commandArgs(TRUE))
library("plotrix", lib.loc=args[3])
matrix<-read.table(args[1], header=TRUE, sep="\t")
numrow<-nrow(matrix)
factor<-log(numrow, numrow)
factor
ystart = 1.01
pdf(file=args[2], width=15, height=factor*100, pointsize=factor*12, onefile=TRUE)
par(mar=c(0,0,0,0))
plot.new()
boxed.labels(0.98, 1, "ATP", bg="yellow", border=TRUE, xpad=1.5, ypad=1.5, cex=1)
boxed.labels(0.98, 0.997, "COX", bg="dark green", border=TRUE, xpad=1.5, ypad=1.5, cex=1) #0.997
boxed.labels(0.98, 0.994, "CYTB", bg="purple", border=TRUE, xpad=1.5, ypad=1.5, cex=1) #0.994
boxed.labels(0.98, 0.991, "ND", bg="dark blue", border=TRUE, xpad=1.5, ypad=1.5, cex=1) #0.991
boxed.labels(0.98, 0.988, "rRNA", bg="dark orange", border=TRUE, xpad=1.5, ypad=1.5, cex=1) #0.988
boxed.labels(0.98, 0.985, "tRNA", bg="dark red", border=TRUE, xpad=1.5, ypad=1.5, cex=1) #0.985
#boxed.labels(0.98, 0.982, "CR", bg="grey", border=TRUE, xpad=1.5, ypad=1.5, cex=1)
for (row in 1:nrow(matrix)) {
pattern_num <- as.character(matrix[row,1])
total <- matrix[row,2]
gene_order <- as.character(matrix[row,-(1:2)])
gene_order <- strsplit(gene_order, " ")[[1]]
len <- length(gene_order)
ystart <- ystart - factor*0.008 # 0.008
linestart = ystart + factor*0.001 # 0.001
lines(c(0,0.95), c(linestart,linestart), col="dark grey", lty=2)
string <- c(pattern_num, "(",total, "species )")
textbox(c(0,1), ystart, string, justify='l', margin=-0.005, box=FALSE, cex=1) # cex=1
xstart = 0.02
ystartfwd = ystart - factor*0.003 # 0.003
ystartrev = ystartfwd - factor*0.002 # 0.002
for (col in 1:len) {
gene <- gene_order[col]
if (grepl("COX", gene)) {
color <- c("dark green")
gene <- gsub("COX", "", gene)
} else if (grepl("ND", gene)) {
color <- c("dark blue")
gene <- gsub("ND", "", gene)
gene <- gsub("4L", "4l", gene)
} else if (grepl("ATP", gene)) {
color <- c("yellow")
gene <- gsub("ATP", "", gene)
} else if (grepl("rrn", gene)) {
color <- c("dark orange")
gene <- gsub("rrn", "", gene)
} else if (grepl("trn", gene)) {
color <- c("dark red")
gene <- gsub("trn", "", gene)
} else if (grepl("CYTB", gene)) {
color <- c("purple")
gene <- gsub("CYTB", "C", gene)
} else {
color <- c("grey")
gene <- gsub("CR", "cr", gene)
}
if (!grepl("^-", gene)) {
boxed.labels(xstart, ystartfwd, gene, bg=color, border=TRUE, xpad=1.5, ypad=1.5, cex=1) # cex=1
} else {
gene <- gsub("-", "", gene)
boxed.labels(xstart, ystartrev, gene, bg=color, border=TRUE, xpad=1.5, ypad=1.5, cex=1) # cex=1
}
xstart <- xstart + factor*0.015 #0.015
}
}
dev.off()
|
ddbc71d46e4f1aaa8bb7490b94a2773e50e4ea38
|
[
"Text",
"R",
"Shell"
] | 3
|
Shell
|
emagallong/MitoPhAST
|
03e0538d6d03c2a432feaa6f7b44d195fdf4dc66
|
91b2319ba249d39138fec4c02667653cd1a95c2e
|
refs/heads/master
|
<repo_name>hzphzp/hr_regan<file_sep>/models.py
import torch
from torch import nn
import torch.nn.functional as F
from torch.autograd import Variable
from torch.utils.data import TensorDataset, DataLoader
class ResidualBlock(nn.Module):
def __init__(self, dim_in, dim_out):
super(ResidualBlock, self).__init__()
self.main = nn.Sequential(
nn.Conv2d(dim_in, dim_out, kernel_size=3, stride=1, padding=1, bias=False),
nn.InstanceNorm2d(dim_out, affine=True),
nn.ReLU(inplace=True),
nn.Conv2d(dim_out, dim_out, kernel_size=3, stride=1, padding=1, bias=False),
nn.InstanceNorm2d(dim_out, affine=True),
)
def forward(self, x):
return x + self.main(x)
class GeneratorCNN(nn.Module):
def __init__(self, input_channel, output_channel, conv_dims, deconv_dims, num_gpu):
super(GeneratorCNN, self).__init__()
self.num_gpu = num_gpu
self.layers = []
prev_dim = conv_dims[0]
self.layers.append(nn.Conv2d(input_channel, prev_dim, 4, 2, 1, bias=False))
self.layers.append(nn.LeakyReLU(0.2, inplace=True))
for out_dim in conv_dims[1:]:
self.layers.append(nn.Conv2d(prev_dim, out_dim, 4, 2, 1, bias=False))
self.layers.append(nn.BatchNorm2d(out_dim))
self.layers.append(nn.LeakyReLU(0.2, inplace=True))
prev_dim = out_dim
for out_dim in deconv_dims:
self.layers.append(nn.ConvTranspose2d(prev_dim, out_dim, 4, 2, 1, bias=False))
self.layers.append(nn.BatchNorm2d(out_dim))
self.layers.append(nn.ReLU(True))
prev_dim = out_dim
self.layers.append(nn.ConvTranspose2d(prev_dim, output_channel, 4, 2, 1, bias=False))
self.layers.append(nn.Tanh())
self.layer_module = nn.ModuleList(self.layers)
def main(self, x):
out = x
for layer in self.layer_module:
out = layer(out)
return out
def forward(self, x):
return self.main(x)
class GeneratorCNN_res(nn.Module):
def __init__(self, input_channel, output_channel, conv_dims, deconv_dims, num_gpu):
super(GeneratorCNN_res, self).__init__()
self.num_gpu = num_gpu
self.layers = []
prev_dim = conv_dims[0]
self.layers.append(nn.Conv2d(input_channel, prev_dim, 4, 2, 1, bias=False))
self.layers.append(nn.LeakyReLU(0.2, inplace=True))
for out_dim in conv_dims[1:]:
self.layers.append(nn.Conv2d(prev_dim, out_dim, 4, 2, 1, bias=False))
self.layers.append(nn.InstanceNorm2d(out_dim, affine=True))
self.layers.append(nn.LeakyReLU(0.2, inplace=True))
prev_dim = out_dim
for i in range(6):
self.layers.append(ResidualBlock(dim_in=out_dim, dim_out=out_dim))
for out_dim in deconv_dims:
self.layers.append(nn.ConvTranspose2d(prev_dim, out_dim, 4, 2, 1, bias=False))
self.layers.append(nn.InstanceNorm2d(out_dim, affine=True))
self.layers.append(nn.ReLU(True))
prev_dim = out_dim
self.layers.append(nn.ConvTranspose2d(prev_dim, output_channel, 4, 2, 1, bias=False))
self.layers.append(nn.Tanh())
self.layer_module = nn.ModuleList(self.layers)
def main(self, x):
out = x
for layer in self.layer_module:
out = layer(out)
return out
def forward(self, x):
return self.main(x)
class EncoderCNN_1(nn.Module):
def __init__(self, input_channel, conv_dims, num_gpu):
super(EncoderCNN_1, self).__init__()
self.num_gpu = num_gpu
self.layers = []
prev_dim = conv_dims[0]
self.layers.append(nn.Conv2d(input_channel, prev_dim, 4, 2, 1, bias=False))
self.layers.append(nn.LeakyReLU(0.2, inplace=True))
for out_dim in conv_dims[1:]:
self.layers.append(nn.Conv2d(prev_dim, out_dim, 4, 2, 1, bias=False))
self.layers.append(nn.BatchNorm2d(out_dim))
self.layers.append(nn.LeakyReLU(0.2, inplace=True))
prev_dim = out_dim
for i in range(6):
self.layers.append(ResidualBlock(dim_in=out_dim, dim_out=out_dim))
self.layer_module = nn.ModuleList(self.layers)
def main(self, x):
out = x
for layer in self.layer_module:
out = layer(out)
return out
def forward(self, x):
return self.main(x)
class EncoderCNN_2(nn.Module):
def __init__(self, input_channel, conv_dims, num_gpu):
super(EncoderCNN_2, self).__init__()
self.num_gpu = num_gpu
self.layers = []
prev_dim = conv_dims[0]
self.layers.append(nn.Conv2d(input_channel, prev_dim, 4, 2, 1, bias=False))
self.layers.append(nn.LeakyReLU(0.2, inplace=True))
for out_dim in conv_dims[1:]:
self.layers.append(nn.Conv2d(prev_dim, out_dim, 4, 2, 1, bias=False))
self.layers.append(nn.BatchNorm2d(out_dim))
self.layers.append(nn.LeakyReLU(0.2, inplace=True))
prev_dim = out_dim
self.layer_module = nn.ModuleList(self.layers)
def main(self, x):
out = x
for layer in self.layer_module:
out = layer(out)
return out
def forward(self, x):
return self.main(x)
class DecoderCNN(nn.Module):
def __init__(self, input_channel, output_channel, deconv_dims, num_gpu):
super(DecoderCNN, self).__init__()
self.num_gpu = num_gpu
self.layers = []
prev_dim = input_channel
for out_dim in deconv_dims:
self.layers.append(nn.ConvTranspose2d(prev_dim, out_dim, 4, 2, 1, bias=False))
self.layers.append(nn.BatchNorm2d(out_dim))
self.layers.append(nn.ReLU(True))
prev_dim = out_dim
self.layers.append(nn.ConvTranspose2d(prev_dim, output_channel, 4, 2, 1, bias=False))
self.layers.append(nn.Tanh())
self.layer_module = nn.ModuleList(self.layers)
def main(self, x):
out = x
for layer in self.layer_module:
out = layer(out)
return out
def forward(self, x):
return self.main(x)
class DiscriminatorCNN(nn.Module):
def __init__(self, input_channel, output_channel, hidden_dims, num_gpu):
super(DiscriminatorCNN, self).__init__()
self.num_gpu = num_gpu
self.layers = []
prev_dim = hidden_dims[0]
self.layers.append(nn.Conv2d(input_channel, prev_dim, kernel_size=4, stride=1, padding=1, bias=True))
self.layers.append(nn.LeakyReLU(0.2, inplace=True))
for out_dim in hidden_dims[1:]:
self.layers.append(nn.Conv2d(prev_dim, out_dim, 4, 1, 1, bias=False))
self.layers.append(nn.BatchNorm2d(out_dim))
self.layers.append(nn.LeakyReLU(0.2, inplace=True))
prev_dim = out_dim
#self.layers.append(nn.Conv2d(prev_dim, output_channel, 4, 1, 0, bias=False))
#self.layers.append(nn.Linear(512*4*4, 1024))
#self.layers.append(nn.ReLU(True))
self.layers.append(nn.Linear(prev_dim, output_channel))
self.layers.append(nn.Sigmoid())
self.layer_module = nn.ModuleList(self.layers)
def main(self, x):
out = x
for index in range(len(self.layer_module)-2):
layer = self.layer_module[index]
out = layer(out)
out=out.view(out.size(0), out.size(1),-1)
out=torch.mean(out,2)
out=out.view(out.size(0), out.size(1))
#print(out.size())
#print out.size(3)
#import IPython
#IPython.embed()
#out = self.layer_module[-4](out)
#out = self.layer_module[-3](out)
out = self.layer_module[-2](out)
out = self.layer_module[-1](out)
return out
def forward(self, x):
return self.main(x)
class GeneratorFC(nn.Module):
def __init__(self, input_size, output_size, hidden_dims):
super(GeneratorFC, self).__init__()
self.layers = []
prev_dim = input_size
for hidden_dim in hidden_dims:
self.layers.append(nn.Linear(prev_dim, hidden_dim))
self.layers.append(nn.ReLU(True))
prev_dim = hidden_dim
self.layers.append(nn.Linear(prev_dim, output_size))
self.layer_module = nn.ModuleList(self.layers)
def forward(self, x):
out = x
for layer in self.layer_module:
out = layer(out)
return out
class DiscriminatorFC(nn.Module):
def __init__(self, input_size, output_size, hidden_dims):
super(DiscriminatorFC, self).__init__()
self.layers = []
prev_dim = input_size
for idx, hidden_dim in enumerate(hidden_dims):
self.layers.append(nn.Linear(prev_dim, hidden_dim))
self.layers.append(nn.ReLU(True))
prev_dim = hidden_dim
self.layers.append(nn.Linear(prev_dim, output_size))
self.layers.append(nn.Sigmoid())
self.layer_module = nn.ModuleList(self.layers)
def forward(self, x):
out = x
for layer in self.layer_module:
out = layer(out)
return out.view(-1, 1)
<file_sep>/trainer.py
from __future__ import print_function
import numpy as np
import os
from glob import glob
# from tqdm import trange
from itertools import chain
import torch
from torch import nn
import torch.nn.parallel
import torchvision.utils as vutils
from torch.autograd import Variable
from models import *
from data_loader import get_loader
from img_random_discmp import img_random_dis
def weights_init(m):
classname = m.__class__.__name__
if classname.find('Conv') != -1:
m.weight.data.normal_(0.0, 0.02)
elif classname.find('BatchNorm') != -1:
m.weight.data.normal_(1.0, 0.02)
m.bias.data.fill_(0)
class Trainer(object):
def __init__(self, config, a_data_loader, b_data_loader):
self.config = config
self.a_data_loader = a_data_loader
self.b_data_loader = b_data_loader
self.num_gpu = config.num_gpu
self.dataset = config.dataset
self.loss = config.loss
self.lr = config.lr
self.beta1 = config.beta1
self.beta2 = config.beta2
self.optimizer = config.optimizer
self.batch_size = config.batch_size
self.weight_decay = config.weight_decay
self.cnn_type = config.cnn_type
self.model_dir = config.model_dir
self.pic_dir = config.pic_dir
self.load_path = config.load_path
self.start_step = 0
self.log_step = config.log_step
self.max_step = config.max_step
self.save_step = config.save_step
self.build_model()
if self.num_gpu == 1:
self.D_F.cuda()
self.D_AB.cuda()
self.E_AB.cuda()
elif self.num_gpu > 1:
self.D_F = nn.DataParallel(self.D_F.cuda(),device_ids=range(self.num_gpu))
self.D_AB = nn.DataParallel(self.D_AB.cuda(),device_ids=range(self.num_gpu))
self.E_AB = nn.DataParallel(self.E_AB.cuda(),device_ids=range(self.num_gpu))
if self.load_path:
self.load_model()
@staticmethod
def psnr(original, compared):
compared = Variable(compared.data, requires_grad=False)
d = nn.MSELoss()
arg_psnr = 0
for i in range(original.size(0)):
mse = d(original[i], compared[i])
try:
psnr = 10 * torch.log(4/ mse)/np.log(10)
arg_psnr = arg_psnr + psnr
except:
pass
arg_psnr = arg_psnr/original.size(0)
return arg_psnr
def build_model(self):
if self.dataset == 'toy':
self.D_F = DiscriminatorFC(2, 1, [self.config.fc_hidden_dim] * self.config.d_num_layer)
else:
a_height, a_width, a_channel = self.a_data_loader.shape
b_height, b_width, b_channel = self.b_data_loader.shape
a_channel = 1
b_channel = 1
if self.cnn_type == 0:
#conv_dims, deconv_dims = [64, 128, 256, 512], [512, 256, 128, 64]
conv_dims, deconv_dims = [64, 128, 256, 1024], [256, 128, 64]
elif self.cnn_type == 1:
#conv_dims, deconv_dims = [32, 64, 128, 256], [256, 128, 64, 32]
conv_dims, deconv_dims = [32, 64, 128, 512], [128, 64, 32]
else:
raise Exception("[!] cnn_type {} is not defined".format(self.cnn_type))
self.D_F = DiscriminatorCNN(
int(conv_dims[-1]/2), 1, deconv_dims, self.num_gpu)
self.D_AB = DecoderCNN(
int(conv_dims[-1]/2), b_channel, deconv_dims, self.num_gpu)
self.E_AB = EncoderCNN_1(
a_channel, conv_dims, self.num_gpu)
self.D_F.apply(weights_init)
self.D_AB.apply(weights_init)
self.E_AB.apply(weights_init)
def load_model(self):
#TODO:how to load model
print("[*] Load models from {}...".format(self.load_path))
paths = glob(os.path.join(self.load_path, 'G_AB_*.pth'))
paths.sort()
if len(paths) == 0:
print("[!] No checkpoint found in {}...".format(self.load_path))
return
idxes = [int(os.path.basename(path.split('.')[0].split('_')[-1])) for path in paths]
self.start_step = max(idxes)
if self.num_gpu == 0:
map_location = lambda storage, loc: storage
else:
map_location = None
G_AB_filename = '{}/G_AB_{}.pth'.format(self.load_path, self.start_step)
#todo: to change the load model function
'''
self.G_AB.load_state_dict(torch.load(G_AB_filename, map_location=map_location))
self.G_BA.load_state_dict(
torch.load('{}/G_BA_{}.pth'.format(self.load_path, self.start_step), map_location=map_location))
self.D_A.load_state_dict(
torch.load('{}/D_A_{}.pth'.format(self.load_path, self.start_step), map_location=map_location))
self.D_B.load_state_dict(
torch.load('{}/D_B_{}.pth'.format(self.load_path, self.start_step), map_location=map_location))
'''
print("[*] Model loaded: {}".format(G_AB_filename))
def train(self):
d = nn.MSELoss()
bce = nn.BCELoss()
real_label = 1
fake_label = 0
real_tensor = Variable(torch.FloatTensor(self.batch_size))
_ = real_tensor.data.fill_(real_label)
fake_tensor = Variable(torch.FloatTensor(self.batch_size))
_ = fake_tensor.data.fill_(fake_label)
rlfk_tensor = Variable(torch.FloatTensor(self.batch_size))
_ = rlfk_tensor.data.fill_(0.5)
if self.num_gpu > 0:
d.cuda()
bce.cuda()
real_tensor = real_tensor.cuda()
fake_tensor = fake_tensor.cuda()
rlfk_tensor = rlfk_tensor.cuda()
if self.optimizer == 'adam':
optimizer = torch.optim.Adam
else:
raise Exception("[!] Caution! Paper didn't use {} optimizer other than Adam".format(self.config.optimizer))
optimizer_Decoder = optimizer(
chain(self.D_AB.parameters(), self.E_AB.parameters()),
lr=self.lr, betas=(self.beta1, self.beta2))
optimizer_Encoder = optimizer(
chain(self.E_AB.parameters()),
lr=self.lr, betas=(self.beta1, self.beta2))
optimizer_Discriminator = optimizer(
chain(self.D_F.parameters()),
lr=self.lr, betas=(self.beta1, self.beta2), weight_decay=self.weight_decay)
A_loader, B_loader = iter(self.a_data_loader), iter(self.b_data_loader)
valid_x_A, valid_x_B = A_loader.next(), B_loader.next()
x_A_t2a=valid_x_A.numpy()
x_A_t2a, x_B_t2a =img_random_dis(x_A_t2a)
valid_x_A=torch.from_numpy(x_A_t2a)
valid_x_B=torch.from_numpy(x_B_t2a)
valid_x_A=valid_x_A.float()
valid_x_B=valid_x_B.float()
valid_x_A, valid_x_B = self._get_variable(valid_x_A), self._get_variable(valid_x_B)
vutils.save_image(valid_x_A.data*0.5+0.5, '{}/valid_x_A.png'.format(self.pic_dir))
vutils.save_image(valid_x_B.data*0.5+0.5, '{}/valid_x_B.png'.format(self.pic_dir))
for step in range(self.start_step, self.max_step):
try:
x_A_1, x_B_1 = A_loader.next(), B_loader.next()
except StopIteration:
A_loader, B_loader = iter(self.a_data_loader), iter(self.b_data_loader)
x_A_1, x_B_1 = A_loader.next(), B_loader.next()
if x_A_1.size(0) != x_B_1.size(0):
print("[!] Sampled dataset from A and B have different # of data. Try resampling...")
continue
x_A_t2a=x_A_1.numpy()
x_A_t2a, x_B_t2a =img_random_dis(x_A_t2a)
x_A=torch.from_numpy(x_A_t2a)
x_B=torch.from_numpy(x_B_t2a)
x_A=x_A.float()
x_B=x_B.float()
x_A, x_B = self._get_variable(x_A), self._get_variable(x_B)
batch_size = x_A.size(0)
real_tensor.data.resize_(batch_size).fill_(real_label)
fake_tensor.data.resize_(batch_size).fill_(fake_label)
rlfk_tensor.data.resize_(batch_size).fill_(0.5)
# update the D_F to separate the feature
self.D_F.zero_grad()
f_AB = self.E_AB(x_A)
f_AB_g = f_AB[:, 0:512, :, :]
f_AB_s = f_AB[:, 512:1024, :, :]
f_AB_g = f_AB_g.detach()
f_AB_s = f_AB_s.detach()
if self.loss == "log_prob":
l_df_B_real, l_df_B_fake = bce(self.D_F(f_AB_g), rlfk_tensor + 0.1), bce(self.D_F(f_AB_s),
rlfk_tensor - 0.1)
elif self.loss == "least_square":
l_df_B_real, l_df_B_fake = \
0.5 * torch.mean((self.D_F(f_AB_g) - 0.6) ** 2), 0.5 * torch.mean((self.D_F(f_AB_s) - 0.4) ** 2)
else:
raise Exception("[!] Unkown loss type: {}".format(self.loss))
l_df_B = l_df_B_real + l_df_B_fake
l_disciminator = l_df_B
l_disciminator.backward()
optimizer_Discriminator.step()
# update E_AB network
for e_step in range(200):
try:
x_A_1, x_B_1 = A_loader.next(), B_loader.next()
except StopIteration:
A_loader, B_loader = iter(self.a_data_loader), iter(self.b_data_loader)
x_A_1, x_B_1 = A_loader.next(), B_loader.next()
if x_A_1.size(0) != x_B_1.size(0):
print("[!] Sampled dataset from A and B have different # of data. Try resampling...")
continue
x_A_t2a=x_A_1.numpy()
x_A_t2a, x_B_t2a =img_random_dis(x_A_t2a)
x_A=torch.from_numpy(x_A_t2a)
x_B=torch.from_numpy(x_B_t2a)
x_A=x_A.float()
x_B=x_B.float()
x_A, x_B = self._get_variable(x_A), self._get_variable(x_B)
batch_size = x_A.size(0)
real_tensor.data.resize_(batch_size).fill_(real_label)
fake_tensor.data.resize_(batch_size).fill_(fake_label)
self.E_AB.zero_grad()
f_AB = self.E_AB(x_A)
f_AB_g = f_AB[:, 0:512, :, :]
f_AB_s = f_AB[:, 512:1024, :, :]
if self.loss == "log_prob":
l_gan_g = bce(self.D_F(f_AB_g), rlfk_tensor+0.1)
l_gan_s = bce(self.D_F(f_AB_s), rlfk_tensor-0.1)
elif self.loss == "least_square":
l_gan_g = 0.5 * torch.mean((self.D_F(f_AB_g) - 0.6)**2)
l_gan_s = 0.5 * torch.mean((self.D_F(f_AB_s) - 0.4)**2)
else:
raise Exception("[!] Unkown loss type: {}".format(self.loss))
l_encoder = l_gan_s + l_gan_g
l_encoder.backward()
optimizer_Encoder.step()
# update E_AB network
for e_step in range(100):
try:
x_A_1, x_B_1 = A_loader.next(), B_loader.next()
except StopIteration:
A_loader, B_loader = iter(self.a_data_loader), iter(self.b_data_loader)
x_A_1, x_B_1 = A_loader.next(), B_loader.next()
if x_A_1.size(0) != x_B_1.size(0):
print("[!] Sampled dataset from A and B have different # of data. Try resampling...")
continue
x_A_t2a=x_A_1.numpy()
x_A_t2a, x_B_t2a =img_random_dis(x_A_t2a)
x_A=torch.from_numpy(x_A_t2a)
x_B=torch.from_numpy(x_B_t2a)
x_A=x_A.float()
x_B=x_B.float()
x_A, x_B = self._get_variable(x_A), self._get_variable(x_B)
batch_size = x_A.size(0)
real_tensor.data.resize_(batch_size).fill_(real_label)
fake_tensor.data.resize_(batch_size).fill_(fake_label)
self.E_AB.zero_grad()
f_AB = self.E_AB(x_A)
f_AB_g = f_AB[:, 0:512, :, :]
f_AB_g_data = Variable(f_AB_g.data, requires_grad=False)
f_AB_H = self.E_AB(x_B)
f_AB_g_H = f_AB_H[:, 0:512, :, :]
f_AB_s_H = f_AB_H[:, 512:1024, :, :]
l_const_fg = d(f_AB_g_H, f_AB_g_data)
l_const_fs = torch.mean(torch.abs(f_AB_s_H))
l_const = l_const_fg + l_const_fs
l_const.backward()
optimizer_Encoder.step()
# update D_AB network
for d_step in range(300):
try:
x_A_1, x_B_1 = A_loader.next(), B_loader.next()
except StopIteration:
A_loader, B_loader = iter(self.a_data_loader), iter(self.b_data_loader)
x_A_1, x_B_1 = A_loader.next(), B_loader.next()
if x_A_1.size(0) != x_B_1.size(0):
print("[!] Sampled dataset from A and B have different # of data. Try resampling...")
continue
x_A_t2a = x_A_1.numpy()
x_A_t2a, x_B_t2a = img_random_dis(x_A_t2a)
x_A = torch.from_numpy(x_A_t2a)
x_B = torch.from_numpy(x_B_t2a)
x_A = x_A.float()
x_B = x_B.float()
x_A, x_B = self._get_variable(x_A), self._get_variable(x_B)
batch_size = x_A.size(0)
real_tensor.data.resize_(batch_size).fill_(real_label)
fake_tensor.data.resize_(batch_size).fill_(fake_label)
self.E_AB.zero_grad()
self.D_AB.zero_grad()
f_AB = self.E_AB(x_A)
f_AB_g = f_AB[:, 0:512, :, :]
f_AB_s = f_AB[:, 512:1024, :, :]
x_H = self.D_AB(f_AB_g)
l_const_H = d(x_H, x_B)
x_L = self.D_AB(f_AB_g + f_AB_s)
l_const_L = d(x_L, x_A)
psnr_H = self.psnr(x_B, x_H)
psnr_L = self.psnr(x_A, x_L)
l_decoder = l_const_H + l_const_L
l_decoder.backward()
optimizer_Decoder.step()
if step % self.log_step == 0:
print("[{}/{}] l_discrimimator: {:.4f} l_df_real: {:.4f} l_df_fake: {:.4f}". \
format(step, self.max_step, l_disciminator.data[0], l_df_B_real.data[0], l_df_B_fake.data[0]))
print("[{}/{}] l_encoder: {:.4f} l_gan_g: {:.4f}, l_gan_s: {:.4f} l_const_fg: {:.4f} l_const_fs: {:.4f}". \
format(step, self.max_step, l_encoder.data[0], l_gan_g.data[0],
l_gan_s.data[0], l_const_fg.data[0], l_const_fs.data[0]))
print("[{}/{}] l_decoder: {:.4f} l_const_H: {:.4f} l_const_L: {:.4f}". \
format(step, self.max_step, l_decoder.data[0], l_const_H.data[0], l_const_L.data[0]))
print("[{}/{}] psnr_H: {:.4f} psnr_L: {:.4f}".format(step, self.max_step, psnr_H.data[0], psnr_L.data[0]))
self.generate_with_A(valid_x_A, self.pic_dir, idx=step)
# self.generate_with_B(valid_x_B, self.model_dir, idx=step)
if step % self.save_step == self.save_step - 1:
print("[*] Save models to {}...".format(self.model_dir))
torch.save(self.E_AB.state_dict(), '{}/E_AB_{}.pth'.format(self.model_dir, step))
torch.save(self.D_AB.state_dict(), '{}/D_AB_{}.pth'.format(self.model_dir, step))
torch.save(self.D_F.state_dict(), '{}/D_F_{}.pth'.format(self.model_dir, step))
# torch.save(self.D_B.state_dict(), '{}/D_B_{}.pth'.format(self.model_dir, step))
def generate_with_A(self, inputs, path, idx=None):
f_AB = self.E_AB(inputs)
f_AB_g = f_AB[:, 0:512:, :, :]
f_AB_s = f_AB[:, 512:1024, :, :]
f_zero = torch.zeros(f_AB_g.size())
f_zero = Variable(f_zero.cuda())
x_H = self.D_AB(f_AB_g)
x_S = self.D_AB(f_AB_s)
x_L = self.D_AB(f_AB_g+f_AB_s)
x_zero = self.D_AB(f_zero)
x_H_path = '{}/{}_x_H.png'.format(path, idx)
x_S_path = '{}/{}_x_S.png'.format(path, idx)
x_L_path = '{}/{}_x_L.png'.format(path, idx)
x_zero_path = '{}/{}_x_zero.png'.format(path, idx)
vutils.save_image(x_H.data*0.5+0.5, x_H_path)
print("[*] Samples saved: {}".format(x_H_path))
vutils.save_image(x_S.data*0.5+0.5, x_S_path)
print("[*] Samples saved: {}".format(x_S_path))
vutils.save_image(x_L.data*0.5+0.5, x_L_path)
print("[*] Samples saved: {}".format(x_L_path))
vutils.save_image(x_zero.data*0.5+0.5, x_zero_path)
print("[*] Samples saved: {}".format(x_zero_path))
def generate_with_A_test(self, inputs, inputs2, path, idx=None):
f_AB = self.E_AB(inputs)
f_AB_s0 = torch.zeros([f_AB.size()[0], 1, f_AB.size()[2], f_AB.size()[3]])
f_AB_s0 = Variable(f_AB_s0)
f_AB_s = f_AB[:, 511:512, :, :]
f_AB_g0 = torch.Tensor(f_AB.size()[0], 511, f_AB.size()[2], f_AB.size()[3]).uniform_(0,
1) # torch.zeros([f_AB.size()[0],511,f_AB.size()[2],f_AB.size()[3]])
f_AB_g0 = Variable(f_AB_g0)
f_AB_g = f_AB[:, 0:511, :, :]
f_max = torch.cat((f_AB_g0, f_AB_s), 1)
x_AB = self.D_AB(f_AB)
x_max = self.D_AB(f_max)
x_AB_path = '{}/{}_x_AB.png'.format(path, idx)
x_max_path = '{}/{}_x_max.png'.format(path, idx)
vutils.save_image(x_AB.data, x_AB_path)
print("[*] Samples saved: {}".format(x_AB_path))
vutils.save_image(x_max.data, x_max_path)
print("[*] Samples saved: {}".format(x_max_path))
'''
def generate_with_B(self, inputs, path, idx=None):
x_BA = self.G_BA(inputs)
x_BAB = self.G_AB(x_BA)
x_BA_path = '{}/{}_x_BA.png'.format(path, idx)
x_BAB_path = '{}/{}_x_BAB.png'.format(path, idx)
vutils.save_image(x_BA.data, x_BA_path)
print("[*] Samples saved: {}".format(x_BA_path))
vutils.save_image(x_BAB.data, x_BAB_path)
print("[*] Samples saved: {}".format(x_BAB_path))
'''
def generate_infinitely(self, inputs, path, input_type, count=10, nrow=2, idx=None):
# todo to debug
if input_type.lower() == "a":
iterator = [self.G_AB, self.G_BA] * count
elif input_type.lower() == "b":
iterator = [self.G_BA, self.G_AB] * count
out = inputs
for step, model in enumerate(iterator):
out = model(out)
out_path = '{}/{}_x_{}_#{}.png'.format(path, idx, input_type, step)
vutils.save_image(out.data, out_path, nrow=nrow)
print("[*] Samples saved: {}".format(out_path))
def test(self):
batch_size = self.config.sample_per_image
A_loader, B_loader = iter(self.a_data_loader), iter(self.b_data_loader)
test_dir = os.path.join(self.model_dir, 'test')
if not os.path.exists(test_dir):
os.makedirs(test_dir)
step = 0
while True:
try:
x_A,x_B = self._get_variable(A_loader.next()), self._get_variable(B_loader.next())
except StopIteration:
print("[!] Test sample generation finished. Samples are in {}".format(test_dir))
break
vutils.save_image(x_A.data, '{}/{}_x_A.png'.format(test_dir, step))
vutils.save_image(x_B.data, '{}/{}_x_B.png'.format(test_dir, step))
self.generate_with_A_test(x_A, x_B, test_dir, idx=step)
step += 1
def _get_variable(self, inputs):
if self.num_gpu > 0:
out = Variable(inputs.cuda())
else:
out = Variable(inputs)
return out
<file_sep>/debug.py
import cv2
import numpy as np
import torchvision.utils as vutils
import torch
img = cv2.imread('000012.jpg')
print(img.shape)
# img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# img = np.expand_dims(img, axis = 2)
img = np.mean(img, axis = 2)
imres = 6
sigma = 30
img = cv2.resize(img, (96 + 16*imres, 128+16*imres), interpolation =
cv2.INTER_CUBIC)
img1 = cv2.resize(img,None,fx=1.0/4.0, fy=1.0/4.0, interpolation = cv2.INTER_CUBIC)
noise= sigma*np.random.randn(img1.shape[0],img1.shape[1])
img1 = img1+noise
img1 = cv2.resize(img1,None,fx=1.0*4.0, fy=1.0*4.0, interpolation = cv2.INTER_NEAREST) #up_sample method
img1 = np.expand_dims(img1,axis=2)
img = np.expand_dims(img, axis=2)
cv2.imwrite('test_change_1.png', img)
cv2.imwrite('test_change_1_noise.png',img1)
img = np.transpose(img,(2,0,1))
img1 = np.transpose(img1,(2,0,1))
#img = np.expand_dims(img, axis = 0)
#out of img_random_...
img = (img/255-0.5)*2
img1 = (img1/255-0.5)*2
img = torch.from_numpy(img)
img1 = torch.from_numpy(img1)
img = img.float()
img1 = img1.float()
vutils.save_image(img1,'test_change_2_noise.png')
vutils.save_image(img,'test_change_2.png')
'''another part'''
import os
from data_loader import Dataset
b_data_set = Dataset("data", [218,178,3],"test",False)
b_data_loader = torch.utils.data.DataLoader(dataset=b_data_set,
batch_size=1,
shuffle=False,
num_workers=2)
b_data_loader.shape = b_data_set.shape
B_loader = iter(b_data_loader)
valid_x_B = B_loader.next()
vutils.save_image(valid_x_B*0.5+0.5,"test_change_3.png")
<file_sep>/trainer_3models.py
from __future__ import print_function
import numpy as np
import os
from glob import glob
# from tqdm import trange
from itertools import chain
import torch
from torch import nn
import torch.nn.parallel
import torchvision.utils as vutils
from torch.autograd import Variable
from models import *
from data_loader import get_loader
from img_random_discmp import img_random_dis
def weights_init(m):
classname = m.__class__.__name__
if classname.find('Conv') != -1:
m.weight.data.normal_(0.0, 0.02)
elif classname.find('BatchNorm') != -1:
m.weight.data.normal_(1.0, 0.02)
m.bias.data.fill_(0)
class Trainer(object):
def __init__(self, config, a_data_loader, b_data_loader):
self.config = config
self.a_data_loader = a_data_loader
self.b_data_loader = b_data_loader
self.num_gpu = config.num_gpu
self.dataset= config.dataset
self.loss = config.loss
self.lr = config.lr
self.beta1 = config.beta1
self.beta2 = config.beta2
self.optimizer = config.optimizer
self.batch_size = config.batch_size
self.weight_decay = config.weight_decay
self.cnn_type = config.cnn_type
self.model_dir = config.model_dir
self.pic_dir = config.pic_dir
self.load_path = config.load_path
self.start_step = 0
self.log_step = config.log_step
self.max_step = config.max_step
self.save_step = config.save_step
self.build_model()
if self.num_gpu == 1:
self.D_H.cuda()
self.D_L.cuda()
self.D_F.cuda()
self.D_AB.cuda()
self.D_BA.cuda()
self.D_FB.cuda()
self.E_AB.cuda()
elif self.num_gpu > 1:
self.D_H = nn.DataParallel(self.D_H.cuda(),device_ids=range(self.num_gpu))
self.D_L = nn.DataParallel(self.D_L.cuda(),device_ids=range(self.num_gpu))
self.D_F = nn.DataParallel(self.D_F.cuda(),device_ids=range(self.num_gpu))
self.D_AB = nn.DataParallel(self.D_AB.cuda(),device_ids=range(self.num_gpu))
self.D_BA = nn.DataParallel(self.D_BA.cuda(),device_ids=range(self.num_gpu))
self.D_FB = nn.DataParallel(self.D_FB.cuda(),device_ids=range(self.num_gpu))
self.E_AB = nn.DataParallel(self.E_AB.cuda(),device_ids=range(self.num_gpu))
if self.load_path:
self.load_model()
@staticmethod
def psnr(original, compared):
d = nn.MSELoss()
arg_psnr = 0
for i in range(original.size(0)):
mse = d(original[i], compared[i])
try:
psnr = 10 * torch.log(4/ mse)/np.log(10)
except:
pass
arg_psnr = arg_psnr + psnr
arg_psnr = arg_psnr/original.size(0)
return arg_psnr
def build_model(self):
if self.dataset == 'toy':
self.D_H = DiscriminatorFC(2, 1, [self.config.fc_hidden_dim] * self.config.d_num_layer)
self.D_L = DiscriminatorFC(2, 1, [self.config.fc_hidden_dim] * self.config.d_num_layer)
else:
a_height, a_width, a_channel = self.a_data_loader.shape
b_height, b_width, b_channel = self.b_data_loader.shape
a_channel = 1
b_channel = 1
if self.cnn_type == 0:
#conv_dims, deconv_dims = [64, 128, 256, 512], [512, 256, 128, 64]
conv_dims, deconv_dims = [64, 128, 256, 512], [256, 128, 64]
elif self.cnn_type == 1:
#conv_dims, deconv_dims = [32, 64, 128, 256], [256, 128, 64, 32]
conv_dims, deconv_dims = [32, 64, 128, 256], [128, 64, 32]
else:
raise Exception("[!] cnn_type {} is not defined".format(self.cnn_type))
self.D_H = DiscriminatorCNN(
a_channel, 1, conv_dims, self.num_gpu)
self.D_L = DiscriminatorCNN(
b_channel, 1, conv_dims, self.num_gpu)
self.D_F = DiscriminatorCNN(
a_channel, 1, conv_dims, self.num_gpu)
self.D_AB = DecoderCNN(
conv_dims[-1], b_channel, deconv_dims, self.num_gpu)
self.D_BA = DecoderCNN(
conv_dims[-1], b_channel, deconv_dims, self.num_gpu)
self.D_FB = DecoderCNN(
conv_dims[-1], b_channel, deconv_dims, self.num_gpu)
self.E_AB = EncoderCNN_1(
a_channel, conv_dims, self.num_gpu)
self.D_H.apply(weights_init)
self.D_L.apply(weights_init)
self.D_F.apply(weights_init)
self.D_AB.apply(weights_init)
self.D_BA.apply(weights_init)
self.D_FB.apply(weights_init)
self.E_AB.apply(weights_init)
def load_model(self):
#TODO:how to load model
print("[*] Load models from {}...".format(self.load_path))
paths = glob(os.path.join(self.load_path, 'G_AB_*.pth'))
paths.sort()
if len(paths) == 0:
print("[!] No checkpoint found in {}...".format(self.load_path))
return
idxes = [int(os.path.basename(path.split('.')[0].split('_')[-1])) for path in paths]
self.start_step = max(idxes)
if self.num_gpu == 0:
map_location = lambda storage, loc: storage
else:
map_location = None
G_AB_filename = '{}/G_AB_{}.pth'.format(self.load_path, self.start_step)
#todo: to change the load model function
'''
self.G_AB.load_state_dict(torch.load(G_AB_filename, map_location=map_location))
self.G_BA.load_state_dict(
torch.load('{}/G_BA_{}.pth'.format(self.load_path, self.start_step), map_location=map_location))
self.D_A.load_state_dict(
torch.load('{}/D_A_{}.pth'.format(self.load_path, self.start_step), map_location=map_location))
self.D_B.load_state_dict(
torch.load('{}/D_B_{}.pth'.format(self.load_path, self.start_step), map_location=map_location))
'''
print("[*] Model loaded: {}".format(G_AB_filename))
def train(self):
d = nn.MSELoss()
bce = nn.BCELoss()
real_label = 1
fake_label = 0
real_tensor = Variable(torch.FloatTensor(self.batch_size))
_ = real_tensor.data.fill_(real_label)
fake_tensor = Variable(torch.FloatTensor(self.batch_size))
_ = fake_tensor.data.fill_(fake_label)
rlfk_tensor = Variable(torch.FloatTensor(self.batch_size))
_ = rlfk_tensor.data.fill_(0.5)
if self.num_gpu > 0:
d.cuda()
bce.cuda()
real_tensor = real_tensor.cuda()
fake_tensor = fake_tensor.cuda()
rlfk_tensor = rlfk_tensor.cuda()
if self.optimizer == 'adam':
optimizer = torch.optim.Adam
else:
raise Exception("[!] Caution! Paper didn't use {} opimizer other than Adam".format(self.config.optimizer))
optimizer_1_g = optimizer(
chain(self.E_AB.parameters(), self.D_AB.parameters()),
lr=self.lr, betas=(self.beta1, self.beta2), weight_decay=self.weight_decay)
optimizer_1_d = optimizer(
chain(self.D_H.parameters()),
lr=self.lr, betas=(self.beta1, self.beta2), weight_decay=self.weight_decay)
optimizer_2_g = optimizer(
chain(self.E_AB.parameters(), self.D_BA.parameters()),
lr=self.lr, betas=(self.beta1, self.beta2), weight_decay=self.weight_decay)
optimizer_2_d = optimizer(
chain(self.D_L.parameters()),
lr=self.lr, betas=(self.beta1, self.beta2))
optimizer_3_g = optimizer(
chain(self.E_AB.parameters(), self.D_FB.parameters()),
lr=self.lr, betas=(self.beta1, self.beta2), weight_decay=self.weight_decay)
optimizer_3_d = optimizer(
chain(self.D_F.parameters()),
lr=self.lr, betas=(self.beta1, self.beta2))
A_loader, B_loader = iter(self.a_data_loader), iter(self.b_data_loader)
valid_x_A, valid_x_B = A_loader.next(), B_loader.next()
x_A_t2a=valid_x_A.numpy()
#x_B_t2a=x_B.numpy()
x_A_t2a, x_B_t2a =img_random_dis(x_A_t2a)
valid_x_A=torch.from_numpy(x_A_t2a)
valid_x_B=torch.from_numpy(x_B_t2a)
valid_x_A=valid_x_A.float()
valid_x_B=valid_x_B.float()
valid_x_A, valid_x_B = self._get_variable(valid_x_A), self._get_variable(valid_x_B)
vutils.save_image(valid_x_A.data, '{}/valid_x_A.png'.format(self.model_dir))
vutils.save_image(valid_x_B.data, '{}/valid_x_B.png'.format(self.model_dir))
for step in range(self.start_step, self.max_step):
try:
x_A_1, x_B_1 = A_loader.next(), B_loader.next()
except StopIteration:
A_loader, B_loader = iter(self.a_data_loader), iter(self.b_data_loader)
x_A_1, x_B_1 = A_loader.next(), B_loader.next()
if x_A_1.size(0) != x_B_1.size(0):
print("[!] Sampled dataset from A and B have different # of data. Try resampling...")
continue
x_A_t2a=x_A_1.numpy()
x_A_t2a, x_B_t2a =img_random_dis(x_A_t2a)
x_A=torch.from_numpy(x_A_t2a)
x_B=torch.from_numpy(x_B_t2a)
x_A=x_A.float()
x_B=x_B.float()
x_A, x_B = self._get_variable(x_A), self._get_variable(x_B)
batch_size = x_A.size(0)
real_tensor.data.resize_(batch_size).fill_(real_label)
fake_tensor.data.resize_(batch_size).fill_(fake_label)
rlfk_tensor.data.resize_(batch_size).fill_(0.5)
'''update the first model: L to H'''
# update D_H network
self.D_H.zero_grad()
f_AB = self.E_AB(x_A)
f_AB_g = f_AB[:, 0:511:, :, :]
f_AB_s = f_AB[:, 511:512, :, :]
f_AB_s0 = torch.zeros([f_AB.size()[0], 1, f_AB.size()[2], f_AB.size()[3]])
f_AB_s0 = Variable(f_AB_s0.cuda())
f_AB_g0 = torch.zeros([f_AB.size()[0], 511, f_AB.size()[2], f_AB.size()[3]])
f_AB_g0 = Variable(f_AB_g0.cuda())
f_max = torch.cat((f_AB_g, f_AB_s0), 1)
f_min = torch.cat((f_AB_g0, f_AB_s), 1)
x_H = self.D_AB(f_max).detach()
if self.loss == "log_prob":
l_dh_B_real, l_dh_B_fake = bce(self.D_H(x_B), real_tensor), bce(self.D_H(x_H), fake_tensor)
elif self.loss == "least_square":
l_dh_B_real, l_dh_B_fake = \
0.5 * torch.mean((self.D_H(x_B) - 1)**2), 0.5 * torch.mean((self.D_H(x_H))**2)
else:
raise Exception("[!] Unknown loss type: {}".format(self.loss))
l_dh_B = l_dh_B_real + l_dh_B_fake
l_dh = l_dh_B
l_dh.backward()
optimizer_1_d.step()
# update D_AB network
for gab_step in range(20):
try:
x_A_1, x_B_1 = A_loader.next(), B_loader.next()
except StopIteration:
A_loader, B_loader = iter(self.a_data_loader), iter(self.b_data_loader)
x_A_1, x_B_1 = A_loader.next(), B_loader.next()
if x_A_1.size(0) != x_B_1.size(0):
print("[!] Sampled dataset from A and B have different # of data. Try resampling...")
continue
x_A_t2a=x_A_1.numpy()
x_A_t2a, x_B_t2a =img_random_dis(x_A_t2a)
x_A=torch.from_numpy(x_A_t2a)
x_B=torch.from_numpy(x_B_t2a)
x_A=x_A.float()
x_B=x_B.float()
x_A, x_B = self._get_variable(x_A), self._get_variable(x_B)
batch_size = x_A.size(0)
real_tensor.data.resize_(batch_size).fill_(real_label)
fake_tensor.data.resize_(batch_size).fill_(fake_label)
self.E_AB.zero_grad()
self.D_AB.zero_grad()
f_AB = self.E_AB(x_A)
f_AB_g = f_AB[:, 0:511:, :, :]
f_AB_s = f_AB[:, 511:512, :, :]
f_AB_s0 = torch.zeros([f_AB.size()[0], 1, f_AB.size()[2], f_AB.size()[3]])
f_AB_s0 = Variable(f_AB_s0.cuda())
f_AB_g0 = torch.zeros([f_AB.size()[0], 511, f_AB.size()[2], f_AB.size()[3]])
f_AB_g0 = Variable(f_AB_g0.cuda())
f_max = torch.cat((f_AB_g, f_AB_s0), 1)
f_min = torch.cat((f_AB_g0, f_AB_s), 1)
x_H = self.D_AB(f_max)
l_const_AB = d(x_H, x_B)
dh_x_AB = self.D_H(x_H)
if self.loss == "log_prob":
l_gan_AB = bce(dh_x_AB, real_tensor)
elif self.loss == "least_square":
l_gan_AB = 0.5 * torch.mean((dh_x_AB - 1)**2)
else:
raise Exception("[!] Unkown loss type: {}".format(self.loss))
l_gh = 10*l_const_AB + l_gan_AB
l_gh.backward()
optimizer_1_g.step()
'''update the second model: L to L'''
# update D_L network
self.D_L.zero_grad()
f_AB = self.E_AB(x_A)
f_AB_g = f_AB[:, 0:511:, :, :]
f_AB_s = f_AB[:, 511:512, :, :]
f_AB_s0 = torch.zeros([f_AB.size()[0], 1, f_AB.size()[2], f_AB.size()[3]])
f_AB_s0 = Variable(f_AB_s0.cuda())
f_AB_g0 = torch.zeros([f_AB.size()[0], 511, f_AB.size()[2], f_AB.size()[3]])
f_AB_g0 = Variable(f_AB_g0.cuda())
f_max = torch.cat((f_AB_g, f_AB_s0), 1)
f_min = torch.cat((f_AB_g0, f_AB_s), 1)
x_L = self.D_BA(f_AB).detach()
if self.loss == "log_prob":
l_dl_A_real, l_dl_A_fake = bce(self.D_L(x_A), real_tensor), bce(self.D_L(x_L), fake_tensor)
elif self.loss == "least_square":
l_dl_A_real, l_dl_A_fake = \
0.5 * torch.mean((self.D_L(x_A) - 1) ** 2), 0.5 * torch.mean((self.D_L(x_L)) ** 2)
else:
raise Exception("[!] Unknown loss type: {}".format(self.loss))
l_dl_A = l_dl_A_real + l_dl_A_fake
l_dl = l_dl_A
l_dl.backward()
optimizer_2_d.step()
# update D_BA network
for gba_step in range(20):
try:
x_A_1, x_B_1 = A_loader.next(), B_loader.next()
except StopIteration:
A_loader, B_loader = iter(self.a_data_loader), iter(self.b_data_loader)
x_A_1, x_B_1 = A_loader.next(), B_loader.next()
if x_A_1.size(0) != x_B_1.size(0):
print("[!] Sampled dataset from A and B have different # of data. Try resampling...")
continue
x_A_t2a = x_A_1.numpy()
x_A_t2a, x_B_t2a = img_random_dis(x_A_t2a)
x_A = torch.from_numpy(x_A_t2a)
x_B = torch.from_numpy(x_B_t2a)
x_A = x_A.float()
x_B = x_B.float()
x_A, x_B = self._get_variable(x_A), self._get_variable(x_B)
batch_size = x_A.size(0)
real_tensor.data.resize_(batch_size).fill_(real_label)
fake_tensor.data.resize_(batch_size).fill_(fake_label)
self.E_AB.zero_grad()
self.D_BA.zero_grad()
f_AB = self.E_AB(x_A)
f_AB_g = f_AB[:, 0:511:, :, :]
f_AB_s = f_AB[:, 511:512, :, :]
f_AB_s0 = torch.zeros([f_AB.size()[0], 1, f_AB.size()[2], f_AB.size()[3]])
f_AB_s0 = Variable(f_AB_s0.cuda())
f_AB_g0 = torch.zeros([f_AB.size()[0], 511, f_AB.size()[2], f_AB.size()[3]])
f_AB_g0 = Variable(f_AB_g0.cuda())
f_max = torch.cat((f_AB_g, f_AB_s0), 1)
f_min = torch.cat((f_AB_g0, f_AB_s), 1)
x_L = self.D_BA(f_AB)
l_const_AFA = d(x_L, x_A)
dl_x_AA = self.D_L(x_L)
if self.loss == "log_prob":
l_gan_AA = bce(dl_x_AA, real_tensor)
elif self.loss == "least_square":
l_gan_AA = 0.5 * torch.mean((dl_x_AA - 1) ** 2)
else:
raise Exception("[!] Unkown loss type: {}".format(self.loss))
l_gl = 10*l_const_AFA + l_gan_AA
l_gl.backward()
optimizer_2_g.step()
'''update the third model, F to ?'''
self.D_F.zero_grad()
f_AB = self.E_AB(x_A)
f_AB_g = f_AB[:, 0:511:, :, :]
f_AB_s = f_AB[:, 511:512, :, :]
f_AB_s0 = torch.zeros([f_AB.size()[0], 1, f_AB.size()[2], f_AB.size()[3]])
f_AB_s0 = Variable(f_AB_s0.cuda())
f_AB_g0 = torch.zeros([f_AB.size()[0], 511, f_AB.size()[2], f_AB.size()[3]])
f_AB_g0 = Variable(f_AB_g0.cuda())
f_max = torch.cat((f_AB_g, f_AB_s0), 1)
f_min = torch.cat((f_AB_g0, f_AB_s), 1)
x_FB = self.D_FB(f_AB).detach()
x_max = self.D_FB(f_max).detach()
if self.loss == "log_prob":
l_df_B_real, l_df_B_fake = bce(self.D_F(x_FB), rlfk_tensor + 0.1), bce(self.D_F(x_max),
rlfk_tensor - 0.1)
elif self.loss == "least_square":
l_df_B_real, l_df_B_fake = \
0.5 * torch.mean((self.D_F(x_FB) - 0.6) ** 2), 0.5 * torch.mean((self.D_F(x_max) - 0.4) ** 2)
else:
raise Exception("[!] Unkown loss type: {}".format(self.loss))
l_df_B = l_df_B_real + l_df_B_fake
l_df = l_df_B
l_df.backward()
optimizer_3_d.step()
# update D_FB network
for gfb_step in range(1):
try:
x_A_1, x_B_1 = A_loader.next(), B_loader.next()
except StopIteration:
A_loader, B_loader = iter(self.a_data_loader), iter(self.b_data_loader)
x_A_1, x_B_1 = A_loader.next(), B_loader.next()
if x_A_1.size(0) != x_B_1.size(0):
print("[!] Sampled dataset from A and B have different # of data. Try resampling...")
continue
x_A_t2a = x_A_1.numpy()
x_A_t2a, x_B_t2a = img_random_dis(x_A_t2a)
x_A = torch.from_numpy(x_A_t2a)
x_B = torch.from_numpy(x_B_t2a)
x_A = x_A.float()
x_B = x_B.float()
x_A, x_B = self._get_variable(x_A), self._get_variable(x_B)
batch_size = x_A.size(0)
real_tensor.data.resize_(batch_size).fill_(real_label)
fake_tensor.data.resize_(batch_size).fill_(fake_label)
rlfk_tensor.data.resize_(batch_size).fill_(0.5)
self.D_FB.zero_grad()
self.E_AB.zero_grad()
f_AB = self.E_AB(x_A)
f_AB_g = f_AB[:, 0:511:, :, :]
f_AB_s = f_AB[:, 511:512, :, :]
f_AB_s0 = torch.zeros([f_AB.size()[0], 1, f_AB.size()[2], f_AB.size()[3]])
f_AB_s0 = Variable(f_AB_s0.cuda())
f_AB_g0 = torch.zeros([f_AB.size()[0], 511, f_AB.size()[2], f_AB.size()[3]])
f_AB_g0 = Variable(f_AB_g0.cuda())
f_max = torch.cat((f_AB_g, f_AB_s0), 1)
f_min = torch.cat((f_AB_g0, f_AB_s), 1)
x_FB = self.D_FB(f_AB)
x_min = self.D_FB(f_min)
x_max = self.D_FB(f_max)
l_const_FA = d(x_FB, x_A)
l_const_min = d(x_min, x_A)
l_const_max = d(x_max, x_A)
if self.loss == "log_prob":
l_gan_A = bce(self.D_F(x_FB), rlfk_tensor + 0.1)
l_gan_B = bce(self.D_F(x_max), rlfk_tensor - 0.1)
elif self.loss == "least_square":
l_gan_A = 0.5 * torch.mean((self.D_F(x_FB) - 0.6) ** 2)
l_gan_B = 0.5 * torch.mean((self.D_F(x_max) - 0.4) ** 2)
else:
raise Exception("[!] Unkown loss type: {}".format(self.loss))
l_gf = 1 * (l_const_FA) + l_gan_A + l_gan_B
l_gf.backward()
optimizer_3_g.step()
if step % self.log_step == 0:
print("[{}/{}] l_dh: {:.4f} l_gan_AB: {:.4f} l_const_AB: {:.4f}". \
format(step, self.max_step, l_dh.data[0], l_dl.data[0], l_const_AB.data[0]))
print("[{}/{}] l_dl: {:.4f} l_gan_AA: {:.4f}, l_const_AFA: {:.4f}". \
format(step, self.max_step, l_dl.data[0], l_gan_AA.data[0],
l_const_AFA.data[0] ))
print("[{}/{}] l_df: {:.4f} l_gan_A: {:.4f} l_gan_B: {:.4f} l_const_FA: {:.4f}". \
format(step, self.max_step, l_df.data[0], l_gan_A.data[0], l_gan_B.data[0],
l_const_FA.data[0] ))
self.generate_with_A(valid_x_A, self.pic_dir, idx=step)
# self.generate_with_B(valid_x_B, self.model_dir, idx=step)
if step % self.save_step == self.save_step - 1:
print("[*] Save models to {}...".format(self.model_dir))
torch.save(self.E_AB.state_dict(), '{}/E_AB_{}.pth'.format(self.model_dir, step))
torch.save(self.D_AB.state_dict(), '{}/D_AB_{}.pth'.format(self.model_dir, step))
# torch.save(self.D_A.state_dict(), '{}/D_A_{}.pth'.format(self.model_dir, step))
# torch.save(self.D_B.state_dict(), '{}/D_B_{}.pth'.format(self.model_dir, step))
def generate_with_A(self, inputs, path, idx=None):
f_AB = self.E_AB(inputs)
f_AB_g = f_AB[:, 0:511:, :, :]
f_AB_s = f_AB[:, 511:512, :, :]
f_AB_s0 = torch.zeros([f_AB.size()[0], 1, f_AB.size()[2], f_AB.size()[3]])
f_AB_s0 = Variable(f_AB_s0.cuda())
f_AB_g0 = torch.zeros([f_AB.size()[0], 511, f_AB.size()[2], f_AB.size()[3]])
f_AB_g0 = Variable(f_AB_g0.cuda())
f_max = torch.cat((f_AB_g, f_AB_s0), 1)
f_min = torch.cat((f_AB_g0, f_AB_s), 1)
x_H = self.D_AB(f_max)
x_S = self.D_AB(f_min)
x_H_full = self.D_AB(f_AB)
x_H_path = '{}/{}_x_H.png'.format(path, idx)
x_S_path = '{}/{}_x_S.png'.format(path, idx)
x_H_full_path = '{}/{}_x_H_ful.png'.format(path, idx)
vutils.save_image(x_H.data, x_H_path)
print("[*] Samples saved: {}".format(x_H_path))
vutils.save_image(x_S.data, x_S_path)
print("[*] Samples saved: {}".format(x_S_path))
vutils.save_image(x_H_full.data, x_H_full_path)
print("[*] Samples saved:{}".format(x_H_full_path))
def generate_with_A_test(self, inputs, inputs2, path, idx=None):
f_AB = self.E_AB(inputs)
f_AB_s0 = torch.zeros([f_AB.size()[0], 1, f_AB.size()[2], f_AB.size()[3]])
f_AB_s0 = Variable(f_AB_s0)
f_AB_s = f_AB[:, 511:512, :, :]
f_AB_g0 = torch.Tensor(f_AB.size()[0], 511, f_AB.size()[2], f_AB.size()[3]).uniform_(0,
1) # torch.zeros([f_AB.size()[0],511,f_AB.size()[2],f_AB.size()[3]])
print(f_AB_g0.size())
f_AB_g0 = Variable(f_AB_g0)
f_AB_g = f_AB[:, 0:511, :, :]
f_max = torch.cat((f_AB_g0, f_AB_s), 1)
x_AB = self.D_AB(f_AB)
x_max = self.D_AB(f_max)
x_AB_path = '{}/{}_x_AB.png'.format(path, idx)
x_max_path = '{}/{}_x_max.png'.format(path, idx)
vutils.save_image(x_AB.data, x_AB_path)
print("[*] Samples saved: {}".format(x_AB_path))
vutils.save_image(x_max.data, x_max_path)
print("[*] Samples saved: {}".format(x_max_path))
'''
def generate_with_B(self, inputs, path, idx=None):
x_BA = self.G_BA(inputs)
x_BAB = self.G_AB(x_BA)
x_BA_path = '{}/{}_x_BA.png'.format(path, idx)
x_BAB_path = '{}/{}_x_BAB.png'.format(path, idx)
vutils.save_image(x_BA.data, x_BA_path)
print("[*] Samples saved: {}".format(x_BA_path))
vutils.save_image(x_BAB.data, x_BAB_path)
print("[*] Samples saved: {}".format(x_BAB_path))
'''
def generate_infinitely(self, inputs, path, input_type, count=10, nrow=2, idx=None):
# todo to debug
if input_type.lower() == "a":
iterator = [self.G_AB, self.G_BA] * count
elif input_type.lower() == "b":
iterator = [self.G_BA, self.G_AB] * count
out = inputs
for step, model in enumerate(iterator):
out = model(out)
out_path = '{}/{}_x_{}_#{}.png'.format(path, idx, input_type, step)
vutils.save_image(out.data, out_path, nrow=nrow)
print("[*] Samples saved: {}".format(out_path))
def test(self):
batch_size = self.config.sample_per_image
A_loader, B_loader = iter(self.a_data_loader), iter(self.b_data_loader)
test_dir = os.path.join(self.model_dir, 'test')
if not os.path.exists(test_dir):
os.makedirs(test_dir)
step = 0
while True:
try:
x_A,x_B = self._get_variable(A_loader.next()), self._get_variable(B_loader.next())
except StopIteration:
print("[!] Test sample generation finished. Samples are in {}".format(test_dir))
break
vutils.save_image(x_A.data, '{}/{}_x_A.png'.format(test_dir, step))
vutils.save_image(x_B.data, '{}/{}_x_B.png'.format(test_dir, step))
self.generate_with_A_test(x_A, x_B, test_dir, idx=step)
step += 1
def _get_variable(self, inputs):
if self.num_gpu > 0:
out = Variable(inputs.cuda())
else:
out = Variable(inputs)
return out
<file_sep>/main.py
#!/usr/local/bin/bash
import torch
from trainer import Trainer
from config import get_config
from data_loader import get_loader
from utils import prepare_dirs_and_logger, save_config
def main(config):
prepare_dirs_and_logger(config)
torch.manual_seed(config.random_seed)
if config.num_gpu > 0:
torch.cuda.manual_seed(config.random_seed)
if config.is_train:
data_path = config.data_path
batch_size = config.batch_size
else:
if config.test_data_path is None:
data_path = config.data_path
else:
data_path = config.test_data_path
batch_size = config.sample_per_image
a_data_loader, b_data_loader = get_loader(
data_path, batch_size, config.input_scale_size,
config.num_worker, config.skip_pix2pix_processing)
trainer = Trainer(config, a_data_loader, b_data_loader)
if config.is_train:
save_config(config)
trainer.train()
else:
if not config.load_path:
raise Exception("[!] You should specify `load_path` to load a pretrained model")
trainer.test()
if __name__ == "__main__":
config, unparsed = get_config()
main(config)
<file_sep>/img_random_discmp.py
_author__ = 'linjx'
import cv2
from PIL import Image
import numpy as np
#from motionblur import motionblur
#img=Image.open('ori10.bmp')
#img=np.array(img)
#img = cv2.imread('ori10.bmp')
def img_random_dis(input_batch, ind = None):
#if ind is 6:
#imres = np.random.randint(0,6)
if ind is None:
imres = np.random.randint(0,6)
else:
imres = ind
img_dis=np.zeros((input_batch.shape[0],128+16*imres,96+16*imres,1))
img_ref=np.zeros((input_batch.shape[0],128+16*imres,96+16*imres,1))
#downsrate=np.random.randint(0,3)
#mobkernel= motionblur(4*np.random.randint(0,4)+1,45*np.random.randint(0,4))
#mobkernel= motionblur(8,45)
#averagekernel=np.ones(16).reshape(4,4)/16
#sigma=10*np.random.randint(0,4)
sigma=30
for i in range(input_batch.shape[0]):
img_rgb = input_batch[i]
img_rgb = 255*(img_rgb*0.5+0.5)
#img_size = img_rgb.shape
#print img_rgb
img_rgb = np.transpose(img_rgb,(1,2,0))
#print img_rgb.shape
#img=np.zeros_like(img_rgb)
#img[:,:,0]=img_rgb[:,:,2]
#img[:,:,1]=img_rgb[:,:,1]
#img[:,:,2]=img_rgb[:,:,0]
#img.astype(float)
img = np.mean(img_rgb,axis = 2)
img = cv2.resize(img,(96+16*imres,128+16*imres),interpolation = cv2.INTER_CUBIC) #multi_scale
#img1 = cv2.filter2D(img,-1,averagekernel) #AVERAGEblur
img1 = cv2.resize(img,None,fx=1.0/4.0, fy=1.0/4.0, interpolation = cv2.INTER_CUBIC)
noise= sigma*np.random.randn(img1.shape[0],img1.shape[1])
img1 = img1+noise
img1 = cv2.resize(img1,None,fx=1.0*4.0, fy=1.0*4.0, interpolation = cv2.INTER_NEAREST) #up_sample method
#img5 = cv2.resize(img2,None,fx=1.0*2**(downsrate), fy=1.0*2**(downsrate), interpolation = cv2.INTER_NEAREST)
#img6 = cv2.resize(img1,None,fx=1.0*2**(downsrate), fy=1.0*2**(downsrate), interpolation = cv2.INTER_NEAREST)
img1 = np.expand_dims(img1,axis=2)
#img1=np.clip(img1,0,255)
#img1[img1<=0]=0
#img1[img>=255]=255
img = np.expand_dims(img,axis=2)
img_dis[i]=img1
img_ref[i]=img
#image2 = Image.fromarray(img)
#image2.show()
#cv2.imshow('Original', img3)
#cv2.waitKey(0)
img_dis = np.transpose(img_dis,(0,3,1,2))
img_ref = np.transpose(img_ref,(0,3,1,2))
#print img_ref.shape
return (img_dis/255-0.5)*2,(img_ref/255-0.5)*2
|
f719b13adb2659aaa94d64500c92cc4b5bf21aa5
|
[
"Python",
"Shell"
] | 6
|
Python
|
hzphzp/hr_regan
|
1da7f21cb075dc7d9343339c608dd29cc15d5bad
|
c2fe1f7f8c26774a2a30f32f98dcab9236836f13
|
refs/heads/master
|
<repo_name>jessefjxm/CSE542<file_sep>/src/proj/software/engenering/junit/AllBrachCoverageTest.java
package proj.software.engenering.junit;
import static org.junit.Assert.*;
import org.junit.Test;
import proj.software.engenering.GradingRubric;
public class AllBrachCoverageTest {
@Test
public void allBrachCoverageTest() {
GradingRubric gradingRubric = new GradingRubric();
double max = 100, min = 0;
double GradeA = 90;
double GradeB = 80;
double GradeC = 70;
double GradeD = 60;
double[] invalidtest = { -0.000000000001, -1.0, -9999999999999.0, -1e200, 100.000000000001, 101.0, 1e200 };
double[] testA = { max, max - 0.000000000001, max - 1, (max + GradeA) / 2, GradeA + 1, GradeA + 0.000000000001,
GradeA };
double[] testB = { GradeA - 0.000000000001, GradeA - 1, (GradeA + GradeB) / 2, GradeB + 1,
GradeB + 0.000000000001, GradeB };
double[] testC = { GradeB - 0.000000000001, GradeB - 1, (GradeB + GradeC) / 2, GradeC + 1,
GradeC + 0.000000000001, GradeC };
double[] testD = { GradeC - 0.000000000001, GradeC - 1, (GradeC + GradeD) / 2, GradeD + 1,
GradeD + 0.000000000001, GradeD };
double[] testE = { GradeD - 0.000000000001, GradeD - 1, (GradeD + min) / 2, min + 1, min + 0.000000000001, min };
// null input
assertNull(gradingRubric.UpdateGrade(null));
assertNull(gradingRubric.UpdateGrade(new double[0]));
// invalid input
for (char c : gradingRubric.UpdateGrade(invalidtest)) {
assertTrue('F' == c);
}
// correct input
for (char c : gradingRubric.UpdateGrade(testA)) {
assertTrue('A' == c);
}
for (char c : gradingRubric.UpdateGrade(testB)) {
assertTrue('B' == c);
}
for (char c : gradingRubric.UpdateGrade(testC)) {
assertTrue('C' == c);
}
for (char c : gradingRubric.UpdateGrade(testD)) {
assertTrue('D' == c);
}
for (char c : gradingRubric.UpdateGrade(testE)) {
assertTrue('E' == c);
}
}
}
|
41a4162f1de5c8c42496063e60496654e276e741
|
[
"Java"
] | 1
|
Java
|
jessefjxm/CSE542
|
9ed0b095affee60312ea91df167a6f42e35df735
|
00837a7195feb7a16215a1583d1bf04d48277e0d
|
refs/heads/master
|
<file_sep><?php
include_once("config.php");
if(isset($_GET['s_id'])){
$s_id = $_GET['s_id'];
$sql = "DELETE FROM students WHERE s_id='$s_id';";
}else if(isset($_GET['l_id'])){
$l_id = $_GET['l_id'];
$sql = "DELETE FROM staff WHERE l_id='$l_id'";
}else if(isset($_GET['date'])){
$date = $_GET['date'];
$mcode = $_GET['mcode'];
$sql = "DELETE FROM exmas WHERE date='$date' AND mcode='$mcode';";
}else if(isset($_GET['mcode'])){
$mcode = $_GET['mcode'];
$sql = "DELETE FROM module WHERE mcode='$mcode';";
}
$result = mysqli_query($con, $sql) or die(mysqli_error($con));
if($result){
echo "Deleted Successfully!";
}else{
echo "Error";
}
<file_sep><?php
session_start();
if(isset($_POST["submit"])){
$mcode = $_POST["mcode"];
$date = $_POST["date"];
include_once("config.php");
$sql1 = "INSERT INTO exmas(date, mcode) VALUES ('$date', '$mcode');";
$result1 = mysqli_query($con, $sql1) or die(mysqli_error($con));
if($result1){
$msg = "* registration successed !";
}else{
$msg = "* Falied!!";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>DBMS- database system</title>
<link rel="stylesheet" href="css/form.css?modified=02209">
<link rel="stylesheet" href="css/test.css?modified=0211009">
<link rel="stylesheet" href="css/tab.css?modified=0202309">
<link rel="stylesheet" href="css/navbar.css?modified=032209">
</head>
<body>
<ul class="navbar">
<li class="navli activenav" onclick="active(this);"><a href="#">home</a></li>
<li class="navli" onclick="active(this);"><a href="#">tmp1</a></li>
<li class="navli" onclick="active(this);"><a href="#">tmp2</a></li>
<li class="navli" onclick="active(this);"><a href="#">tmp3</a></li>
<li class="space" onclick="active(this);"><a href="#">space</a></li>
<li class="navli" id="logout"><a href="logout.php">logout</a></li>
</ul>
<h1>DBMS System</h1>
<h1>Registeration page</h1>
<div class="container-main">
<div id="signup" class="tabcontent">
<ul class="tab tabani">
<li class="tabLi" ><a style="margin-left: 17%;" id="default" class="tablink" >Register Student</a></li>
</ul>
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
<p style="color: red; margin-left: 5%;">
<?php if(isset($msg)) echo $msg; ?>
</p>
<p>
<label for="sign-id">Module code:</label>
<input type="text" name="mcode" id="sign-id" placeholder="Enter Module code" required>
</p>
<p>
<label for="sign-fname">Date:</label>
<input type="date" name="date" id="sign-date" placeholder="Enter the Date" required>
</p>
<input id="submit" type="submit" name="submit"value="Register">
</form>
</div>
</div>
<script src="js/validation.js"></script>
<script src="js/navbar.js"></script>
</body>
</html>
<file_sep><?php
if(isset($_POST["submit"])){
$fname = $_POST["fname"];
$lname = $_POST["lname"];
$username = $_POST["username"];
$password = md5($_POST["password"]);
include_once("config.php");
$sql = "INSERT INTO users(fname, lname, username, password) VALUES ('$fname', '$lname', '$username', '$password')";
$result = mysqli_query($con, $sql);
if($result){
echo "Done.";
}else{
echo mysqli_error($con);
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Signed In</title>
<link rel="stylesheet" href="css/test.css?modified=2011009">
</head>
<body>
<h1>Signed In</h1>
</body>
</html>
<file_sep><?php
session_start();
if (!isset($_SESSION["id"]) || !isset($_SESSION["level"])) {
header("Location: index.php");
$link = "hide";
}else{
$link = "";
}
if(isset($_GET["mcode"])){
include_once("config.php");
$mcode = $_GET["mcode"];
$sql1 = "SELECT mcode, title, cr_level, coordinator_id, name FROM module INNER JOIN department ON module.dep_id=department.dep_id WHERE mcode='$mcode';";
$result1 = mysqli_query($con, $sql1) or die(mysqli_error($con));
if(mysqli_num_rows($result1)>0){
$str = '';
while($row=mysqli_fetch_assoc($result1)){
$str .= "<li>Module code: <b>$row[mcode]</b></li>";
$str .= "<li>Title: <b>$row[title]</b></li>";
$str .= "<li>Credit Level: <b>$row[cr_level]</b></li>";
$str .= "<li>Coordinator: <b>$row[coordinator_id]</b></li>";
$str .= "<li>Department: <b>$row[name]</b></li>";
}
}else{
$str = "<li>No data</li>";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>DBMS- database system</title>
<link rel="stylesheet" href="css/form.css?modified=205209">
<link rel="stylesheet" href="css/test.css?modified=20094">
<link rel="stylesheet" href="css/tab.css?modified=200209">
<link rel="stylesheet" href="css/navbar.css?modified=20209">
<style>
table, th, td{border: 3px solid #ddd; border-collapse: collapse; padding: 10px;}
table{width: 100%;}
.container{margin-left: auto; margin-right: auto; width: 50%; display: block;}
table{background: #888;}
th{background: #555;}
li, !.navli{padding: 10px;}
</style>
</head>
<body>
<ul class="navbar">
<li class="navli activenav" onclick="active(this);"><a href="#">home</a></li>
<li class="navli" onclick="active(this);"><a href="#">tmp1</a></li>
<li class="navli" onclick="active(this);"><a href="#">tmp2</a></li>
<li class="navli" onclick="active(this);"><a href="#">tmp3</a></li>
<li class="space" onclick="active(this);"><a href="#">space</a></li>
<li class="navli" id="logout"><a href="logout.php" class="<?php echo $link ?>">Log out</a></li>
</ul>
<h1>DBMS System</h1>
<h1>Module page</h1>
<div class="container-main2">
<h2>Module details</h2>
<ul>
<?php if(isset($str)){echo $str; } ?>
</ul>
</div>
<script src="js/navbar.js"></script>
</body>
</html>
<file_sep># dbms-assignment
database system for dbms assignment\n
sql injection ->-> x'; DROP TABLE members; --
edit page titles.
fill missed fields in database tables
<file_sep><?php
if(isset($_POST["submit"])){
include_once("config.php");
$search = $_POST["search"];
$sql = "SELECT * FROM users WHERE fname LIKE '%$search%' OR lname LIKE '%$search%'";
$result = mysqli_query($con, $sql);
if(mysqli_num_rows($result)>0){
$str= "<table>";
$str.="<tr><th>id</th><th>first name</th><th>last name</th><th>username</th></tr>";
while($row = mysqli_fetch_array($result)){
$str.= "<tr><td>$row[id]</td><td>$row[fname]</td><td>$row[lname]</td><td>$row[username]</td></tr>";
}
$str.= "</table>";
}else{
echo "<style>html{font-size: 40px;}</style>";
echo "No records matched.";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Search Results</title>
<style>
html{background: #f2f2f2; font-family: sans-serif;}
table, th, td{border: 1px solid red; border-collapse: collapse; padding: 10px;}
table{width: 100%;}
.container{margin-left: auto; margin-right: auto; width: 50%; display: block;}
</style>
</head>
<body>
<div class="container">
<?php if(isset($str)){echo $str;} ?>
</div>
</body>
</html>
<file_sep><?php
if(isset($_POST["submit"])){
include_once("config.php");
$id = $_POST["id"];
$password = $_POST["<PASSWORD>"];
$sql = "SELECT id, ulevel FROM users WHERE id = '$id' AND password = '" . md5($password) . "';";
$result = mysqli_query($con, $sql);
if(mysqli_num_rows($result)>0){
$row = mysqli_fetch_array($result);
echo $row["id"];
echo $row["ulevel"];
//if details are correct logging in the user
session_start();
$_SESSION["id"] = $row['id'];
$_SESSION["level"] = $row["ulevel"];
if($_SESSION["level"] == 1){
header("Location: admin.php");
}else{
header("Location: student.php");
}
}else{
echo "You have Failed! #This city.";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Logged In</title>
<link rel="stylesheet" href="css/test.css?modified=2011009">
</head>
<body>
<h1>Logged In</h1>
</body>
</html>
<file_sep><?php
session_start();
if(isset($_POST["submit"])){
$s_id = $_POST["id"];
$fname = $_POST["fname"];
$lname = $_POST["lname"];
$department = $_POST["department"];
$password = md5($_POST["password"]);
$mcode = trim($_POST["mcode"]);
$r = explode(" ", $mcode);
include_once("config.php");
$sql1 = "INSERT INTO staff(l_id, fname, lname, dep_id) VALUES ('$s_id', '$fname', '$lname', '$department');";
$sql2 = " INSERT INTO users(id, password, ulevel) VALUES ('$s_id', '$password', 1);";
$result1 = mysqli_query($con, $sql1) or die(mysqli_error($con));
$result2 = mysqli_query($con, $sql2) or die(mysqli_error($con));
if($result1 && $result2){
$msg = "* registration successed !";
}else{
$msg = "* Falied! ";
}
for ($i=0; $i <count($r) ; $i++) {
$sql1 = "INSERT INTO staff_module(mcode, l_id) VALUES ('$r[$i]', '$s_id');";
$result1 = mysqli_query($con, $sql1) or die(mysqli_error($con));
if($result1){
$mag = "* registration successed !";
}else{
echo mysqli_error($con);
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>DBMS- database system</title>
<link rel="stylesheet" href="css/form.css?modified=02209">
<link rel="stylesheet" href="css/test.css?modified=0211009">
<link rel="stylesheet" href="css/tab.css?modified=0202309">
<link rel="stylesheet" href="css/navbar.css?modified=032209">
</head>
<body>
<ul class="navbar">
<li class="navli activenav" onclick="active(this);"><a href="#">home</a></li>
<li class="navli" onclick="active(this);"><a href="#">tmp1</a></li>
<li class="navli" onclick="active(this);"><a href="#">tmp2</a></li>
<li class="navli" onclick="active(this);"><a href="#">tmp3</a></li>
<li class="space" onclick="active(this);"><a href="#">space</a></li>
<li class="navli" id="logout"><a href="logout.php">logout</a></li>
</ul>
<h1>DBMS System</h1>
<h1>Registeration page</h1>
<div class="container-main">
<div id="signup" class="tabcontent">
<ul class="tab tabani">
<li class="tabLi" ><a style="margin-left: 17%;" id="default" class="tablink" >Register Lecture</a></li>
</ul>
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
<p style="color: red; margin-left: 5%;">
<?php if(isset($msg)) echo $msg; ?>
</p>
<p>
<label for="sign-id">Id:</label>
<input type="text" name="id" id="sign-id" placeholder="Enter ID" required>
</p>
<p>
<label for="sign-fname">First Name:</label>
<input type="name" name="fname" id="sign-fname" placeholder="Enter First name" required>
</p>
<p>
<label for="sign-lname">Last Name:</label>
<input type="text" name="lname" id="sign-lname" placeholder="Enter Last name" required>
</p>
<p>
<label for="sign-department">Department id:</label>
<input type="text" name="department" id="sign-department" placeholder="Department Id" required>
</p>
<p>
<label for="sign-id">mcode:</label>
<input type="text" name="mcode" id="sign-id" placeholder="Module codes (seperate by a space)" required>
</p>
<p>
<label for="sign-password">Password:</label>
<input type="<PASSWORD>" name="password" id="sign-password" placeholder="<PASSWORD>" required>
</p>
<p>
<label for="sign-password">Re-enter password:</label>
<input type="<PASSWORD>" name="password" id="sign-re-password" placeholder="Re-enter password" required>
</p>
<input id="submit" type="submit" name="submit"value="Register" onclick="return validatePassword()">
</form>
</div>
</div>
<script src="js/validation.js"></script>
<script src="js/navbar.js"></script>
</body>
</html>
<file_sep><?php
session_start();
if (!isset($_SESSION["id"]) || !isset($_SESSION["level"])) {
header("Location: index.php");
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>DBMS- database system</title>
<link rel="stylesheet" href="css/form.css?modified=02209">
<link rel="stylesheet" href="css/test.css?modified=02009">
<link rel="stylesheet" href="css/tab.css?modified=022309">
<link rel="stylesheet" href="css/navbar.css?modified=022309">
</head>
<body>
<ul class="navbar">
<li class="navli activenav" onclick="active(this);"><a href="#">home</a></li>
<li class="navli" onclick="active(this);"><a href="#">tmp1</a></li>
<li class="navli" onclick="active(this);"><a href="#">tmp2</a></li>
<li class="navli" onclick="active(this);"><a href="#">tmp3</a></li>
<li class="space"><a href="#">space</a></li>
<li class="navli" id="logout"><a href="logout.php">logout</a></li>
</ul>
<h1>DBMS System</h1>
<h1>Admin page</h1>
<div class="container-main admin">
<a class="admin-link" href="insert_module.php">Registere Module</a>
<a class="admin-link" href="register_student.php">Registere Students</a>
<a class="admin-link" href="register_lecture.php">Registere Lecture</a>
<a class="admin-link" href="while.php">Update module's lecturers</a>
<a class="admin-link" href="search.php">Search Students</a>
<a class="admin-link" href="search_staff.php">Search Staff</a>
<a class="admin-link" href="insert_results.php">Enter results</a>
<a class="admin-link" href="insert_exams.php">Enter exam dates</a>
<a class="admin-link" href="exams.php">Show exams</a>
<a class="admin-link" href="modules.php">Show modules</a>
</div>
<script src="js/navbar.js"></script>
</body>
</html>
|
444fb4308eecf81e4287b54af94a4afd2116e964
|
[
"Markdown",
"PHP"
] | 9
|
PHP
|
ppkavinda/dbms-assignment
|
1f15460d5b41510642915fb6841e4d33aa9885b7
|
e28f0b6dfa017a50fc14a389382058adea07e817
|
refs/heads/main
|
<repo_name>Shrayas1497/react-spotify<file_sep>/spotify/client/src/useAuth.js
import {useState,useEffect } from 'react'
import axiosInstance from '../../config';
export default function useAuth(code) {
const[accessToken,setAccessToken]= useState()
const[refreshToken,setRefreshToken] = useState()
const[expiresIn,setExpiresIn] = useState()
console.log(refreshToken)
useEffect(() => {
axiosInstance.post('https://react-better-spotify.herokuapp.com//login',
{
code,
}).then(res => {
setAccessToken(res.data.accessToken)
setRefreshToken(res.data.refreshToken)
setExpiresIn(res.data.expiresIn)
window.history.pushState( { }, null,"/")
}).catch(() => {
window.location ="/"
})
}, [code])
useEffect(()=>{
if (!refreshToken ||! expiresIn) return
const interval=setInterval(()=> {
axiosInstance.post('https://react-better-spotify.herokuapp.com//refresh',
{
refreshToken,
})
.then(res => {
setAccessToken(res.data.accessToken)
setExpiresIn(res.data.expiresIn)
})
.catch(() => {
window.location = "/"
})
} ,(expiresIn - 60) * 1000)
return () => clearInterval(interval)
},[refreshToken,expiresIn])
return accessToken
}<file_sep>/spotify/client/server/server.js
const express= require('express');
const cors =require("cors")
const bodyParser = require("body-parser")
const lyricsFinder =require("lyrics-finder")
const SpotifyWebApi= require('spotify-web-api-node');
const app = express();
app.use(cors())
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))
app.post('/refresh',(req,res)=>
{
const refreshToken =req.body.refreshToken
console.log("hi")
const spotifyApi= new SpotifyWebApi ({
redirectUri:'https://react-better-spotify.herokuapp.com/',
clientId:'<KEY>',
clientSecret:'<KEY>',
refreshToken,
})
spotifyApi
.refreshAccessToken()
.then(data => {
res.json({
accessToken:data.body.accessToken,
expiresIn: data.body.expiresIn
})
})
.catch((err)=>{
console.log(err)
res.sendStatus(400)
})
})
app.post('/login',(req,res)=>
{
const code = req.body.code
const spotifyApi= new SpotifyWebApi ({
redirectUri:'https://react-better-spotify.herokuapp.com/',
clientId:'<KEY>',
clientSecret:'<KEY>',
})
spotifyApi
.authorizationCodeGrant(code)
.then(data =>
{
res.json({
accessToken: data.body.access_token,
refreshToken: data.body.refresh_token,
expiresIn: data.body.expires_in
})
} )
.catch((err)=>{
console.log(err)
res.sendStatus(400)
})
})
app.get('lyrics',async(req,res) =>{
const lyrics =await lyricsFinder(req.query.artist,req.query.track) || 'no lyrics found'
res.json({lyrics})
})
app.use(express.static(path.join(__dirname, "/client")));
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, '/client/build', 'index.html'));
});
app.listen(process.env.PORT || 3001)
|
61fc6e2e1cf1c96030301a4664c7a2b6985ce490
|
[
"JavaScript"
] | 2
|
JavaScript
|
Shrayas1497/react-spotify
|
bc31251aa4f915c0a88914982f59fda833003623
|
784c28187b358f546c806336d572308a9374663d
|
refs/heads/master
|
<file_sep>package in.mytring;
import android.Manifest;
import android.annotation.TargetApi;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.telephony.CellInfo;
import android.telephony.CellInfoCdma;
import android.telephony.CellInfoGsm;
import android.telephony.CellInfoLte;
import android.telephony.CellInfoWcdma;
import android.telephony.SubscriptionInfo;
import android.telephony.SubscriptionManager;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
public class MainActivity extends AppCompatActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private ListenerThread listenerThread = null;
int sim1LastSignalStrength, sim2LastSignalStrength,sim1NewSignalStrength,sim2NewSignalStrength;
String sim1Operator="",sim2Operator="",sim1Details = "", sim2Details = "";
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver () {
@Override
public void onReceive(Context context, Intent intent) {
sim1NewSignalStrength = intent.getIntExtra(MyTringPhoneStateListener.NEW_SIGNAL_STRENGTH,MyTringPhoneStateListener.DEFAULT_STRENGTH);
Log.d("MainActivity" ,"Refreshed Signal Stength = " + sim1NewSignalStrength);
refreshSignalStrength();
}
};
@TargetApi(22)
public void refreshSignalStrength(){
TextView sim1TextView = (TextView) findViewById(R.id.Sim1_details_text);
String[] strings = sim1Details.split(System.lineSeparator());
if(strings.length>=2) {
strings[2] = "" + sim1NewSignalStrength + " dBm";
strings[3] = getSignalQuality(sim1NewSignalStrength);
sim1Details = strings[0]+ System.lineSeparator() + strings[1] + System.lineSeparator() + strings[2] + System.lineSeparator() + strings[3];
sim1TextView.setText(sim1Details);
}
}
private String getSignalQuality(int signalStrength){
if(signalStrength>-75){
return "Excellent";
}else if(signalStrength>-90){
return "Good";
}else if(signalStrength>-100){
return "Poor";
}else if(signalStrength>-109){
return "Very Poor";
}else{
return "No Signal";
}
}
@Override
protected void onResume(){
super.onResume();
IntentFilter broadcastFilter = new IntentFilter(LOCAL_ACTION);
LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(this);
localBroadcastManager.registerReceiver(broadcastReceiver, broadcastFilter);
}
public static final String LOCAL_ACTION = "in.mytring.intent_service.ALL_DONE";
ArrayList<in.mytring.CellTowerData> cellTowerDatas = new ArrayList<in.mytring.CellTowerData>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getPermissionAndFindMyNetwork();
populateCellTowerData();
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
mapFragment.getMapAsync(this);
registerReceiver(broadcastReceiver, new IntentFilter(LOCAL_ACTION));
/*Intent i = new Intent(MainActivity.this, ListenerService.class);
startService(i);*/
// if (listenerThread == null) {
// listenerThread = new ListenerThread(this);
// listenerThread.start();
// }
}
private void populateCellTowerData() {
in.mytring.GPSTracker gps = new in.mytring.GPSTracker(this);
if (gps.canGetLocation()) {
Double latitude = gps.getLatitude();
Double longitude = gps.getLongitude();
// read the CSV
BufferedReader buffer = null;
int i = 0;
try {
String line;
InputStream raw = getBaseContext().getResources().openRawResource(R.raw.databangalore_airtel);//getBaseContext().getAssets().open("databangalore.csv");
buffer = new BufferedReader(new InputStreamReader(raw));
// How to read file in java line by line?
while ((line = buffer.readLine()) != null) {
i++;
String[] parts = line.split(",");
if (parts.length < 7 || i % 3 != 0)
continue;
if ((Math.abs(Double.parseDouble(parts[4]) - longitude) > 0.02 || Math.abs(Double.parseDouble(parts[5]) - latitude) > 0.02))
continue;
in.mytring.CellTowerData cellTowerData = new in.mytring.CellTowerData(Integer.parseInt(parts[0]), Integer.parseInt(parts[1]), Integer.parseInt(parts[2]),
Long.parseLong(parts[3]), Double.parseDouble(parts[4]), Double.parseDouble(parts[5]), parts[6]);
cellTowerDatas.add(cellTowerData);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (buffer != null) buffer.close();
} catch (IOException exception) {
exception.printStackTrace();
}
}
}
}
@Override
public void onWindowFocusChanged(boolean hasFocus){
super.onWindowFocusChanged(hasFocus);
getWindow().getDecorView().setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
try {
if (broadcastReceiver != null)
unregisterReceiver(broadcastReceiver);
if (listenerThread != null) {
listenerThread.yield();
}
} catch (Exception e) {
}
super.onDestroy();
}
public void wifiDashboard(View v)
{
Intent j = new Intent(MainActivity.this, WifiActivity.class);
startActivity(j);
finish();
}
public void switchNetwork(View v)
{
Intent i = new Intent(MainActivity.this, SwitchNetworkActivity.class);
startActivity(i);
finish();
}
public void speedTest(View v)
{
Intent j = new Intent(MainActivity.this, SpeedTestActivity.class);
startActivity(j);
finish();
}
public void settings(View v)
{
Intent j = new Intent(MainActivity.this, in.mytring.Settings.class);
startActivity(j);
finish();
}
@Override
@TargetApi(22)
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.clear();
String latitude="",longitude="";
in.mytring.GPSTracker gps = new in.mytring.GPSTracker(this);
if(gps.canGetLocation()){
latitude = Double.toString(gps.getLatitude());
longitude = Double.toString(gps.getLongitude());
// \n is for new line
}else{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
LatLng currentLocation = new LatLng(gps.latitude,gps.longitude);
int pinheight = 130;
int pinwidth = 70;
Bitmap mylocationimage = BitmapFactory.decodeResource(getResources(), R.drawable.mylocation1);
Bitmap mylocationMarker = Bitmap.createScaledBitmap(mylocationimage, pinwidth, pinheight, false);
mMap.addMarker(new MarkerOptions().position(currentLocation).icon(BitmapDescriptorFactory.fromBitmap(mylocationMarker)));
//mMap.addMarker(new MarkerOptions().position(currentLocation).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW)));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(currentLocation,14.0f));
int theight = 150;
int twidth = 70;
Bitmap sim1towerimage = BitmapFactory.decodeResource(getResources(), R.drawable.tower_icon1);
Bitmap sim1towerMarker = Bitmap.createScaledBitmap(sim1towerimage, twidth, theight, false);
Bitmap sim2towerimage = BitmapFactory.decodeResource(getResources(), R.drawable.tower_icon);
Bitmap sim2towerMarker = Bitmap.createScaledBitmap(sim2towerimage, twidth, theight, false);
Bitmap sim1ConnectedTowerImage = BitmapFactory.decodeResource(getResources(), R.drawable.tower_connected1);
Bitmap sim1ConnectedTowerMarker = Bitmap.createScaledBitmap(sim1ConnectedTowerImage, twidth, 200, false);
Bitmap sim2ConnectedTowerImage = BitmapFactory.decodeResource(getResources(), R.drawable.tower_connected);
Bitmap sim2ConnectedTowerMarker = Bitmap.createScaledBitmap(sim2ConnectedTowerImage, twidth, 200, false);
CellTowerData sim1ConnectedCell = getNearestTower(currentLocation,sim1Operator);
CellTowerData sim2ConnectedCell = getNearestTower(currentLocation,sim2Operator);
if(sim1ConnectedCell!=null){
LatLng sim1ConnectedTower = new LatLng(sim1ConnectedCell.getLatitude(),sim1ConnectedCell.getLongitude());
mMap.addMarker(new MarkerOptions().position(sim1ConnectedTower).icon(BitmapDescriptorFactory.fromBitmap(sim1ConnectedTowerMarker)));
cellTowerDatas.remove(sim1ConnectedCell);
}
if(sim2ConnectedCell!=null){
LatLng sim2ConnectedTower = new LatLng(sim2ConnectedCell.getLatitude(),sim2ConnectedCell.getLongitude());
mMap.addMarker(new MarkerOptions().position(sim2ConnectedTower).icon(BitmapDescriptorFactory.fromBitmap(sim2ConnectedTowerMarker)));
cellTowerDatas.remove(sim2ConnectedCell);
}
ArrayList<CellTowerData> sim1Cells = filterCells(sim1Operator);
if(sim1Cells!=null){
for(in.mytring.CellTowerData celldata: sim1Cells){
LatLng tower = new LatLng(celldata.getLatitude(),celldata.getLongitude());
mMap.addMarker(new MarkerOptions().position(tower).icon(BitmapDescriptorFactory.fromBitmap(sim2towerMarker)));
//mMap.addMarker(new MarkerOptions().position(tower));
}
}
ArrayList<CellTowerData> sim2Cells = filterCells(sim2Operator);
if(sim2Cells!=null){
for(in.mytring.CellTowerData celldata: sim2Cells){
LatLng tower = new LatLng(celldata.getLatitude(),celldata.getLongitude());
mMap.addMarker(new MarkerOptions().position(tower).icon(BitmapDescriptorFactory.fromBitmap(sim2towerMarker)));
//mMap.addMarker(new MarkerOptions().position(tower));
}
}
}
private ArrayList<CellTowerData> filterCells(String operatorName){
if(operatorName==null){
return null;
}
ArrayList<CellTowerData> filteredCells = new ArrayList<>();
for(CellTowerData celldata:cellTowerDatas){
if (operatorName.toLowerCase().contains("jio") && celldata.getMcc()==405 && celldata.getMnc()==10) {
filteredCells.add(celldata);
}else if (operatorName.toLowerCase().contains("airtel") && celldata.getMcc()==404 && celldata.getMnc()==45) {
filteredCells.add(celldata);
} else if (operatorName.toLowerCase().contains("vodafone") && celldata.getMcc()==404 && celldata.getMnc()==86) {
filteredCells.add(celldata);
}
}
return filteredCells;
}
private CellTowerData getNearestTower (LatLng currentLatLong,String operatorName){
if(operatorName==null || operatorName.isEmpty()){
return null;
}
Location currentLocation = new Location("Base Location");
currentLocation.setLatitude(currentLatLong.latitude);
currentLocation.setLongitude(currentLatLong.longitude);
float distance= Float.MAX_VALUE;
ArrayList<CellTowerData> nearestTowers = new ArrayList<>();
CellTowerData nearestCell =null;
for(in.mytring.CellTowerData celldata: cellTowerDatas) {
if (operatorName.toLowerCase().contains("jio") && celldata.getMcc()==405 && celldata.getMnc()==10) {
Location newLocation = new Location("New Location");
newLocation.setLatitude(celldata.getLatitude());
newLocation.setLongitude(celldata.getLongitude());
if(distance>currentLocation.distanceTo(newLocation)){
distance=currentLocation.distanceTo(newLocation);
nearestCell = celldata;
}
} else if (operatorName.toLowerCase().contains("airtel") && celldata.getMcc()==404 && celldata.getMnc()==45) {
Location newLocation = new Location("New Location");
newLocation.setLatitude(celldata.getLatitude());
newLocation.setLongitude(celldata.getLongitude());
if(distance>currentLocation.distanceTo(newLocation)){
distance=currentLocation.distanceTo(newLocation);
nearestCell = celldata;
}
} else if (operatorName.toLowerCase().contains("vodafone") && celldata.getMcc()==404 && celldata.getMnc()==86) {
Location newLocation = new Location("New Location");
newLocation.setLatitude(celldata.getLatitude());
newLocation.setLongitude(celldata.getLongitude());
if(distance>currentLocation.distanceTo(newLocation)){
distance=currentLocation.distanceTo(newLocation);
nearestCell = celldata;
}
}
}
return nearestCell;
}
private static final int REQUEST_PERMISSIONS = 20;
public void getPermissionAndFindMyNetwork(){
if (ContextCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.ACCESS_COARSE_LOCATION) +
ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_PHONE_STATE)!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, android.Manifest.permission.ACCESS_COARSE_LOCATION)||
ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, android.Manifest.permission.READ_PHONE_STATE)){
Snackbar.make(findViewById(android.R.id.content),
"Please Grant Permissions",
Snackbar.LENGTH_INDEFINITE).setAction("ENABLE",
new View.OnClickListener() {
@Override
public void onClick(View v) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.READ_PHONE_STATE},REQUEST_PERMISSIONS);
}
}).show();
} else {
ActivityCompat.requestPermissions(MainActivity.this,new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.READ_PHONE_STATE},REQUEST_PERMISSIONS);
}
}else {
//Call whatever you want
findMyNetwork();
}
}
@Override
public void onRequestPermissionsResult(int requestCode,
@NonNull String permissions[],
@NonNull int[] grantResults) {
switch (requestCode) {
case REQUEST_PERMISSIONS: {
if ((grantResults.length > 0) && (grantResults[0] +
grantResults[1]) == PackageManager.PERMISSION_GRANTED) {
//Call whatever you want
findMyNetwork();
} else {
Snackbar.make(findViewById(android.R.id.content), "Enable Permissions from settings",Snackbar.LENGTH_INDEFINITE).setAction("ENABLE",
new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.setData(Uri.parse("package:" + getPackageName()));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
startActivity(intent);
}
}).show();
}
return;
}
}
}
@TargetApi(23)
public void findMyNetwork() {
TelephonyManager tManager = (TelephonyManager) getBaseContext().getSystemService(Context.TELEPHONY_SERVICE);
SubscriptionManager subscriptionManager = SubscriptionManager.from(getBaseContext());
List<SubscriptionInfo> subscriptions = subscriptionManager.getActiveSubscriptionInfoList();
if (subscriptions != null){
if(subscriptions.size()==1){
sim1Operator = subscriptions.get(0).getCarrierName().toString();
sim2Details = "SIM2 Details: "+ System.lineSeparator() + "No Connection";
}else{
sim1Operator = subscriptions.get(0).getCarrierName().toString();
sim2Operator = subscriptions.get(1).getCarrierName().toString();
}
}
List<CellInfo> listAllCellInfo = tManager.getAllCellInfo();
if (null != tManager && tManager.getPhoneCount() > 1) {
for (ListIterator<CellInfo> itr = listAllCellInfo.listIterator(); itr.hasNext(); ) {
CellInfo currentCellInfo = itr.next();
if (currentCellInfo.isRegistered()) {
if (null == sim1Details || sim1Details.isEmpty()) {
sim1LastSignalStrength =sim1NewSignalStrength= getSignalStrength(currentCellInfo);
sim1Details = sim1Details + "SIM1 Details: "+ System.lineSeparator() + getNetworkType(currentCellInfo) + " | " + sim1Operator + System.lineSeparator() + sim1NewSignalStrength + " dBm" + System.lineSeparator() + getSingalQuality(currentCellInfo);
} else if (null == sim2Details || sim2Details.isEmpty()) {
sim2LastSignalStrength =sim2NewSignalStrength= getSignalStrength(currentCellInfo);
sim2Details = sim2Details + "SIM2 Details: "+ System.lineSeparator() + getNetworkType(currentCellInfo) + " | " + sim2Operator + System.lineSeparator() + sim2NewSignalStrength + " dBm" + System.lineSeparator() + getSingalQuality(currentCellInfo);
}
}
}
TextView sim1Text = (TextView) findViewById( R.id.Sim1_details_text);
sim1Text.setText(sim1Details);
TextView sim2Text = (TextView) findViewById( R.id.Sim2_details_text);
sim2Text.setText(sim2Details);
} else {
for (ListIterator<CellInfo> itr = listAllCellInfo.listIterator(); itr.hasNext(); ) {
CellInfo currentCellInfo = itr.next();
if (currentCellInfo.isRegistered()) {
if (null == sim1Details || sim1Details.isEmpty()) {
sim1Details = sim1Details +"SIM1 Details: "+ System.lineSeparator() + getNetworkType(currentCellInfo) + " | " + sim1Operator + System.lineSeparator() + getSignalStrength(currentCellInfo) + " dBm" + System.lineSeparator() + getSingalQuality(currentCellInfo);
}
}
}
TextView sim1Text = (TextView) findViewById( R.id.Sim1_details_text);
sim1Text.setText(sim1Details);
TextView sim2Text = (TextView) findViewById( R.id.Sim2_details_text);
sim2Text.setText("SIM2 Details: "+ System.lineSeparator() + "No Connection");
}
}
@TargetApi(18)
int getSignalStrength(CellInfo currentCellInfo){
if (currentCellInfo instanceof CellInfoWcdma) {
return ((CellInfoWcdma) currentCellInfo).getCellSignalStrength().getDbm();
} else if (currentCellInfo instanceof CellInfoLte) {
Log.d("LTE Parameters:",((CellInfoLte) currentCellInfo).getCellSignalStrength().toString());
return ((CellInfoLte) currentCellInfo).getCellSignalStrength().getDbm();
} else if (currentCellInfo instanceof CellInfoGsm) {
return ((CellInfoGsm) currentCellInfo).getCellSignalStrength().getDbm();
} else {
return ((CellInfoCdma) currentCellInfo).getCellSignalStrength().getDbm();
}
}
String getNetworkType(CellInfo currentCellInfo){
if (currentCellInfo instanceof CellInfoWcdma) {
return "3G";
} else if (currentCellInfo instanceof CellInfoLte) {
return "4G";
} else
return "2G";
}
String getSingalQuality(CellInfo currentCellInfo){
int signalStrength = getSignalStrength(currentCellInfo);
if(signalStrength>-75){
return "Excellent";
}else if(signalStrength>-90){
return "Good";
}else if(signalStrength>-100){
return "Poor";
}else if(signalStrength>-109){
return "Very Poor";
}else{
return "No Signal";
}
}
}
<file_sep>package in.mytring;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
/**
* Created by shadabbaig on 13/02/17.
*/
public class ListenerService extends Service {
private ListenerThread listenerThread = null;
PhoneStateListener myPhoneStateListener;
TelephonyManager tm;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
if (listenerThread == null) {
listenerThread = new ListenerThread(this);
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (listenerThread == null)
listenerThread = new ListenerThread(this);
if ((listenerThread.getState() == Thread.State.NEW) || (listenerThread.getState() == Thread.State.TERMINATED)) {
if (listenerThread.getState() == Thread.State.TERMINATED)
listenerThread = new ListenerThread(this);
listenerThread.start();
// Notification localNotification = new Notification(R.drawable.ic_launcher, "", System.currentTimeMillis());
// localNotification.setLatestEventInfo(this,AppConstants.NOTIFICATION_NAME,AppConstants.NOTIFICATION_DESCRIPTION, null);
// localNotification.flags = Notification.FLAG_NO_CLEAR;
// startForeground(377982, localNotification);
//myPhoneStateListener = new MyTringPhoneStateListener(this);
// tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
// try {
// tm.listen(myPhoneStateListener,
// PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
//
//
// } catch (Exception e) {
//
// }
// Log.d("ListenerService", "Inside listener onStartCommand");
}
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
// listenerThread.yield();
// listenerThread = null;
}
}
<file_sep>package in.mytring;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.PowerManager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* Created by shadabbaig on 02/02/17.
*/
public class SpeedTestActivity extends AppCompatActivity {
private ProgressBar mProgress;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.speed_test);
mProgress = (ProgressBar) findViewById(R.id.progressBar);
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
getWindow().getDecorView().setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
}
public void startSpeedTest(View v) {
WifiManager wifiManager = (WifiManager) getBaseContext().getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
if (wifiInfo != null) {
Integer linkSpeed = wifiInfo.getLinkSpeed(); //measured using WifiInfo.LINK_SPEED_UNITS
TextView wifiSpeed = (TextView) findViewById( R.id.wifiDownloadSpeed);
wifiSpeed.setText(linkSpeed.toString()+" mbps");
}
}
private class DownloadTask extends AsyncTask<String, Integer, String> {
private Context context;
private PowerManager.WakeLock mWakeLock;
public DownloadTask(Context context) {
this.context = context;
}
@Override
protected String doInBackground(String... sUrl) {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(sUrl[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
// expect HTTP 200 OK, so we don't mistakenly save error report
// instead of the file
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
}
// this will be useful to display download percentage
// might be -1: server did not report the length
int fileLength = connection.getContentLength();
// download the file
input = connection.getInputStream();
output = new FileOutputStream("/sdcard/file_name.extension");
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
// allow canceling with back button
if (isCancelled()) {
input.close();
return null;
}
total += count;
// publishing the progress....
if (fileLength > 0) // only if total length is known
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
} catch (Exception e) {
return e.toString();
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
return null;
}
}
public void mobileDashboard(View v) {
Intent j = new Intent(SpeedTestActivity.this, in.mytring.MainActivity.class);
startActivity(j);
finish();
}
public void wifiDashboard(View v)
{
Intent j = new Intent(SpeedTestActivity.this, WifiActivity.class);
startActivity(j);
finish();
}
public void switchNetwork(View v) {
Intent i = new Intent(SpeedTestActivity.this, SwitchNetworkActivity.class);
startActivity(i);
finish();
}
public void settings(View v)
{
Intent j = new Intent(SpeedTestActivity.this, in.mytring.Settings.class);
startActivity(j);
finish();
}
}
<file_sep>package in.mytring;
import android.annotation.TargetApi;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* Created by Prem on 2/15/2017.
*/
public class WifiActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.wifi_layout);
//lv= (ListView) findViewById(R.id.list);
//getWifiNetworksList();
registerReceiver(broadcastReceiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
if (wifi.isWifiEnabled() == false) {
Toast.makeText(getApplicationContext(), "wifi is disabled..making it enabled", Toast.LENGTH_LONG).show();
wifi.setWifiEnabled(true);
}
getPermissionAndStartActivity();
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
getWindow().getDecorView().setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
}
public void mobileDashboard(View v) {
Intent i = new Intent(WifiActivity.this, in.mytring.MainActivity.class);
startActivity(i);
finish();
}
public void switchNetwork(View v) {
Intent i = new Intent(WifiActivity.this, SwitchNetworkActivity.class);
startActivity(i);
finish();
}
public void speedTest(View v) {
Intent j = new Intent(WifiActivity.this, SpeedTestActivity.class);
startActivity(j);
finish();
}
public void settings(View v)
{
Intent j = new Intent(WifiActivity.this, in.mytring.Settings.class);
startActivity(j);
finish();
}
/*private int size = 0;
private ListView lv;
List<ScanResult> scanList;
String ITEM_KEY = "key";
ArrayList<HashMap<String, String>> arraylist = new ArrayList<HashMap<String, String>>();
SimpleAdapter adapter;
private void getWifiNetworksList(){
IntentFilter filter = new IntentFilter();
filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
final WifiManager wifiManager =
(WifiManager)getApplicationContext().getSystemService(Context.WIFI_SERVICE);
if (wifiManager.isWifiEnabled() == false) {
Toast.makeText(getApplicationContext(), "wifi is disabled..making it enabled", Toast.LENGTH_LONG).show();
wifiManager.setWifiEnabled(true);
}
this.adapter = new SimpleAdapter(WifiActivity.this, arraylist, R.layout.activity_list_view_items, new String[]{ITEM_KEY}, new int[]{R.id.textView, R.id.imageView});
lv.setAdapter(this.adapter);
registerReceiver(new BroadcastReceiver(){
@SuppressLint("UseValueOf") @Override
public void onReceive(Context context, Intent intent) {
scanList = wifiManager.getScanResults();
size = scanList.size();
try {
size = size - 1;
while (size >= 0) {
HashMap<String, String> item = new HashMap<>();
item.put(ITEM_KEY, scanList.get(size).SSID + " " + scanList.get(size).capabilities);
arraylist.add(item);
size--;
adapter.notifyDataSetChanged();
}
} catch (Exception e) {
}
}
},filter);
wifiManager.startScan();
Toast.makeText(this, "Scanning...." + size, Toast.LENGTH_SHORT).show();
}*/
private static final String TAG = "WiFiActivity";
WifiManager wifi;
/* ListView lv;*/
int size = 0;
List<ScanResult> results;
String SSIDs="", networkType="", strengths="";
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
@TargetApi(22)
public void onReceive(Context c, Intent intent) {
if(null!=arraylist && !arraylist.isEmpty()){
arraylist.clear();
}
if(null!=results && !results.isEmpty()){
results.clear();
}
results = wifi.getScanResults();
size = results.size();
Log.d(TAG, " Size = "+ results.size()+"\n");
try {
size = size - 1;
while (size >= 0) {
HashMap<String, String> item = new HashMap<>();
Log.d(TAG, "KEY=" + ITEM_KEY+ "; Size= "+ size + "; SSID= " + results.get(size).SSID + "; Signal= " + results.get(size).level + "\n");
if (results.get(size).SSID != null && !results.get(size).SSID.isEmpty() && !results.get(size).SSID.equals(wifi.getConnectionInfo().getSSID().substring(1,wifi.getConnectionInfo().getSSID().length()-1))) {
item.put(ITEM_KEY, results.get(size).SSID + " " + results.get(size).level);
arraylist.add(item);
//adapter.notifyDataSetChanged();
SSIDs = SSIDs + results.get(size).SSID + System.lineSeparator() + System.lineSeparator();
if (results.get(size).capabilities.toUpperCase().contains("WEP")
|| results.get(size).capabilities.toUpperCase().contains("WPA")
|| results.get(size).capabilities.toUpperCase().contains("WPA2")) {
networkType = networkType + "Secured" + System.lineSeparator() + System.lineSeparator();
} else {
// Open Network
networkType = networkType + "Open" + System.lineSeparator() + System.lineSeparator();
}
strengths = strengths + results.get(size).level + System.lineSeparator() + System.lineSeparator();
}
size--;
}
displayAllWifis(SSIDs,networkType,strengths);
} catch (Exception e) {
e.printStackTrace();
}
}
};
String ITEM_KEY = "key";
ArrayList<HashMap<String, String>> arraylist = new ArrayList<HashMap<String, String>>();
SimpleAdapter adapter;
private static final int REQUEST_PERMISSIONS = 20;
public void getPermissionAndStartActivity(){
if (ContextCompat.checkSelfPermission(WifiActivity.this, android.Manifest.permission.ACCESS_COARSE_LOCATION) +
ContextCompat.checkSelfPermission(WifiActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION) +
ContextCompat.checkSelfPermission(WifiActivity.this, android.Manifest.permission.ACCESS_WIFI_STATE) +
ContextCompat.checkSelfPermission(WifiActivity.this, android.Manifest.permission.CHANGE_WIFI_STATE) +
ContextCompat.checkSelfPermission(WifiActivity.this, android.Manifest.permission.INTERNET)!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(WifiActivity.this, android.Manifest.permission.ACCESS_COARSE_LOCATION)||
ActivityCompat.shouldShowRequestPermissionRationale(WifiActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION) ||
ActivityCompat.shouldShowRequestPermissionRationale(WifiActivity.this, android.Manifest.permission.ACCESS_WIFI_STATE)||
ActivityCompat.shouldShowRequestPermissionRationale(WifiActivity.this, android.Manifest.permission.CHANGE_WIFI_STATE)||
ActivityCompat.shouldShowRequestPermissionRationale(WifiActivity.this, android.Manifest.permission.INTERNET)){
Snackbar.make(findViewById(android.R.id.content),
"Please Grant Permissions",
Snackbar.LENGTH_INDEFINITE).setAction("ENABLE",
new View.OnClickListener() {
@Override
public void onClick(View v) {
ActivityCompat.requestPermissions(WifiActivity.this,
new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION,android.Manifest.permission.ACCESS_FINE_LOCATION,
android.Manifest.permission.ACCESS_WIFI_STATE,android.Manifest.permission.CHANGE_WIFI_STATE,android.Manifest.permission.INTERNET}
,REQUEST_PERMISSIONS);
}
}).show();
} else {
ActivityCompat.requestPermissions(WifiActivity.this,new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION,
android.Manifest.permission.ACCESS_FINE_LOCATION,android.Manifest.permission.ACCESS_WIFI_STATE,
android.Manifest.permission.CHANGE_WIFI_STATE,android.Manifest.permission.INTERNET}, REQUEST_PERMISSIONS);
}
}else {
//Call whatever you want
startActivity();
}
}
@Override
public void onRequestPermissionsResult(int requestCode,
@NonNull String permissions[],
@NonNull int[] grantResults) {
switch (requestCode) {
case REQUEST_PERMISSIONS: {
if (null!=grantResults && (grantResults.length > 0) && (grantResults[0] +
grantResults[1]) == PackageManager.PERMISSION_GRANTED) {
//Call whatever you want
startActivity();
} else {
Snackbar.make(findViewById(android.R.id.content), "Enable Permissions from settings",Snackbar.LENGTH_INDEFINITE).setAction("ENABLE",
new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.setData(Uri.parse("package:" + getPackageName()));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
startActivity(intent);
}
}).show();
}
return;
}
}
}
//* Called when the activity is first created. *//*
@TargetApi(22)
public void startActivity() {
/*this.adapter = new SimpleAdapter(WifiActivity.this, arraylist, R.layout.activity_list_view_items, new String[]{ITEM_KEY}, new int[]{R.id.textView, R.id.imageView});
lv.setAdapter(this.adapter);*/
WifiInfo connectedWifi = wifi.getConnectionInfo();
String wifiDetails = "Connected To: " + connectedWifi.getSSID()+System.lineSeparator()+connectedWifi.getLinkSpeed()+"Mbps | "+ getSingalQuality(connectedWifi.getRssi());
TextView connectedWiFiDetails = (TextView) findViewById(R.id.Wifi_details_text);
connectedWiFiDetails.setText(wifiDetails);
arraylist.clear();
wifi.startScan();
Toast.makeText(this, "Scanning...." + size, Toast.LENGTH_SHORT).show();
}
String getSingalQuality(int signalStrength){
if(signalStrength>-75){
return "Excellent";
}else if(signalStrength>-90){
return "Good";
}else if(signalStrength>-100){
return "Poor";
}else if(signalStrength>-109){
return "Very Poor";
}else{
return "No Signal";
}
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
try {
if (broadcastReceiver != null)
unregisterReceiver(broadcastReceiver);
} catch (Exception e) {
}
super.onDestroy();
}
public void displayAllWifis(String SSIDs, String networkType, String strengths){
TextView displayAllSSIDs = (TextView) findViewById(R.id.scrollView_SSIDText);
displayAllSSIDs.setText(SSIDs);
TextView displayAllNWTypes = (TextView) findViewById(R.id.scrollView_networkTypeText);
displayAllNWTypes.setText(networkType);
TextView displayAllWifiStrength = (TextView) findViewById(R.id.scrollView_StrengthText);
displayAllWifiStrength.setText(strengths);
}
}
|
a5480d99d4d2a93d9ab162f487c1323462d9320b
|
[
"Java"
] | 4
|
Java
|
solelyshadab/MyTring
|
d7c4086bf231a7b1689aa30bcdb697144bdf5905
|
be105fbe6e28897f0f8fd940d6503ba80aaf30b2
|
refs/heads/master
|
<repo_name>tarampampam/tasker-php<file_sep>/src/Support/Traits/IOInteractsTrait.php
<?php
declare(strict_types = 1);
namespace Tarampampam\Tasker\Support\Traits;
use Symfony\Component\Console\Helper\ProgressBar;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Output\ConsoleOutputInterface;
trait IOInteractsTrait
{
/**
* Make visual progress bar customization.
*
* @param ProgressBar $progress_bar
* @param string $status
* @param int $bar_width
*
* @return ProgressBar
*/
protected function customizeProgressBar(ProgressBar $progress_bar,
string $status = 'In progress..',
int $bar_width = 60): ProgressBar
{
$progress_bar->setBarCharacter('<fg=green>▓</>');
$progress_bar->setEmptyBarCharacter('░');
$progress_bar->setProgressCharacter('▓');
$progress_bar->setBarWidth($bar_width);
$progress_bar->setFormat(
"Status: <options=bold>%status%</>\n%current%/%max% [%bar%] %percent:3s%% %memory:10s%"
);
$this->setProgressBarStatus($progress_bar, $status);
return $progress_bar;
}
/**
* Set progress bar message.
*
* @param ProgressBar $progress_bar
* @param string $message
*
* @return ProgressBar
*/
protected function setProgressBarStatus(ProgressBar $progress_bar, string $message): ProgressBar
{
$progress_bar->setMessage($message, 'status');
return $progress_bar;
}
/**
* Write some message into STDERR.
*
* @param OutputInterface $output
* @param string|string[] $messages The message as an iterable of strings or a single string
* @param bool $newline Whether to add a newline
* @param int $options A bitmask of options
*/
protected function error(OutputInterface $output,
$messages,
bool $newline = true,
int $options = 0)
{
$stderr = $output instanceof ConsoleOutputInterface
? $output->getErrorOutput()
: $output;
foreach ((array) $messages as $message) {
$stderr->write("<bg=red;fg=white> ERROR </> {$message}", $newline, $options);
}
}
/**
* Write into output message with default level.
*
* @param OutputInterface $output
* @param string|string[] $messages The message as an iterable of strings or a single string
* @param bool $new_line Whether to add a newline
* @param int $options A bitmask of options
*/
protected function log(OutputInterface $output,
$messages,
bool $new_line = true,
int $options = 0)
{
foreach ((array) $messages as $message) {
$output->write("<bg=blue;fg=white> ℹ ️</><fg=blue></>️ {$message}", $new_line, $options);
}
}
/**
* Write into output message with level 'verbose'.
*
* @param OutputInterface $output
* @param string|string[] $messages The message as an iterable of strings or a single string
* @param bool $new_line Whether to add a newline
* @param int $options A bitmask of options
*/
protected function verbose(OutputInterface $output,
$messages,
bool $new_line = true,
int $options = OutputInterface::VERBOSITY_VERBOSE)
{
foreach ((array) $messages as $message) {
$output->write("<bg=blue;fg=white> LOG </> {$message}", $new_line, $options);
}
}
/**
* Write into output message with level 'debug'.
*
* @param OutputInterface $output
* @param string|string[] $messages The message as an iterable of strings or a single string
* @param bool $new_line Whether to add a newline
* @param int $options A bitmask of options
*/
protected function debug(OutputInterface $output,
$messages,
bool $new_line = true,
int $options = OutputInterface::VERBOSITY_DEBUG)
{
foreach ((array) $messages as $message) {
$output->write("<bg=yellow;fg=black> DEBUG </> {$message}", $new_line, $options);
}
}
}
<file_sep>/tasks/LaravelDatabaseMigrateTask.php
<?php
declare(strict_types = 1);
namespace Tarampampam\Tasker\Tasks;
use Tarampampam\Tasker\Components\Task;
use Symfony\Component\Console\Output\OutputInterface;
use Tarampampam\Tasker\Support\Traits\IOInteractsTrait;
use Tarampampam\Tasker\Tasks\Traits\ExecProcessesTrait;
/**
* Task: Make laravel database migration.
*
* @link <https://laravel.com/docs/5.6/migrations>
*/
class LaravelDatabaseMigrateTask extends Task
{
use ExecProcessesTrait,
IOInteractsTrait;
/**
* Get default task name.
*
* @return string
*/
public static function defaultTaskName(): string
{
return 'laravel:migrate';
}
/**
* {@inheritdoc}
*/
public function defaultActions(): array
{
return [
// Migrate database
function (OutputInterface $output): bool {
$stdout = $stderr = [];
$process = $this->execArtisan($signature = $this->getMigrateCommandSignature(), $stdout, $stderr);
if (empty($stderr) && $process->isSuccessful()) {
$this->debug($output, $stdout);
return true;
}
$this->debug($output, \sprintf('Command [%s] failed', \implode(' ', $signature)));
return false;
},
];
}
/**
* Get `artisan migrate` command signature (without 'artisan' at first, of course).
*
* @return string[]
*/
public function getMigrateCommandSignature(): array
{
return [
'migrate',
'--force',
'--no-ansi',
];
}
/**
* {@inheritdoc}
*/
public function defaultChecks(): array
{
return [
// Make check - database is migrated?
function (OutputInterface $output): bool {
$stdout = $stderr = [];
$process = $this->execArtisan($this->getMigrateStatusCommandSignature(), $stdout, $stderr);
if (empty($stderr) && $process->isSuccessful()) {
$this->debug($output, $stdout);
// Parse stdout into structured array
$migrations = \array_filter(\array_map(function ($line) {
// Grep only lines with 'migration row' pattern
if (\is_string($line) && \preg_match('~\|[\sNnYn]+\|[[:print:]]+\|[\s\d]+\|~', $line) === 1) {
// Explode for columns (and make line a little bit clean before)
$columns = \explode('|', \str_replace(['\\|', '\\\\|'], '', $line));
return [
'ran' => \is_string($ran = ($columns[1] ?? false))
? \trim((string) $ran) === 'Y'
: false,
'name' => \trim($columns[2] ?? ''),
'batch' => \is_numeric($batch = trim($columns[3]))
? (int) $batch
: null,
];
}
}, $stdout));
// Migrations exists?
if (! empty($migrations)) {
// Try to find not migrated migration
foreach ($migrations as $migration) {
if (($migration['ran'] ?? false) === false) {
// If found - exit now with error
return false;
}
}
// If nothing found - all is ok
return true;
}
}
return false;
},
];
}
/**
* Get `artisan migrate:status` command signature (without 'artisan' at first, of course).
*
* @return string[]
*/
public function getMigrateStatusCommandSignature(): array
{
return [
'migrate:status',
'--no-ansi',
];
}
/**
* {@inheritdoc}
*/
public function defaultDescription()
{
return 'Migrate database for laravel applications';
}
}
<file_sep>/src/Commands/AbstractRunCommand.php
<?php
declare(strict_types = 1);
namespace Tarampampam\Tasker\Commands;
use Closure;
use ReflectionFunction;
use Tarampampam\Tasker\Support\StackInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Helper\ProgressBar;
use Symfony\Component\Console\Output\OutputInterface;
abstract class AbstractRunCommand extends AbstractCommand
{
// Task name option signature
const TASK_NAME_OPTION_NAME = 'task-name';
// Fast stop option signature
const FAST_STOP_OPTION_NAME = 'fast-stop';
/**
* {@inheritdoc}
*/
protected function configure()
{
parent::configure();
$this
->addOption(
static::TASK_NAME_OPTION_NAME,
't',
InputOption::VALUE_IS_ARRAY | InputOption::VALUE_OPTIONAL,
'Task name'
)
->addOption(
static::FAST_STOP_OPTION_NAME,
null,
InputOption::VALUE_NONE,
'Stop execution of first action fail'
);
}
/**
* Make selection of tasks for a work, based on passed to method.
*
* @param array $passed_tasks_names
*
* @return array|string[]
*/
protected function selectTasksNames(array $passed_tasks_names): array
{
$tasks = $this->getApplication()->getConfiguration()->tasks();
// If nothing passed - returns all available tasks
return empty($passed_tasks_names)
? $tasks->names()
// Otherwise - remove invalid task names and return them
: \array_filter($passed_tasks_names, function ($name) use ($tasks) {
return $tasks->exists((string) $name);
});
}
/**
* Iterate each callable in passed callable-stack.
*
* @param StackInterface $callable_stack
* @param StackInterface $errors
* @param OutputInterface $output
* @param bool $stop_on_first_error
*
* @return bool
*/
protected function iterateCallableStack(StackInterface $callable_stack,
StackInterface $errors,
OutputInterface $output,
bool $stop_on_first_error = false): bool
{
// Make check - callable stack is not empty?
if (($callable_count = $callable_stack->count()) > 0) {
$progress_bar = $this->customizeProgressBar(new ProgressBar($output, $callable_count));
// Start checks iterator
foreach ($callable_stack->all() as $callable) {
if (\is_callable($callable)) {
try {
// Execute callable
if ($callable($output) === false) {
$message = 'Called function returns false';
// Attach additional info about called closure
if ($callable instanceof Closure) {
$reflection = new ReflectionFunction($callable);
$message .= " ({$reflection->getFileName()}:{$reflection->getStartLine()})";
}
$errors->add($message);
}
} catch (\Exception $e) {
$errors->add("{$e->getMessage()} ({$e->getFile()}:{$e->getLine()})");
}
}
if ($errors->isNotEmpty()) {
$progress_bar->setMessage("We'v got an error ({$errors->count()})", 'status');
// Stop on first error logic
if ($stop_on_first_error === true) {
break;
}
}
$progress_bar->advance();
}
$progress_bar->setMessage('Functions execution completed ' . ($errors->isEmpty()
? 'successful'
: "with errors ({$errors->count()})"), 'status');
$progress_bar->finish();
$output->write(PHP_EOL);
return true;
}
return false;
}
}
<file_sep>/tests/Commands/TaskCheckCommandTest.php
<?php
declare(strict_types = 1);
namespace Tarampampam\Tasker\Tests\Commands;
use Symfony\Component\Console\Input\InputOption;
use Tarampampam\Tasker\Commands\TaskCheckCommand;
use Symfony\Component\Console\Tester\CommandTester;
/**
* @covers \Tarampampam\Tasker\Commands\TaskCheckCommand
*/
class TaskCheckCommandTest extends AbstractRunCommandTestCase
{
/**
* @var TaskCheckCommand
*/
protected $command;
/**
* {@inheritdoc}
*/
public function expectedCommandName(): string
{
return 'task:check';
}
/**
* {@inheritdoc}
*/
public function expectedCommandDescription(): string
{
return 'checks';
}
/**
* @return TaskCheckCommand
*/
public function commandFactory()
{
return new class extends TaskCheckCommand {
public $sleep_exec_counter = 0;
protected function sleep(int $seconds = 0)
{
$this->sleep_exec_counter++;
parent::sleep($seconds);
}
protected function doSleep(int $seconds)
{
// Do nothing
}
};
}
/**
* @return void
*/
public function testConstants()
{
$this->assertSame('loop', $this->command::LOOP_OPTION_NAME);
$this->assertSame('delay', $this->command::LOOP_DELAY_OPTION_NAME);
$this->assertSame('limit', $this->command::TRIES_LIMIT_OPTION_NAME);
}
/**
* @covers \Tarampampam\Tasker\Commands\TaskCheckCommand::configure
*
* @return void
*/
public function testAbstractConfigure()
{
parent::testAbstractConfigure();
/** @var InputOption $fast_stop_option */
$fast_stop_option = $this->command->getDefinition()->getOption($this->command::LOOP_OPTION_NAME);
$this->assertNull($fast_stop_option->getShortcut());
$this->assertFalse($fast_stop_option->acceptValue());
/** @var InputOption $task_name_option */
$task_name_option = $this->command->getDefinition()->getOption($this->command::LOOP_DELAY_OPTION_NAME);
$this->assertNull($fast_stop_option->getShortcut());
$this->assertTrue($task_name_option->isValueOptional());
/** @var InputOption $task_name_option */
$task_name_option = $this->command->getDefinition()->getOption($this->command::TRIES_LIMIT_OPTION_NAME);
$this->assertNull($fast_stop_option->getShortcut());
$this->assertTrue($task_name_option->isValueOptional());
}
/**
* @covers \Tarampampam\Tasker\Commands\TaskCheckCommand::execute
*
* @return void
*/
public function testExecutionWithoutPassingAnyTasks()
{
$first_executed = false;
$second_executed = false;
$this->app->getConfiguration()->tasks()
->addCheck('foo', function () use (&$first_executed) {
$first_executed = true;
})
->addCheck('bar', function () use (&$second_executed) {
$second_executed = true;
});
$tester = new CommandTester($this->command);
$this->assertSame(0, $tester->execute([]));
$this->assertTrue($first_executed);
$this->assertTrue($second_executed);
}
/**
* @covers \Tarampampam\Tasker\Commands\TaskCheckCommand::execute
*
* @return void
*/
public function testExecutionWithPassingOneTaskName()
{
$first_executed = false;
$second_executed = false;
$this->app->getConfiguration()->tasks()
->addCheck($task_name = 'foo', function () use (&$first_executed) {
$first_executed = true;
})
->addCheck('bar', function () use (&$second_executed) {
$second_executed = true;
});
$tester = new CommandTester($this->command);
$this->assertSame(0, $tester->execute([
'--' . $this->command::TASK_NAME_OPTION_NAME => $task_name,
]));
$this->assertTrue($first_executed);
$this->assertFalse($second_executed);
}
/**
* @covers \Tarampampam\Tasker\Commands\TaskCheckCommand::execute
*
* @return void
*/
public function testExecutionWithPassingMultipleTaskNames()
{
$first_executed = false;
$second_executed = false;
$this->app->getConfiguration()->tasks()
->addCheck($first_check_name = 'foo', function () use (&$first_executed) {
$first_executed = true;
})
->addCheck($second_check_name = 'bar', function () use (&$second_executed) {
$second_executed = true;
});
$tester = new CommandTester($this->command);
$this->assertSame(0, $tester->execute([
'--' . $this->command::TASK_NAME_OPTION_NAME => [$first_check_name, $second_check_name],
]));
$this->assertTrue($first_executed);
$this->assertTrue($second_executed);
}
/**
* @covers \Tarampampam\Tasker\Commands\TaskCheckCommand::execute
*
* @return void
*/
public function testExecutionWithErrors()
{
$first_executed = false;
$second_executed = false;
$this->app->getConfiguration()->tasks()
->addCheck($first_check_name = 'foo', function () use (&$first_executed) {
$first_executed = true;
return false;
})
->addCheck($second_check_name = 'bar', function () use (&$second_executed) {
$second_executed = true;
return false;
});
$tester = new CommandTester($this->command);
$this->assertSame(1, $tester->execute([
'--' . $this->command::TASK_NAME_OPTION_NAME => [$first_check_name, $second_check_name],
]));
$this->assertTrue($first_executed);
$this->assertTrue($second_executed);
}
/**
* @covers \Tarampampam\Tasker\Commands\TaskCheckCommand::execute
*
* @return void
*/
public function testExecutionWithLoopAndDelay()
{
$check_executed = false;
$this->app->getConfiguration()->tasks()
->addCheck($check_name = 'foo', function () use (&$check_executed) {
$check_executed = true;
return false;
});
$tester = new CommandTester($this->command);
$this->assertSame(1, $tester->execute([
'--' . $this->command::TASK_NAME_OPTION_NAME => $check_name,
'--' . $this->command::LOOP_OPTION_NAME => true,
'--' . $this->command::TRIES_LIMIT_OPTION_NAME => $try_count = 3,
]));
$this->assertSame($try_count, $this->command->sleep_exec_counter);
$this->assertTrue($check_executed);
}
/**
* @covers \Tarampampam\Tasker\Commands\TaskCheckCommand::execute
*
* @return void
*/
public function testExecutionWithInvalidTaskName()
{
$this->expectException(\InvalidArgumentException::class);
$tester = new CommandTester($this->command);
$tester->execute([
'--' . $this->command::TASK_NAME_OPTION_NAME => 'foo',
]);
}
}
<file_sep>/src/Commands/TaskListCommand.php
<?php
declare(strict_types = 1);
namespace Tarampampam\Tasker\Commands;
use Symfony\Component\Console\Helper\Table;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class TaskListCommand extends AbstractCommand
{
/**
* {@inheritdoc}
*/
public static function getCommandName(): string
{
return 'task:list';
}
/**
* {@inheritdoc}
*/
public static function getCommandDescription(): string
{
return 'Show all available tasks in table view';
}
/**
* {@inheritdoc}
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
parent::execute($input, $output);
$tasks = $this->getApplication()->getConfiguration()->tasks();
if ($tasks->count() > 0) {
$table = (new Table($output))
->setHeaders(['Task name', 'Actions count', 'Checks count', 'Description']);
foreach ($tasks->all() as $task_name => $task) {
// Show only stacks with non-empty tasks or checks
if ((($actions_count = $task->actions()->count()) + ($check_count = $task->checks()->count())) > 0) {
$table->addRow([
"<options=bold>$task_name</>",
$actions_count,
$check_count,
'<comment>' . ($task->description() ?? '-') . '</comment>',
]);
}
}
$table->render();
} else {
$output->writeln('<info>Tasks was not found</info>');
}
}
}
<file_sep>/tests/Support/Traits/MacroableTraitTest.php
<?php
declare(strict_types = 1);
namespace Tarampampam\Tasker\Tests\Support\Traits;
use BadMethodCallException;
use Tarampampam\Tasker\Tests\AbstractTestCase;
/**
* @covers \Tarampampam\Tasker\Support\Traits\MacroableTrait
*/
class MacroableTraitTest extends AbstractTestCase
{
/**
* @var MacroableMock
*/
protected $instance;
/**
* {@inheritdoc}
*/
protected function setUp()
{
parent::setUp();
$this->instance = new MacroableMock;
}
/**
* {@inheritdoc}
*/
protected function tearDown()
{
unset($this->instance);
parent::tearDown();
}
/**
* @covers \Tarampampam\Tasker\Support\Traits\MacroableTrait::hasMacro
* @covers \Tarampampam\Tasker\Support\Traits\MacroableTrait::macro
* @covers \Tarampampam\Tasker\Support\Traits\MacroableTrait::__call
* @covers \Tarampampam\Tasker\Support\Traits\MacroableTrait::__callStatic
*
* @return void
*/
public function testMacrosClosure()
{
$this->assertFalse($this->instance::hasMacro($macros_name = 'fooBar'));
$this->instance::macro($macros_name, function ($value) {
return $value;
});
$this->assertTrue($this->instance::hasMacro($macros_name));
$this->assertSame($expected = 'bar baz', $this->instance::{$macros_name}($expected));
$this->assertSame($expected = 123, $this->instance->{$macros_name}($expected));
}
/**
* @covers \Tarampampam\Tasker\Support\Traits\MacroableTrait::macro
* @covers \Tarampampam\Tasker\Support\Traits\MacroableTrait::__call
* @covers \Tarampampam\Tasker\Support\Traits\MacroableTrait::__callStatic
*
* @return void
*/
public function testPassingNotCallable()
{
$this->instance::macro($name = 'foo', [$this, 'getPassedValue']);
$this->assertEquals($expects = 'bar', $this->instance->{$name}($expects));
$this->assertEquals($expects = 'bar', $this->instance::{$name}($expects));
}
/**
* @covers \Tarampampam\Tasker\Support\Traits\MacroableTrait::mixin
* @covers \Tarampampam\Tasker\Support\Traits\MacroableTrait::__call
* @covers \Tarampampam\Tasker\Support\Traits\MacroableTrait::__callStatic
*
* @return void
*/
public function testMacrosObject()
{
$macros = new class {
public function foo()
{
return function ($value) {
return $value;
};
}
};
$this->instance::mixin($macros);
$this->assertSame($expected = 'bar baz', $this->instance::foo($expected));
$this->assertSame($expected = 123, $this->instance->foo($expected));
}
/**
* @covers \Tarampampam\Tasker\Support\Traits\MacroableTrait::__call
*
* @return void
*/
public function testNotExistsMethodCalling()
{
$this->expectException(BadMethodCallException::class);
$macros_name = 'nonExistsMacrosName' . \random_int(0, 1000);
$this->instance->{$macros_name}();
}
/**
* @covers \Tarampampam\Tasker\Support\Traits\MacroableTrait::__callStatic
*
* @return void
*/
public function testNotExistsStaticMethodCalling()
{
$this->expectException(BadMethodCallException::class);
$macros_name = 'nonExistsMacrosName' . \random_int(0, 1000);
$this->instance::{$macros_name}();
}
/**
* Getter for any passed value(s).
*
* @param mixed $value
*
* @return mixed
*/
public function getPassedValue($value)
{
return $value;
}
}
<file_sep>/tests/Stubs/samples/configs/empty.php
<?php
return new \Tarampampam\Tasker\Components\TasksStack;
<file_sep>/tests/Exceptions/ExceptionsTest.php
<?php
declare(strict_types = 1);
namespace Tarampampam\Tasker\Tests\Exceptions;
use Tarampampam\Tasker\Tests\AbstractTestCase;
use Symfony\Component\Console\Exception\ExceptionInterface;
use Tarampampam\Tasker\Exceptions\InvalidConfigurationException;
use Tarampampam\Tasker\Exceptions\MissingConfigurationException;
class ExceptionsTest extends AbstractTestCase
{
/**
* @covers \Tarampampam\Tasker\Exceptions\InvalidConfigurationException
* @covers \Tarampampam\Tasker\Exceptions\MissingConfigurationException
*
* @return void
*/
public function testExceptions()
{
$classes = [
InvalidConfigurationException::class,
MissingConfigurationException::class,
];
foreach ($classes as $class) {
$this->assertInstanceOf(ExceptionInterface::class, $instance = new $class);
}
}
}
<file_sep>/tasks/Traits/ExecProcessesTrait.php
<?php
declare(strict_types = 1);
namespace Tarampampam\Tasker\Tasks\Traits;
use Symfony\Component\Process\Process;
trait ExecProcessesTrait
{
/**
* Execute artisan process.
*
* @param array $arguments
* @param array $stdout
* @param array $stderr
* @param float|null $timeout Process timeout (in seconds) or null to disable
*
* @return Process
*/
protected function execArtisan(array $arguments,
array &$stdout,
array &$stderr,
$timeout = 5.0): Process
{
return $this->execProcess(
\array_merge([PHP_BINARY, $this->getArtisanLocation()], $arguments),
$stdout,
$stderr,
$timeout
);
}
/**
* Execute process.
*
* @param string[] $arguments
* @param array $stdout
* @param array $stderr
* @param float|null $timeout Process timeout (in seconds) or null to disable
*
* @return Process
*/
protected function execProcess(array $arguments,
array &$stdout,
array &$stderr,
$timeout = 5.0): Process
{
$process = new Process(
$arguments,
$this->getWorkingDirectoryPath(),
null,
null,
$timeout
);
$process->run(function ($type, $line) use (&$stdout, &$stderr) {
$lines = (array) \preg_split('(\\r\\n|\\r|\\n)', $line);
if ($type === Process::ERR) {
$stderr = \array_merge($stderr, $lines);
} else {
$stdout = \array_merge($stdout, $lines);
}
});
return $process;
}
/**
* Get working directory path.
*
* @throws \RuntimeException
*
* @return string
*/
protected function getWorkingDirectoryPath(): string
{
if (\is_dir($current_directory = (string) \getcwd())) {
return $current_directory;
}
// @codeCoverageIgnoreStart
throw new \RuntimeException('Cannot resolve current working directory path');
// @codeCoverageIgnoreEnd
}
/**
* Get artisan file location.
*
* @return string
*/
protected function getArtisanLocation(): string
{
return $this->getWorkingDirectoryPath() . DIRECTORY_SEPARATOR . 'artisan';
}
}
<file_sep>/tests/Support/Traits/StaticSelfFactoryTraitTest.php
<?php
declare(strict_types = 1);
namespace Tarampampam\Tasker\Tests\Support\Traits;
use Tarampampam\Tasker\Tests\AbstractTestCase;
/**
* @covers \Tarampampam\Tasker\Support\Traits\StaticSelfFactoryTrait
*/
class StaticSelfFactoryTraitTest extends AbstractTestCase
{
/**
* @covers \Tarampampam\Tasker\Support\Traits\StaticSelfFactoryTrait::make
*
* @return void
*/
public function testMake()
{
$this->assertInstanceOf(StaticSelfFactoryTraitMock::class, $instance = StaticSelfFactoryTraitMock::make($value = 'foo bar'));
$this->assertSame($value, $instance->foo);
}
}
<file_sep>/src/Components/Configuration.php
<?php
declare(strict_types = 1);
namespace Tarampampam\Tasker\Components;
use Tarampampam\Tasker\Exceptions\InvalidConfigurationException;
use Tarampampam\Tasker\Exceptions\MissingConfigurationException;
class Configuration
{
/**
* Default configuration file name.
*
* @var string
*/
const DEFAULT_CONFIG_FILE_NAME = '.tasker.php';
/**
* @var TasksStack
*/
protected $tasks_stack;
/**
* @var string|null
*/
protected $file_path;
/**
* Create a new configuration.
*
* @param string $file_path
*/
public function __construct(string $file_path = null)
{
$this->tasks_stack = $file_path === null
? new TasksStack
: $this->readFile($file_path);
}
/**
* Load tasks from configuration file ad re-initialize tasks stack.
*
* @param string $file_path
*
* @return $this
*/
public function loadFrom(string $file_path)
{
$this->tasks_stack = $this->readFile($file_path);
return $this;
}
/**
* Get configuration file path.
*
* @return null|string
*/
public function loadedFrom()
{
return $this->file_path;
}
/**
* Get the tasks stack.
*
* @return TasksStack
*/
public function tasks(): TasksStack
{
return $this->tasks_stack;
}
/**
* Read tasks from configuration file.
*
* @param string $file_path
*
* @throws MissingConfigurationException
* @throws InvalidConfigurationException
*
* @return TasksStack
*/
protected function readFile(string $file_path): TasksStack
{
$this->file_path = $file_path;
if (\is_file($file_path)) {
$configuration = require $file_path;
if ($configuration instanceof TasksStack) {
return $configuration;
}
throw new InvalidConfigurationException(sprintf(
"Configuration file [{$file_path}] should return object type of [%s]", TasksStack::class
));
}
throw new MissingConfigurationException("Configuration file [{$file_path}] does not exists");
}
}
<file_sep>/tests/Components/ConfigurationTest.php
<?php
declare(strict_types = 1);
namespace Tarampampam\Tasker\Tests\Components;
use Tarampampam\Tasker\Tests\AbstractTestCase;
use Tarampampam\Tasker\Components\Configuration;
use Tarampampam\Tasker\Exceptions\InvalidConfigurationException;
use Tarampampam\Tasker\Exceptions\MissingConfigurationException;
/**
* @covers \Tarampampam\Tasker\Components\Configuration
*/
class ConfigurationTest extends AbstractTestCase
{
/**
* @var Configuration
*/
protected $configuration;
/**
* {@inheritdoc}
*/
protected function setUp()
{
parent::setUp();
$this->configuration = new Configuration;
}
/**
* {@inheritdoc}
*/
protected function tearDown()
{
unset($this->configuration);
parent::tearDown();
}
/**
* @covers \Tarampampam\Tasker\Components\Configuration::__construct
* @covers \Tarampampam\Tasker\Components\Configuration::loadedFrom
*
* @return void
*/
public function testConstructor()
{
$configuration = new Configuration;
$this->assertNull($configuration->loadedFrom());
$configuration = new Configuration($loaded_from = __DIR__ . '/stubs/valid_configuration.php');
$this->assertSame($loaded_from, $configuration->loadedFrom());
}
/**
* @covers \Tarampampam\Tasker\Components\Configuration::loadFrom
* @covers \Tarampampam\Tasker\Components\Configuration::loadedFrom
*
* @return void
*/
public function testLoadFrom()
{
$this->assertInstanceOf(
Configuration::class,
$this->configuration->loadFrom($loaded_from = __DIR__ . '/stubs/valid_configuration.php')
);
$this->assertSame($loaded_from, $this->configuration->loadedFrom());
}
/**
* @covers \Tarampampam\Tasker\Components\Configuration::tasks
* @covers \Tarampampam\Tasker\Components\Configuration::readFile
*
* @return void
*/
public function testReadFile()
{
$this->assertEmpty($this->configuration->tasks());
$this->configuration->loadFrom($loaded_from = __DIR__ . '/stubs/valid_configuration.php');
$this->assertTrue($this->configuration->tasks()->exists('foo'));
}
/**
* @covers \Tarampampam\Tasker\Components\Configuration::readFile
*
* @return void
*/
public function testReadFileWithWrongContent()
{
$this->expectException(InvalidConfigurationException::class);
$this->configuration->loadFrom(__DIR__ . '/stubs/invalid_configuration.php');
}
/**
* @covers \Tarampampam\Tasker\Components\Configuration::readFile
*
* @return void
*/
public function testReadFileWithMissingFile()
{
$this->expectException(MissingConfigurationException::class);
$this->configuration->loadFrom(__DIR__ . '/foo_bar' . \random_int(0, 1000));
}
}
<file_sep>/tests/Tasks/LaravelDatabaseMigrateTaskTest.php
<?php
declare(strict_types = 1);
namespace Tarampampam\Tasker\Tests\Tasks;
use Symfony\Component\Process\Process;
use Tarampampam\Tasker\Tests\AbstractTestCase;
use Symfony\Component\Console\Output\BufferedOutput;
use Tarampampam\Tasker\Support\Traits\IOInteractsTrait;
use Tarampampam\Tasker\Tasks\Traits\ExecProcessesTrait;
use Tarampampam\Tasker\Tasks\LaravelDatabaseMigrateTask;
/**
* @covers \Tarampampam\Tasker\Tasks\LaravelDatabaseMigrateTask
*/
class LaravelDatabaseMigrateTaskTest extends AbstractTestCase
{
/**
* @var LaravelDatabaseMigrateTask
*/
protected $task;
/**
* {@inheritdoc}
*/
protected function setUp()
{
parent::setUp();
$this->task = new LaravelDatabaseMigrateTask;
}
/**
* {@inheritdoc}
*/
protected function tearDown()
{
unset($this->task);
parent::tearDown();
}
/**
* @covers \Tarampampam\Tasker\Tasks\LaravelDatabaseMigrateTask
*
* @return void
*/
public function testTraitsUsage()
{
foreach ([ExecProcessesTrait::class, IOInteractsTrait::class] as $trait_class) {
$this->assertClassUsesTraits(LaravelDatabaseMigrateTask::class, $trait_class);
}
}
/**
* @covers \Tarampampam\Tasker\Tasks\LaravelDatabaseMigrateTask::getMigrateCommandSignature
* @covers \Tarampampam\Tasker\Tasks\LaravelDatabaseMigrateTask::getMigrateStatusCommandSignature
*
* @return void
*/
public function testSignatureGetters()
{
$this->assertSame(['migrate', '--force', '--no-ansi'], $this->task->getMigrateCommandSignature());
$this->assertSame(['migrate:status', '--no-ansi'], $this->task->getMigrateStatusCommandSignature());
}
/**
* @covers \Tarampampam\Tasker\Tasks\LaravelDatabaseMigrateTask::defaultDescription
* @covers \Tarampampam\Tasker\Tasks\LaravelDatabaseMigrateTask::defaultTaskName
*
* @return void
*/
public function testTaskDecorateMethods()
{
$this->assertRegExp('~migrate.+laravel~i', $this->task->defaultDescription());
$this->assertSame('laravel:migrate', $this->task::defaultTaskName());
}
/**
* @covers \Tarampampam\Tasker\Tasks\LaravelDatabaseMigrateTask::defaultActions
*
* @return void
*/
public function testFirstDefaultActionWithSuccess()
{
$stub = $this->getInstanceWithMockedExecArtisanMethod(true, ['Nothing to migrate.', '']);
$this->assertTrue($stub->defaultActions()[0](new BufferedOutput()));
}
/**
* @covers \Tarampampam\Tasker\Tasks\LaravelDatabaseMigrateTask::defaultActions
*
* @return void
*/
public function testFirstDefaultActionWithJustMigrated()
{
$stub = $this->getInstanceWithMockedExecArtisanMethod(true, [
'Migration table created successfully.',
'Migrating: 2014_10_12_000000_create_users_table',
'Migrated: 2014_10_12_000000_create_users_table',
]);
$this->assertTrue($stub->defaultActions()[0](new BufferedOutput()));
}
/**
* @covers \Tarampampam\Tasker\Tasks\LaravelDatabaseMigrateTask::defaultActions
*
* @return void
*/
public function testFirstDefaultActionWithError()
{
$stub = $this->getInstanceWithMockedExecArtisanMethod(false);
$this->assertFalse($stub->defaultActions()[0](new BufferedOutput()));
}
/**
* @covers \Tarampampam\Tasker\Tasks\LaravelDatabaseMigrateTask::defaultActions
*
* @return void
*/
public function testFirstDefaultActionWithFullStdErr()
{
$stub = $this->getInstanceWithMockedExecArtisanMethod(true, [], ['Fuck up']);
$this->assertFalse($stub->defaultActions()[0](new BufferedOutput()));
}
/**
* @covers \Tarampampam\Tasker\Tasks\LaravelDatabaseMigrateTask::defaultChecks
*
* @return void
*/
public function testFirstDefaultCheckWithSuccess()
{
$stub = $this->getInstanceWithMockedExecArtisanMethod(true, [
'+------+------------------------------------------------+-------+',
'| Ran? | Migration | Batch |',
'+------+------------------------------------------------+-------+',
'| Y | 2014_10_12_000000_create_users_table | 1 |',
'| Y | 2014_10_12_100000_create_password_resets_table | 1 |',
'+------+------------------------------------------------+-------+',
]);
$this->assertTrue($stub->defaultChecks()[0]($output = new BufferedOutput(BufferedOutput::VERBOSITY_DEBUG)));
}
/**
* @covers \Tarampampam\Tasker\Tasks\LaravelDatabaseMigrateTask::defaultChecks
*
* @return void
*/
public function testFirstDefaultCheckWithNonMigratedMigrations()
{
$stub = $this->getInstanceWithMockedExecArtisanMethod(true, [
'+------+------------------------------------------------+-------+',
'| Ran? | Migration | Batch |',
'+------+------------------------------------------------+-------+',
'| N | 2014_10_12_000000_create_users_table | |',
'| N | 2014_10_12_100000_create_password_resets_table | |',
'+------+------------------------------------------------+-------+',
]);
$this->assertFalse($stub->defaultChecks()[0]($output = new BufferedOutput(BufferedOutput::VERBOSITY_DEBUG)));
}
/**
* @covers \Tarampampam\Tasker\Tasks\LaravelDatabaseMigrateTask::defaultChecks
*
* @return void
*/
public function testFirstDefaultCheckWithNonMigratedSingleMigration()
{
$stub = $this->getInstanceWithMockedExecArtisanMethod(true, [
'+------+------------------------------------------------+-------+',
'| Ran? | Migration | Batch |',
'+------+------------------------------------------------+-------+',
'| Y | 2014_10_12_000000_create_users_table | 1 |',
'| N | 2014_10_12_100000_create_password_resets_table | |',
'+------+------------------------------------------------+-------+',
]);
$this->assertFalse($stub->defaultChecks()[0]($output = new BufferedOutput(BufferedOutput::VERBOSITY_DEBUG)));
}
/**
* @covers \Tarampampam\Tasker\Tasks\LaravelDatabaseMigrateTask::defaultChecks
*
* @return void
*/
public function testFirstDefaultCheckWithSomethingInStdErr()
{
$stub = $this->getInstanceWithMockedExecArtisanMethod(true, [
'+------+------------------------------------------------+-------+',
'| Ran? | Migration | Batch |',
'+------+------------------------------------------------+-------+',
'| Y | 2014_10_12_000000_create_users_table | 1 |',
'| Y | 2014_10_12_100000_create_password_resets_table | 1 |',
'+------+------------------------------------------------+-------+',
], ['Fuck up']);
$this->assertFalse($stub->defaultChecks()[0]($output = new BufferedOutput(BufferedOutput::VERBOSITY_DEBUG)));
}
/**
* @covers \Tarampampam\Tasker\Tasks\LaravelDatabaseMigrateTask::defaultChecks
*
* @return void
*/
public function testFirstDefaultCheckWithoutMigrationsTable()
{
$stub = $this->getInstanceWithMockedExecArtisanMethod(true, []);
$this->assertFalse($stub->defaultChecks()[0]($output = new BufferedOutput(BufferedOutput::VERBOSITY_DEBUG)));
}
/**
* Returns task instance with mocked "execArtisan" method.
*
* @param bool $is_success
* @param string[] $fake_stdout
* @param string[] $fake_stderr
*
* @return LaravelDatabaseMigrateTask
*/
protected function getInstanceWithMockedExecArtisanMethod(bool $is_success = true,
array $fake_stdout = [],
array $fake_stderr = []): LaravelDatabaseMigrateTask
{
$stub = $this
->getMockBuilder(LaravelDatabaseMigrateTask::class)
->setMethods([$exec_artisan = 'execArtisan'])
->getMock();
$stub
->method($exec_artisan)
->willReturnCallback(function (array $arguments, array &$stdout, array &$stderr, $timeout = 5.0) use (
$is_success,
$fake_stdout,
$fake_stderr
) {
$stdout = $fake_stdout;
$stderr = $fake_stderr;
$process = new Process($is_success === true
? PHP_BINARY . ' -v'
: PHP_BINARY . ' -r "exit(1);"'
);
$process->run();
return $process;
});
/* @var LaravelDatabaseMigrateTask $stub */
return $stub;
}
}
<file_sep>/tests/Support/StackTest.php
<?php
declare(strict_types = 1);
namespace Tarampampam\Tasker\Tests\Support;
use Countable;
use ArrayAccess;
use IteratorAggregate;
use Tarampampam\Tasker\Support\Stack;
use Tarampampam\Tasker\Support\StackInterface;
use Tarampampam\Tasker\Tests\AbstractTestCase;
use Tarampampam\Tasker\Support\Traits\MacroableTrait;
use Tarampampam\Tasker\Support\Traits\StaticSelfFactoryTrait;
/**
* @covers \Tarampampam\Tasker\Support\Stack
*/
class StackTest extends AbstractTestCase
{
/**
* @var Stack
*/
protected $stack;
/**
* {@inheritdoc}
*/
protected function setUp()
{
parent::setUp();
$this->stack = new Stack;
}
/**
* {@inheritdoc}
*/
protected function tearDown()
{
unset($this->stack);
parent::tearDown();
}
/**
* @return void
*/
public function testInterfaces()
{
$this->assertInstanceOf(StackInterface::class, $this->stack);
$this->assertInstanceOf(Countable::class, $this->stack);
$this->assertInstanceOf(ArrayAccess::class, $this->stack);
$this->assertInstanceOf(IteratorAggregate::class, $this->stack);
}
/**
* @return void
*/
public function testTraits()
{
$this->assertClassUsesTraits($this->stack, StaticSelfFactoryTrait::class);
$this->assertClassUsesTraits($this->stack, MacroableTrait::class);
}
/**
* @covers \Tarampampam\Tasker\Support\Stack::__construct
* @covers \Tarampampam\Tasker\Support\Stack::all
*
* @return void
*/
public function testConstructor()
{
$this->assertEquals($expected = [1, 2, 'foo', false, null, [], new \stdClass], (new Stack($expected))->all());
}
/**
* @covers \Tarampampam\Tasker\Support\Stack::put
* @covers \Tarampampam\Tasker\Support\Stack::get
* @covers \Tarampampam\Tasker\Support\Stack::forget
*
* @return void
*/
public function testDataAccessMethods()
{
$this->assertInstanceOf(Stack::class, $this->stack->put($key = 'foo', $value = 'bar'));
$this->assertSame($value, $this->stack->get($key));
$this->assertNull($this->stack->get($not_exists = 'not exists' . \random_int(0, 2048)));
$this->assertSame($default = 123, $this->stack->get($not_exists, $default));
$this->assertInstanceOf(Stack::class, $this->stack->forget($not_exists));
$this->stack->put($key2 = 'foo2', $value2 = 'bar2');
$this->assertSame($value2, $this->stack->get($key2));
$this->stack->forget([$key, $key2]);
$this->assertNull($this->stack->get($key));
$this->assertNull($this->stack->get($key2));
$this->stack->put($key3 = 'foo3', $value3 = 'bar3');
$this->assertSame($value3, $this->stack->get($key3));
$this->stack->forget($key3);
$this->assertNull($this->stack->get($key3));
}
/**
* @covers \Tarampampam\Tasker\Support\Stack::add
* @covers \Tarampampam\Tasker\Support\Stack::isNotEmpty
* @covers \Tarampampam\Tasker\Support\Stack::isEmpty
*
* @return void
*/
public function testAddEndEmpty()
{
$this->assertTrue($this->stack->isEmpty());
$this->assertFalse($this->stack->isNotEmpty());
$this->assertInstanceOf(Stack::class, $this->stack->add('foo'));
$this->assertFalse($this->stack->isEmpty());
$this->assertTrue($this->stack->isNotEmpty());
}
/**
* @covers \Tarampampam\Tasker\Support\Stack::add
* @covers \Tarampampam\Tasker\Support\Stack::each
* @covers \Tarampampam\Tasker\Support\Stack::count
*
* @return void
*/
public function testEach()
{
$counter = 0;
$values = [true, null, 1, 'foo', new \stdClass];
foreach ($values as $value) {
$this->assertInstanceOf(Stack::class, $this->stack->add($value));
}
$this->stack->each(function ($value) use (&$counter, &$values) {
$this->assertSame($values[$counter], $value);
$counter++;
});
$this->assertEquals(\count($values), $counter);
$this->assertEquals(\count($values), $this->stack->count());
}
/**
* @covers \Tarampampam\Tasker\Support\Stack::add
* @covers \Tarampampam\Tasker\Support\Stack::put
* @covers \Tarampampam\Tasker\Support\Stack::keys
* @covers \Tarampampam\Tasker\Support\Stack::values
*
* @return void
*/
public function testKeys()
{
$this->stack->put($key1 = 'foo', $value1 = 'bar');
$this->stack->put($key2 = 'bar', $value2 = 'baz');
$this->stack->add($value3 = 'blah');
$this->stack->put($key4 = 'arr', $value4 = 'lol');
$this->stack->add($value5 = 'kek');
$this->stack->put($key5 = 777, $value6 = 'xxx');
$this->assertEquals([$key1, $key2, 0, $key4, 1, 777], $this->stack->keys());
$this->assertEquals([$value1, $value2, $value3, $value4, $value5, $value6], $this->stack->values());
}
/**
* @covers \Tarampampam\Tasker\Support\Stack::offsetGet
* @covers \Tarampampam\Tasker\Support\Stack::getIterator
* @covers \Tarampampam\Tasker\Support\Stack::offsetSet
* @covers \Tarampampam\Tasker\Support\Stack::offsetExists
* @covers \Tarampampam\Tasker\Support\Stack::offsetUnset
*
* @return void
*/
public function testArrayAccess()
{
$this->stack[$key1 = 'foo'] = $value1 = 'bar';
$this->stack[$key2 = 123] = $value2 = 'baz';
$this->stack[null] = $value3 = 'boom';
$this->stack[] = $value4 = 'kek';
$this->assertSame($value1, $this->stack[$key1]);
$this->assertSame($value2, $this->stack[$key2]);
$this->assertTrue(isset($this->stack[$key1]));
$this->assertFalse(isset($this->stack[$not_exists = 'not exists' . \random_int(0, 2048)]));
$this->stack[$key3 = 'blah'] = 'lol';
unset($this->stack[$key3]);
$this->assertFalse(isset($this->stack[$key3]));
$this->assertCount(4, $this->stack);
$long_keys = $long_values = '';
foreach ($this->stack as $key => $value) {
$long_keys .= $key;
$long_values .= $value;
}
$this->assertSame($key1 . $key2 . ($key2 + 1) . ($key2 + 2), $long_keys);
$this->assertSame($value1 . $value2 . $value3 . $value4, $long_values);
}
}
<file_sep>/tests/AbstractTestCase.php
<?php
namespace Tarampampam\Tasker\Tests;
use Tarampampam\Tasker\Tasker;
use PHPUnit\Framework\TestCase;
use Tarampampam\Tasker\Tests\Mocks\TeskerMock;
/**
* Class AbstractTestCase.
*/
abstract class AbstractTestCase extends TestCase
{
/**
* @var TeskerMock
*/
protected $app;
/**
* {@inheritdoc}
*/
protected function setUp()
{
parent::setUp();
$this->app = $this->applicationFactory();
}
/**
* {@inheritdoc}
*/
protected function tearDown()
{
unset($this->app);
parent::tearDown();
}
/*
* Calls a instance method (public/private/protected) by its name.
*
* @param object $object
* @param string $method_name
* @param array $args
*
* @throws \ReflectionException
*
* @return mixed
*/
public function callMethod($object, string $method_name, array $args = [])
{
$class = new \ReflectionClass($object);
$method = $class->getMethod($method_name);
$method->setAccessible(true);
return $method->invokeArgs($object, $args);
}
/**
* Application instance factory.
*
* @param array ...$arguments
*
* @return TeskerMock
*/
protected function applicationFactory(...$arguments): Tasker
{
return new TeskerMock(...$arguments);
}
/**
* Asserts that passed class uses expected traits.
*
* @param string $class
* @param string|string[] $expected_traits
*
* @return void
*/
protected function assertClassUsesTraits($class, $expected_traits)
{
/**
* Returns all traits used by a trait and its traits.
*
* @param string $trait
*
* @return string[]
*/
$trait_uses_recursive = function ($trait) use (&$trait_uses_recursive) {
$traits = \class_uses($trait);
foreach ($traits as $trait_iterate) {
$traits += $trait_uses_recursive($trait_iterate);
}
return $traits;
};
/**
* Returns all traits used by a class, its subclasses and trait of their traits.
*
* @param object|string $class
*
* @return array
*/
$class_uses_recursive = function ($class) use ($trait_uses_recursive) {
if (\is_object($class)) {
$class = \get_class($class);
}
$results = [];
foreach (\array_reverse(\class_parents($class)) + [$class => $class] as $class_iterate) {
$results += $trait_uses_recursive($class_iterate);
}
return \array_values(\array_unique($results));
};
$uses = $class_uses_recursive($class);
foreach ((array) $expected_traits as $trait_class) {
static::assertContains($trait_class, $uses);
}
}
/*
* Get a instance property (public/private/protected) value.
*
* @param object $object
* @param string $property_name
*
* @throws \ReflectionException
*
* @return mixed
*/
//public function getProperty($object, string $property_name)
//{
// $reflection = new \ReflectionClass($object);
//
// $property = $reflection->getProperty($property_name);
// $property->setAccessible(true);
//
// return $property->getValue($object);
//}
}
<file_sep>/src/Commands/AbstractCommand.php
<?php
declare(strict_types = 1);
namespace Tarampampam\Tasker\Commands;
use LogicException;
use Tarampampam\Tasker\Tasker;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Tarampampam\Tasker\Support\Traits\IOInteractsTrait;
abstract class AbstractCommand extends Command
{
use IOInteractsTrait;
/**
* {@inheritdoc}
*
* @throws LogicException
*
* @return Tasker An Application instance
*/
public function getApplication(): Tasker
{
$app = parent::getApplication();
if ($app instanceof Tasker) {
return $app;
}
// @codeCoverageIgnoreStart
throw new LogicException('Application instance should be ' . Tasker::class);
// @codeCoverageIgnoreEnd
}
/**
* Returns command name.
*
* @return string
*/
abstract public static function getCommandName(): string;
/**
* Returns command description.
*
* @return string
*/
abstract public static function getCommandDescription(): string;
/**
* {@inheritdoc}
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$config = $this->getApplication()->getConfiguration();
if (($config_file = $config->loadedFrom()) !== null) {
$this->verbose($output, "Configuration file location: <comment>{$config_file}</comment>");
}
$this->verbose(
$output, sprintf('Available tasks: [<comment>%s</comment>]', \implode(', ', $config->tasks()->names()))
);
}
/**
* {@inheritdoc}
*/
protected function configure()
{
$this
->setName(static::getCommandName())
->setDescription(static::getCommandDescription());
}
}
<file_sep>/tests/TeskerTest.php
<?php
declare(strict_types = 1);
namespace Tarampampam\Tasker\Tests;
use PackageVersions\Versions;
use Symfony\Component\Console\ConsoleEvents;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Input\InputOption;
use Tarampampam\Tasker\Commands\TaskListCommand;
use Tarampampam\Tasker\Components\Configuration;
use Tarampampam\Tasker\Commands\TaskCheckCommand;
use Tarampampam\Tasker\Commands\TaskExecuteCommand;
use Symfony\Component\Console\Output\BufferedOutput;
use Symfony\Component\Console\Event\ConsoleCommandEvent;
/**
* @covers \Tarampampam\Tasker\Tasker
*/
class TeskerTest extends AbstractTestCase
{
/**
* {@inheritdoc}
*/
protected function setUp()
{
parent::setUp();
\chdir(__DIR__);
}
/**
* @covers \Tarampampam\Tasker\Tasker::getName
*
* @return void
*/
public function testGetName()
{
$this->assertSame('Tasker', $this->app->getName());
}
/**
* @covers \Tarampampam\Tasker\Tasker::getConfiguration
*
* @return void
*/
public function testConfigurationGetter()
{
$this->assertInstanceOf(Configuration::class, $this->app->getConfiguration());
}
/**
* @covers \Tarampampam\Tasker\Tasker::getVersion
*
* @return void
*/
public function testGetVersion()
{
$this->assertSame($version = Versions::getVersion('tarampampam/tasker-php'), $this->app->getVersion(false));
$short = \substr($version, 0, (int) \strpos($version, '@'));
$this->assertSame($short, $this->app->getVersion());
}
/**
* @covers \Tarampampam\Tasker\Tasker::getDefaultInputDefinition
*
* @return void
*/
public function testInputDefinitions()
{
/** @var InputOption $task_name_option */
$config_option = $this->app->getDefinition()->getOption('config');
$this->assertSame('c', $config_option->getShortcut());
$this->assertTrue($config_option->isValueOptional());
/** @var InputOption $working_dir_option */
$working_dir_option = $this->app->getDefinition()->getOption('working-dir');
$this->assertSame('d', $working_dir_option->getShortcut());
$this->assertTrue($working_dir_option->isValueOptional());
}
/**
* @covers \Tarampampam\Tasker\Tasker::getDefaultCommands
*
* @return void
*/
public function testCommands()
{
$commands = $this->app->all();
$expects = [
'task:list' => TaskListCommand::class,
'task:exec' => TaskExecuteCommand::class,
'task:check' => TaskCheckCommand::class,
];
foreach ($expects as $signature => $class_name) {
$this->assertArrayHasKey($signature, $commands);
$this->assertInstanceOf($class_name, $commands[$signature]);
}
}
/**
* @covers \Tarampampam\Tasker\Tasker::initEvents
*
* @return void
*/
public function testWorkingDirGlobalEventListener()
{
// At first - make a change
\chdir($start_dir = \realpath(\sys_get_temp_dir()));
$this->assertEquals(\getcwd(), $start_dir);
// Dispatch event
$this->dispatchCommandEvent(['--working-dir' => $new_working_dir = __DIR__]);
// And assert that new "getcwd" equals passed in argument
$this->assertEquals(\getcwd(), $new_working_dir);
}
/**
* @covers \Tarampampam\Tasker\Tasker::initEvents
*
* @return void
*/
public function testLoadingConfigFileUsingPassedOption()
{
$this->assertNull($this->app->getConfiguration()->loadedFrom());
$this->dispatchCommandEvent(['--config' => $path = __DIR__ . '/Stubs/samples/configs/valid_configuration.php']);
$this->assertSame($path, $this->app->getConfiguration()->loadedFrom());
}
/**
* @covers \Tarampampam\Tasker\Tasker::initEvents
*
* @return void
*/
public function testLoadingDefaultConfigFileWithDistExtension()
{
\chdir($path = __DIR__ . '/Stubs/samples/configs/with_dist');
$this->assertNull($this->app->getConfiguration()->loadedFrom());
$this->dispatchCommandEvent();
$this->assertSame($path . '/.tasker.php.dist', $this->app->getConfiguration()->loadedFrom());
}
/**
* @covers \Tarampampam\Tasker\Tasker::initEvents
*
* @return void
*/
public function testLoadingDefaultConfigFile()
{
\chdir($path = __DIR__ . '/Stubs/samples/configs/with_dist_and_default');
$this->assertNull($this->app->getConfiguration()->loadedFrom());
$this->dispatchCommandEvent();
$this->assertSame($path . '/.tasker.php', $this->app->getConfiguration()->loadedFrom());
}
/**
* @param string[] $command_arguments
* @param string $command_name
*
* @return void
*/
protected function dispatchCommandEvent(array $command_arguments = [], string $command_name = 'list')
{
/** @var Command $command */
$command = $this->app->find($command_name);
$dispatcher = $this->app->_eventsDispatcher();
$input = new ArrayInput(
\array_merge(['command' => $command->getName()], $command_arguments),
$this->app->_getDefaultInputDefinition()
);
$dispatcher->dispatch(
ConsoleEvents::COMMAND,
new ConsoleCommandEvent($command, $input, $output = new BufferedOutput)
);
}
}
<file_sep>/tests/Stubs/samples/configs/with_dist_and_default/.tasker.php
<?php
use Tarampampam\Tasker\Components\TasksStack;
return TasksStack::make()
->addAction($task_name = 'foo', function () {
return 'ok';
})
->addCheck($task_name, function () {
return 'ok';
})
->setDescription($task_name, 'foo description');
<file_sep>/tests/Commands/TaskExecuteCommandTest.php
<?php
declare(strict_types = 1);
namespace Tarampampam\Tasker\Tests\Commands;
use Symfony\Component\Console\Tester\CommandTester;
use Tarampampam\Tasker\Commands\TaskExecuteCommand;
/**
* @covers \Tarampampam\Tasker\Commands\TaskExecuteCommand
*/
class TaskExecuteCommandTest extends AbstractRunCommandTestCase
{
/**
* {@inheritdoc}
*/
public function expectedCommandName(): string
{
return 'task:exec';
}
/**
* {@inheritdoc}
*/
public function expectedCommandDescription(): string
{
return 'tasks';
}
/**
* @return TaskExecuteCommand
*/
public function commandFactory()
{
return new TaskExecuteCommand;
}
/**
* @covers \Tarampampam\Tasker\Commands\TaskExecuteCommand::execute
*
* @return void
*/
public function testExecutionWithoutPassingAnyTasks()
{
$first_executed = false;
$second_executed = false;
$this->app->getConfiguration()->tasks()
->addAction('foo', function () use (&$first_executed) {
$first_executed = true;
})
->addAction('bar', function () use (&$second_executed) {
$second_executed = true;
});
$tester = new CommandTester($this->command);
$this->assertSame(0, $tester->execute([]));
$this->assertTrue($first_executed);
$this->assertTrue($second_executed);
}
/**
* @covers \Tarampampam\Tasker\Commands\TaskExecuteCommand::execute
*
* @return void
*/
public function testExecutionWithPassingOneTaskName()
{
$first_executed = false;
$second_executed = false;
$this->app->getConfiguration()->tasks()
->addAction($task_name = 'foo', function () use (&$first_executed) {
$first_executed = true;
})
->addAction('bar', function () use (&$second_executed) {
$second_executed = true;
});
$tester = new CommandTester($this->command);
$this->assertSame(0, $tester->execute([
'--' . $this->command::TASK_NAME_OPTION_NAME => $task_name,
]));
$this->assertTrue($first_executed);
$this->assertFalse($second_executed);
}
/**
* @covers \Tarampampam\Tasker\Commands\TaskExecuteCommand::execute
*
* @return void
*/
public function testExecutionWithPassingMultipleTaskNames()
{
$first_executed = false;
$second_executed = false;
$this->app->getConfiguration()->tasks()
->addAction($first_task_name = 'foo', function () use (&$first_executed) {
$first_executed = true;
})
->addAction($second_task_name = 'bar', function () use (&$second_executed) {
$second_executed = true;
});
$tester = new CommandTester($this->command);
$this->assertSame(0, $tester->execute([
'--' . $this->command::TASK_NAME_OPTION_NAME => [$first_task_name, $second_task_name],
]));
$this->assertTrue($first_executed);
$this->assertTrue($second_executed);
}
/**
* @covers \Tarampampam\Tasker\Commands\TaskExecuteCommand::execute
*
* @return void
*/
public function testExecutionWithErrors()
{
$first_executed = false;
$second_executed = false;
$this->app->getConfiguration()->tasks()
->addAction($first_task_name = 'foo', function () use (&$first_executed) {
$first_executed = true;
return false;
})
->addAction($second_task_name = 'bar', function () use (&$second_executed) {
$second_executed = true;
return false;
});
$tester = new CommandTester($this->command);
$this->assertSame(1, $tester->execute([
'--' . $this->command::TASK_NAME_OPTION_NAME => [$first_task_name, $second_task_name],
]));
$this->assertTrue($first_executed);
$this->assertTrue($second_executed);
}
/**
* @covers \Tarampampam\Tasker\Commands\TaskExecuteCommand::execute
*
* @return void
*/
public function testExecutionWithInvalidTaskName()
{
$this->expectException(\InvalidArgumentException::class);
$tester = new CommandTester($this->command);
$tester->execute([
'--' . $this->command::TASK_NAME_OPTION_NAME => 'foo',
]);
}
}
<file_sep>/src/Components/TaskInterface.php
<?php
namespace Tarampampam\Tasker\Components;
use Tarampampam\Tasker\Support\StackInterface;
interface TaskInterface
{
/**
* Get actions stack.
*
* @return StackInterface
*/
public function actions(): StackInterface;
/**
* Add action into stack.
*
* @param callable $action
*
* @return self
*/
public function addAction(callable $action);
/**
* Get default actions.
*
* @return callable[]
*/
public function defaultActions(): array;
/**
* Get checks stack.
*
* @return StackInterface
*/
public function checks(): StackInterface;
/**
* Add check into stack.
*
* @param callable $check
*
* @return self
*/
public function addCheck(callable $check);
/**
* Get default checks.
*
* @return callable[]
*/
public function defaultChecks(): array;
/**
* Get stack description.
*
* @return null|string
*/
public function description();
/**
* Set stack description.
*
* @param string $description
*
* @return self
*/
public function setDescription(string $description);
/**
* Get default description.
*
* @return string|null
*/
public function defaultDescription();
}
<file_sep>/README.md
<p align="center">
<img alt="logo" src="https://hsto.org/webt/0v/qb/0p/0vqb0pp6ntyyd8mbdkkj0wsllwo.png" width="70" height="70" />
</p>
# PHP Tasker
[![Version][badge_packagist_version]][link_packagist]
[![Version][badge_php_version]][link_packagist]
[![Build Status][badge_build_status]][link_build_status]
[![Coverage][badge_coverage]][link_coverage]
[![Downloads count][badge_downloads_count]][link_packagist]
[![License][badge_license]][link_license]
Using this package you can declare _named tasks_. All tasks includes two entities:
- **Action** - plain PHP-code for execution (like files creating, external applications running and others);
- **Checks** - plain PHP-code for checking some actions (like php-extensions existing, database connections, etc).
For example, you may want to run database migraion **only** if this operation is required _(database is not migrated)_. So, you need in _check_ for this, and _action_ with command for running database migration. Just create file `.tasker.php` in root directory of your application with these instructions and execute:
```bash
./vendor/bin/tasker task:check && ./vendor/bin/tasker task:exec
```
For more examples - look into "usage" section of this file.
## Install
Require this package with composer using the following command:
```bash
$ composer require tarampampam/tasker-php "^1.0"
```
> Installed `composer` is required ([how to install composer][getcomposer]).
> You need to fix the major version of package.
### Usage <sup>ru</sup>
Данный пакет может вами использоваться для реализации следующих
#### Настройка
Для их описания используется конфигурационный файл с именем `.tasker.php` в **текущей** директории (или `.tasker.php.dist`, если `.tasker.php` не был обнаружен), или явно указывается с помощью опции `--config`.
Конфигурационный файл должен возвращать объект класса `\Tarampampam\Tasker\Components\TasksStack`, содержащий инструкции действий и их проверок ("Tasks").
Пример конфигурационного файла:
```php
<?php // File: ./.tasker.php
use Tarampampam\Tasker\Components\Task;
use Tarampampam\Tasker\Components\TasksStack;
$lock_file = __DIR__ . '/lock.file';
return TasksStack::make()
->addTask(
'lock_file',
Task::make()
->addAction(function () use ($lock_file) {
if (\is_file($lock_file)) {
\unlink($lock_file);
}
})
->addAction(function () use ($lock_file): bool {
return \file_put_contents($lock_file, 'Locked at: ' . (new DateTime)->getTimestamp()) > 0;
})
->addCheck(function () use ($lock_file) {
if (! \is_file($lock_file)) {
throw new \Exception("File [{$lock_file}] was not found");
}
})
->setDescription('Make lock-file')
);
```
Который "умеет" как проверку наличия _некоторого_ lock-файла, так и метод его создания.
> **Внимание:** Любые исключения, сгенерированные действиями или проверками корректно обрабатываются
#### Запуск действия и его проверки
Давайте рассмотрим пример использования данной конфигурации. Для начала выведем таблицу всех доступных "задач" (task-ов):
```bash
./vendor/bin/tasker task:list
+-----------+---------------+--------------+----------------+
| Task name | Actions count | Checks count | Description |
+-----------+---------------+--------------+----------------+
| lock_file | 2 | 1 | Make lock-file |
+-----------+---------------+--------------+----------------+
```
Так как мы описали только одну "задачу" - именно её и наблюдаем в выводе.
Теперь проверим наличие "lock"-файла с помощью описанной нами проверки:
```bash
./vendor/bin/tasker task:check -t lock_file
INFO: Tasks for a work: [lock_file]
Status: Functions execution completed with errors (1)
1/1 [▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓] 100%
ERROR: File [./lock.file] was not found (./.tasker.php:27)
```
Так как проверка задачи с именем `lock_file` завершилась ошибкой (файл не существует), код выхода равен `1`.
> **Внимание:** Возвращение из `closure` как _действия_, так и _проверки_ значения `false` трактуется как ошибка.
Теперь выполним **действие**, которое создает "lock"-файл:
```bash
./vendor/bin/tasker task:exec -t lock_file
INFO: Tasks for a work: [lock_file]
Status: Functions execution completed successful
2/2 [▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓] 100%
```
Так как оба действия (удаление существующего lock-файла при его наличии и запись нового) выполнились успешно - код выхода равен `0` (без ошибок). Выполняем повторную проверку:
```bash
./vendor/bin/tasker task:check -t lock_file
INFO: Tasks for a work: [lock_file]
Status: Functions execution completed successful
1/1 [▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓] 100%
```
Теперь проверка выполнена успешно, и код выхода соответственно равен `0`.
#### Дополнительные опции запуска проверок
При запуске проверок вы можете использовать следующие опции:
Опция | Описание
--------- | --------
`--loop` | Выполнение проверок в цикле (по умолчанию - бесконечном)
`--delay` | Задержка (в секундах) между итерациями цикла
`--limit` | Ограничение количества итераций цикла (используя опция `--loop`)
### Testing
For package testing we use `phpunit` framework. Just write into your terminal:
```bash
$ git clone <EMAIL>:tarampampam/tasker-php.git ./tasker-php && cd $_
$ make test
```
## Changes log
[![Release date][badge_release_date]][link_releases]
[![Commits since latest release][badge_commits_since_release]][link_commits]
Changes log can be [found here][link_changes_log].
## Support
[![Issues][badge_issues]][link_issues]
[![Issues][badge_pulls]][link_pulls]
If you will find any package errors, please, [make an issue][link_create_issue] in current repository.
## License
This is open-sourced software licensed under the [MIT License][link_license].
[badge_packagist_version]:https://img.shields.io/packagist/v/tarampampam/tasker-php.svg?maxAge=180
[badge_php_version]:https://img.shields.io/packagist/php-v/tarampampam/tasker-php.svg?longCache=true
[badge_build_status]:https://travis-ci.com/tarampampam/tasker-php.svg?branch=master
[badge_coverage]:https://img.shields.io/codecov/c/github/tarampampam/tasker-php/master.svg?maxAge=15
[badge_downloads_count]:https://img.shields.io/packagist/dt/tarampampam/tasker-php.svg?maxAge=180
[badge_license]:https://img.shields.io/packagist/l/tarampampam/tasker-php.svg?longCache=true
[badge_release_date]:https://img.shields.io/github/release-date/tarampampam/tasker-php.svg?maxAge=180
[badge_commits_since_release]:https://img.shields.io/github/commits-since/tarampampam/tasker-php/latest.svg?maxAge=180
[badge_issues]:https://img.shields.io/github/issues/tarampampam/tasker-php.svg?maxAge=180
[badge_pulls]:https://img.shields.io/github/issues-pr/tarampampam/tasker-php.svg?maxAge=180
[link_releases]:https://github.com/tarampampam/tasker-php/releases
[link_packagist]:https://packagist.org/packages/tarampampam/tasker-php
[link_build_status]:https://travis-ci.com/tarampampam/tasker-php/branches
[link_coverage]:https://codecov.io/gh/tarampampam/tasker-php
[link_changes_log]:https://github.com/tarampampam/tasker-php/blob/master/CHANGELOG.md
[link_issues]:https://github.com/tarampampam/tasker-php/issues
[link_create_issue]:https://github.com/tarampampam/tasker-php/issues/new/choose
[link_commits]:https://github.com/tarampampam/tasker-php/commits
[link_pulls]:https://github.com/tarampampam/tasker-php/pulls
[link_license]:https://github.com/tarampampam/tasker-php/blob/master/LICENSE
[getcomposer]:https://getcomposer.org/download/
<file_sep>/src/Exceptions/MissingConfigurationException.php
<?php
declare(strict_types = 1);
namespace Tarampampam\Tasker\Exceptions;
use LogicException;
use Symfony\Component\Console\Exception\ExceptionInterface;
class MissingConfigurationException extends LogicException implements ExceptionInterface
{
//
}
<file_sep>/tests/Commands/AbstractCommandTestCase.php
<?php
declare(strict_types = 1);
namespace Tarampampam\Tasker\Tests\Commands;
use Tarampampam\Tasker\Tasker;
use Symfony\Component\Console\Command\Command;
use Tarampampam\Tasker\Tests\AbstractTestCase;
use Tarampampam\Tasker\Commands\AbstractCommand;
use Symfony\Component\Console\Tester\CommandTester;
use Symfony\Component\Console\Output\OutputInterface;
/**
* @cover \Tarampampam\Tasker\Commands\AbstractCommand
*/
abstract class AbstractCommandTestCase extends AbstractTestCase
{
/**
* @var AbstractCommand
*/
protected $command;
/**
* {@inheritdoc}
*/
protected function setUp()
{
parent::setUp();
$this->command = $this->commandFactory();
$this->command->setApplication($this->app);
}
/**
* {@inheritdoc}
*/
protected function tearDown()
{
unset($this->command);
parent::tearDown();
}
/**
* @covers \Tarampampam\Tasker\Commands\AbstractCommand::getApplication
*
* @return void
*/
public function testAppGetter()
{
$this->assertInstanceOf(Tasker::class, $this->command->getApplication());
}
/**
* @covers \Tarampampam\Tasker\Commands\AbstractCommand::configure
*
* @return void
*/
public function testAbstractConfigure()
{
$this->assertSame($this->command::getCommandName(), $this->command->getName());
$this->assertSame($this->command::getCommandDescription(), $this->command->getDescription());
}
/**
* @covers \Tarampampam\Tasker\Commands\AbstractCommand::execute
*
* @return void
*/
public function testSharedExecuteCode()
{
$this->loadConfigFrom($path = __DIR__ . '/../Stubs/samples/configs/valid_configuration.php');
$tester = new CommandTester($this->command);
$tester->execute([], ['verbosity' => OutputInterface::VERBOSITY_DEBUG]);
$this->assertContains($path, $tester->getDisplay());
$this->assertRegExp('~Available tasks.+\[.+\]~i', $tester->getDisplay());
}
/**
* Get expected command name.
*
* @return string
*/
abstract public function expectedCommandName(): string;
/**
* Get expected command description.
*
* @return string
*/
abstract public function expectedCommandDescription(): string;
/**
* @return Command
*/
abstract public function commandFactory();
/**
* @covers \Tarampampam\Tasker\Commands\TaskListCommand::getCommandName
*
* @return void
*/
public function testGetCommandName()
{
$this->assertSame($this->expectedCommandName(), $this->command::getCommandName());
}
/**
* @covers \Tarampampam\Tasker\Commands\TaskListCommand::getDescription
*
* @return void
*/
public function testGetCommandDescription()
{
$this->assertContains($this->expectedCommandDescription(), $this->command::getCommandDescription());
}
/**
* Load app configuration from file.
*
* @param string $file_path
*/
protected function loadConfigFrom(string $file_path)
{
$this->app->getConfiguration()->loadFrom($file_path);
}
}
<file_sep>/tests/Support/Traits/IOInteractsTraitTest.php
<?php
declare(strict_types = 1);
namespace Tarampampam\Tasker\Tests\Support\Traits;
use Tarampampam\Tasker\Tests\AbstractTestCase;
use Symfony\Component\Console\Output\NullOutput;
use Symfony\Component\Console\Helper\ProgressBar;
use Symfony\Component\Console\Output\ConsoleOutput;
use Symfony\Component\Console\Output\BufferedOutput;
use Symfony\Component\Console\Output\OutputInterface;
use Tarampampam\Tasker\Support\Traits\IOInteractsTrait;
/**
* @covers \Tarampampam\Tasker\Support\Traits\IOInteractsTrait
*/
class IOInteractsTraitTest extends AbstractTestCase
{
use IOInteractsTrait;
/**
* @covers \Tarampampam\Tasker\Support\Traits\IOInteractsTrait::customizeProgressBar
*
* @return void
*/
public function testCustomizeProgressBar()
{
$progress_bar = new ProgressBar($output = new NullOutput);
$progress_bar = $this->customizeProgressBar($progress_bar, $message = 'foo bar', $size = 30);
$this->assertSame('░', $progress_bar->getEmptyBarCharacter());
$this->assertSame('▓', $progress_bar->getProgressCharacter());
$this->assertSame($size, $progress_bar->getBarWidth());
$this->assertSame($message, $progress_bar->getMessage('status'));
}
/**
* @covers \Tarampampam\Tasker\Support\Traits\IOInteractsTrait::setProgressBarStatus
*
* @return void
*/
public function testSetProgressBarStatus()
{
$progress_bar = new ProgressBar($output = new NullOutput);
$this->setProgressBarStatus($progress_bar, $message = 'foo bar');
$this->assertSame($message, $progress_bar->getMessage('status'));
}
/**
* @covers \Tarampampam\Tasker\Support\Traits\IOInteractsTrait::error
*
* @return void
*/
public function testError()
{
$this->error($output = new BufferedOutput, [$first = 'foo bar', $second = 'bar baz']);
$buffer = \explode("\n", $output->fetch());
$this->assertContains($prefix = 'err', $buffer[0], $err_message = 'Prefix was not found', true);
$this->assertStringEndsWith($first, $buffer[0]);
$this->assertContains($prefix, $buffer[1], $err_message, true);
$this->assertStringEndsWith($second, $buffer[1]);
$this->assertEmpty($buffer[2]); // New line at the end of output
}
/**
* @covers \Tarampampam\Tasker\Support\Traits\IOInteractsTrait::error
*
* @return void
*/
public function testErrorStdErr()
{
$this->error($output = new class extends ConsoleOutput {
public $output;
public function getErrorOutput()
{
static $output;
return $output instanceof BufferedOutput
? $output
: $output = new BufferedOutput;
}
}, $message = 'foo foo');
$this->assertContains($message, $output->getErrorOutput()->fetch());
}
/**
* @covers \Tarampampam\Tasker\Support\Traits\IOInteractsTrait::log
*
* @return void
*/
public function testLog()
{
$output = new BufferedOutput;
$this->log($output, [$first = 'foo bar', $second = 'bar baz']);
$buffer = \explode("\n", $output->fetch());
$this->assertStringEndsWith($first, $buffer[0]);
$this->assertStringEndsWith($second, $buffer[1]);
$this->assertEmpty($buffer[2]); // New line at the end of output
}
/**
* @covers \Tarampampam\Tasker\Support\Traits\IOInteractsTrait::verbose
*
* @return void
*/
public function testVerbose()
{
$output = new BufferedOutput(OutputInterface::VERBOSITY_VERBOSE);
$this->verbose($output, [$first = 'foo bar', $second = 'bar baz']);
$buffer = \explode("\n", $output->fetch());
$this->assertContains($prefix = 'log', $buffer[0], $err_message = 'Prefix was not found', true);
$this->assertStringEndsWith($first, $buffer[0]);
$this->assertContains($prefix, $buffer[1], $err_message, true);
$this->assertStringEndsWith($second, $buffer[1]);
$this->assertEmpty($buffer[2]); // New line at the end of output
}
/**
* @covers \Tarampampam\Tasker\Support\Traits\IOInteractsTrait::debug
*
* @return void
*/
public function testDebug()
{
$output = new BufferedOutput(OutputInterface::VERBOSITY_DEBUG);
$this->debug($output, [$first = 'foo bar', $second = 'bar baz']);
$buffer = \explode("\n", $output->fetch());
$this->assertContains($prefix = 'debug', $buffer[0], $err_message = 'Prefix was not found', true);
$this->assertStringEndsWith($first, $buffer[0]);
$this->assertContains($prefix, $buffer[1], $err_message, true);
$this->assertStringEndsWith($second, $buffer[1]);
$this->assertEmpty($buffer[2]); // New line at the end of output
}
}
<file_sep>/tests/Components/TaskTest.php
<?php
declare(strict_types = 1);
namespace Tarampampam\Tasker\Tests\Components;
use Tarampampam\Tasker\Components\Task;
use Tarampampam\Tasker\Tests\AbstractTestCase;
/**
* @covers \Tarampampam\Tasker\Components\Task
*/
class TaskTest extends AbstractTestCase
{
/**
* @var Task
*/
protected $task;
/**
* {@inheritdoc}
*/
protected function setUp()
{
parent::setUp();
$this->task = new Task;
}
/**
* {@inheritdoc}
*/
protected function tearDown()
{
unset($this->task);
parent::tearDown();
}
/**
* @covers \Tarampampam\Tasker\Components\Task::__construct
* @covers \Tarampampam\Tasker\Components\Task::actions
* @covers \Tarampampam\Tasker\Components\Task::checks
* @covers \Tarampampam\Tasker\Components\Task::description
*
* @return void
*/
public function testConstructor()
{
$this->assertEmpty($this->task->actions());
$this->assertEmpty($this->task->checks());
$this->assertNull($this->task->description());
$this->task = new Task(
$actions = [function () {
return 'foo';
}],
$checks = [function () {
return 'bar';
}],
$description = 'foo bar'
);
$this->assertEquals($actions, $this->task->actions()->values());
$this->assertEquals($checks, $this->task->checks()->values());
$this->assertEquals($description, $this->task->description());
}
/**
* @covers \Tarampampam\Tasker\Components\Task::defaultDescription
* @covers \Tarampampam\Tasker\Components\Task::defaultActions
* @covers \Tarampampam\Tasker\Components\Task::defaultChecks
*
* @return void
*/
public function testDefaultGetters()
{
$this->assertEmpty($this->task->defaultActions());
$this->assertEmpty($this->task->defaultDescription());
$this->assertNull($this->task->defaultDescription());
}
/**
* @covers \Tarampampam\Tasker\Components\Task::addAction
* @covers \Tarampampam\Tasker\Components\Task::actions
* @covers \Tarampampam\Tasker\Components\Task::addCheck
* @covers \Tarampampam\Tasker\Components\Task::checks
* @covers \Tarampampam\Tasker\Components\Task::setDescription
* @covers \Tarampampam\Tasker\Components\Task::description
*
* @return void
*/
public function testSetters()
{
$this->assertInstanceOf(Task::class, $this->task->addAction($action = function () {
return 'foo';
}));
$this->assertEquals([$action], $this->task->actions()->all());
$this->assertInstanceOf(Task::class, $this->task->addCheck($check = function () {
return 'foo';
}));
$this->assertEquals([$check], $this->task->checks()->all());
$this->assertInstanceOf(Task::class, $this->task->setDescription($description = 'foo bar'));
$this->assertEquals($description, $this->task->description());
}
}
<file_sep>/tests/Mocks/TeskerMock.php
<?php
declare(strict_types = 1);
namespace Tarampampam\Tasker\Tests\Mocks;
use Tarampampam\Tasker\Tasker;
use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
class TeskerMock extends Tasker
{
public function _eventsDispatcher(): EventDispatcherInterface
{
return $this->events_dispatcher;
}
public function _getDefaultInputDefinition(): InputDefinition
{
return parent::getDefaultInputDefinition();
}
}
<file_sep>/tests/Commands/TaskListCommandTest.php
<?php
declare(strict_types = 1);
namespace Tarampampam\Tasker\Tests\Commands;
use Tarampampam\Tasker\Components\Task;
use Tarampampam\Tasker\Commands\TaskListCommand;
use Symfony\Component\Console\Tester\CommandTester;
/**
* @covers \Tarampampam\Tasker\Commands\TaskListCommand
*/
class TaskListCommandTest extends AbstractCommandTestCase
{
/**
* {@inheritdoc}
*/
public function expectedCommandName(): string
{
return 'task:list';
}
/**
* {@inheritdoc}
*/
public function expectedCommandDescription(): string
{
return 'Show all available tasks in table view';
}
/**
* @return TaskListCommand
*/
public function commandFactory()
{
return new TaskListCommand();
}
/**
* @covers \Tarampampam\Tasker\Commands\TaskListCommand::execute
*
* @return void
*/
public function testWithEmptyConfig()
{
$this->loadConfigFrom($path = __DIR__ . '/../Stubs/samples/configs/empty.php');
$tester = new CommandTester($this->command);
$tester->execute([]);
$this->assertRegExp('~Tasks was not found~i', $tester->getDisplay());
}
/**
* @covers \Tarampampam\Tasker\Commands\TaskListCommand::execute
*
* @return void
*/
public function testWithNonEmptyConfig()
{
$this->loadConfigFrom($path = __DIR__ . '/../Stubs/samples/configs/valid_configuration.php');
$tasks = $this->app->getConfiguration()->tasks();
$tester = new CommandTester($this->command);
$tester->execute([]);
$this->assertGreaterThan(0, $tasks->count());
foreach ($tasks as $name => $task) {
if ((($actions_count = $task->actions()->count()) + ($check_count = $task->checks()->count())) > 0) {
/* @var Task $task */
$this->assertRegExp(
"~{$name}.*\|.*{$actions_count}.*\|.*{$check_count}.*\|.*{$task->description()}~i",
$tester->getDisplay()
);
}
}
}
}
<file_sep>/src/Tasker.php
<?php
declare(strict_types = 1);
namespace Tarampampam\Tasker;
use PackageVersions\Versions;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\ConsoleEvents;
use Symfony\Component\Console\Input\InputOption;
use Tarampampam\Tasker\Components\Configuration;
use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\Console\Event\ConsoleCommandEvent;
class Tasker extends Application
{
/**
* @var EventDispatcher
*/
protected $events_dispatcher;
/**
* @var Configuration
*/
protected $configuration;
/**
* Tasker constructor.
*
* @param string $name
* @param string $version
*/
public function __construct(string $name = 'UNKNOWN', string $version = 'UNKNOWN')
{
parent::__construct($name, $version);
$this->configuration = new Configuration;
$this->setDispatcher($this->events_dispatcher = new EventDispatcher);
$this->initEvents();
}
/**
* {@inheritdoc}
*/
public function getName(): string
{
return 'Tasker';
}
/**
* Get the application configuration.
*
* @return Configuration
*/
public function getConfiguration(): Configuration
{
return $this->configuration;
}
/**
* {@inheritdoc}
*
* @param bool $without_hash
*/
public function getVersion(bool $without_hash = true): string
{
$version = Versions::getVersion('tarampampam/tasker-php');
if ($without_hash === true && \is_int($delimiter_position = \strpos($version, '@'))) {
return \substr($version, 0, (int) $delimiter_position);
}
return $version;
}
/**
* Make listeners initialization.
*
* @see https://symfony.com/doc/current/components/console/events.html
*
* @return void
*/
protected function initEvents()
{
// Change current working directory if needed
$this->events_dispatcher->addListener(ConsoleEvents::COMMAND, function (ConsoleCommandEvent $event) {
if ($event->getInput()->hasOption($option_name = 'working-dir')) {
$passed_working_dir = $event->getInput()->getOption($option_name);
if (\is_string($passed_working_dir) && \is_dir($passed_working_dir) && $passed_working_dir !== \getcwd()) {
$event->getOutput()->writeln(
"<comment>Current working directory changed to [{$passed_working_dir}]</comment>",
OutputInterface::VERBOSITY_VERBOSE
);
\chdir($passed_working_dir);
}
}
});
// Auto-loading configuration from file
$this->events_dispatcher->addListener(ConsoleEvents::COMMAND, function (ConsoleCommandEvent $event) {
$passed_config_file_path = $event->getInput()->hasOption($option_name = 'config')
? $event->getInput()->getOption($option_name)
: null;
// Try to load passed config file
if (\is_string($passed_config_file_path) && $passed_config_file_path !== '') {
$this->configuration->loadFrom($passed_config_file_path);
} else {
// Otherwise - try to find config file in current directory
$defaults = [
$default_path = \getcwd() . DIRECTORY_SEPARATOR . Configuration::DEFAULT_CONFIG_FILE_NAME,
$default_path . '.dist',
];
foreach ($defaults as $default_file_path) {
if (\is_file($default_file_path)) {
$this->configuration->loadFrom($default_file_path);
break;
}
}
}
});
}
/**
* {@inheritdoc}
*/
protected function getDefaultCommands(): array
{
return \array_merge(parent::getDefaultCommands(), [
new Commands\TaskListCommand,
new Commands\TaskExecuteCommand,
new Commands\TaskCheckCommand,
]);
}
/**
* {@inheritdoc}
*/
protected function getDefaultInputDefinition(): InputDefinition
{
$definition = parent::getDefaultInputDefinition();
$definition->addOptions([
new InputOption(
'config',
'c',
InputOption::VALUE_OPTIONAL,
'Custom configuration file path'
),
new InputOption(
'working-dir',
'd',
InputOption::VALUE_OPTIONAL,
'If specified, use the given directory as working directory'
),
]);
return $definition;
}
}
<file_sep>/tests/Tasks/Traits/ExecProcessesTraitTest.php
<?php
declare(strict_types = 1);
namespace Tarampampam\Tasker\Tests\Tasks\Traits;
use Symfony\Component\Process\Process;
use Tarampampam\Tasker\Tests\AbstractTestCase;
use Tarampampam\Tasker\Tasks\Traits\ExecProcessesTrait;
/**
* @covers \Tarampampam\Tasker\Tasks\Traits\ExecProcessesTrait
*/
class ExecProcessesTraitTest extends AbstractTestCase
{
use ExecProcessesTrait;
/**
* {@inheritdoc}
*/
protected function tearDown()
{
\chdir(__DIR__ . '/..');
parent::tearDown();
}
/**
* @covers \Tarampampam\Tasker\Tasks\Traits\ExecProcessesTrait::getWorkingDirectoryPath
*
* @return void
*/
public function testGetWorkingDirectoryPath()
{
\chdir($temp_dir = \realpath(\sys_get_temp_dir()));
$this->assertSame($temp_dir, \getcwd());
\chdir($current_dir = __DIR__);
$this->assertSame($current_dir, $this->getWorkingDirectoryPath());
}
/**
* @covers \Tarampampam\Tasker\Tasks\Traits\ExecProcessesTrait::getArtisanLocation
*
* @return void
*/
public function testGetArtisanLocation()
{
$this->assertSame(
$this->getWorkingDirectoryPath() . DIRECTORY_SEPARATOR . 'artisan',
$this->getArtisanLocation()
);
}
/**
* @covers \Tarampampam\Tasker\Tasks\Traits\ExecProcessesTrait::execProcess
*
* @return void
*/
public function testExecProcessWithoutError()
{
$stdout = $stderr = [];
$process = $this->execProcess([PHP_BINARY, '-v'], $stdout, $stderr, 2);
$this->assertInstanceOf(Process::class, $process);
foreach (['php', 'copyright', 'zend'] as $expected_substring) {
$this->assertContains($expected_substring, \implode('', $stdout), 'Stdout fuck up', true);
}
$this->assertEmpty($stderr);
}
/**
* @covers \Tarampampam\Tasker\Tasks\Traits\ExecProcessesTrait::execProcess
*
* @return void
*/
public function testExecProcessWithError()
{
$stdout = $stderr = [];
$stdout_msg = 'To stdout ' . \random_int(1, 999);
$stderr_msg = 'To stderr ' . \random_int(1, 999);
$exit_code = \random_int(2, 22);
$process = $this->execProcess([
PHP_BINARY,
'-r',
'echo("' . $stdout_msg . '\n1\n2\n3\n4");' .
'fwrite(STDERR, "' . $stderr_msg . '\n1\n2\n3\n4"); ' .
'exit(' . $exit_code . ');',
], $stdout, $stderr, 2);
$this->assertContains($stdout_msg, \implode('', $stdout));
$this->assertSame('1', $stdout[1]);
$this->assertSame('2', $stdout[2]);
$this->assertSame('3', $stdout[3]);
$this->assertSame('4', $stdout[4]);
$this->assertContains($stderr_msg, \implode('', $stderr));
$this->assertSame('1', $stderr[1]);
$this->assertSame('2', $stderr[2]);
$this->assertSame('3', $stderr[3]);
$this->assertSame('4', $stderr[4]);
$this->assertSame($exit_code, $process->getExitCode());
}
/**
* @covers \Tarampampam\Tasker\Tasks\Traits\ExecProcessesTrait::execArtisan
*
* @return void
*/
public function testExecArtisan()
{
$mock = new class {
use ExecProcessesTrait {
ExecProcessesTrait::execArtisan as public;
}
// Override artisan command caller with "inline" php-command
protected function getArtisanLocation(): string
{
return '-r';
}
};
$stdout = $stderr = [];
$this->assertEquals(
$expected = \random_int(1, 10),
$mock->execArtisan(['exit(' . $expected . ');'], $stdout, $stderr)->getExitCode()
);
}
}
<file_sep>/tests/Components/TasksStackTest.php
<?php
declare(strict_types = 1);
namespace Tarampampam\Tasker\Tests\Components;
use Tarampampam\Tasker\Components\Task;
use Tarampampam\Tasker\Components\TasksStack;
use Tarampampam\Tasker\Tests\AbstractTestCase;
/**
* @covers \Tarampampam\Tasker\Components\TasksStack
*/
class TasksStackTest extends AbstractTestCase
{
/**
* @var TasksStack
*/
protected $instance;
/**
* {@inheritdoc}
*/
protected function setUp()
{
parent::setUp();
$this->instance = new TasksStack;
}
/**
* {@inheritdoc}
*/
protected function tearDown()
{
unset($this->instance);
parent::tearDown();
}
/**
* @covers \Tarampampam\Tasker\Components\TasksStack::all
* @covers \Tarampampam\Tasker\Components\TasksStack::count
* @covers \Tarampampam\Tasker\Components\TasksStack::setTask
* @covers \Tarampampam\Tasker\Components\TasksStack::exists
* @covers \Tarampampam\Tasker\Components\TasksStack::getTask
* @covers \Tarampampam\Tasker\Components\TasksStack::names
*
* @return void
*/
public function testBasicGetters()
{
$this->assertEmpty($this->instance->all());
$this->assertCount(0, $this->instance);
$this->assertSame(0, $this->instance->count());
$this->instance->setTask($task_name = 'foobar', $task = new Task());
$this->assertCount(1, $this->instance);
$this->assertTrue($this->instance->exists($task_name));
$this->assertEquals($task, $this->instance->getTask($task_name));
$this->assertEquals([$task_name], $this->instance->names());
}
/**
* @covers \Tarampampam\Tasker\Components\TasksStack::addAction
* @covers \Tarampampam\Tasker\Components\TasksStack::addTask
* @covers \Tarampampam\Tasker\Components\TasksStack::addCheck
* @covers \Tarampampam\Tasker\Components\TasksStack::setDescription
* @covers \Tarampampam\Tasker\Components\TasksStack::initTaskIfNeeded
*
* @return void
*/
public function testTasksGettersAndSetters()
{
$this->assertFalse($this->instance->exists($task_name = 'foo_bar'));
$this->instance->addAction($task_name, $action_1 = function () {
return 'foo';
});
$this->assertTrue($this->instance->exists($task_name));
$this->assertEquals([$action_1], $this->instance->getTask($task_name)->actions()->all());
$this->assertEmpty($this->instance->getTask($task_name)->checks()->all());
$this->instance->addAction($task_name, $action_2 = function () {
return 'bar';
});
$this->assertEquals([$action_1, $action_2], $this->instance->getTask($task_name)->actions()->all());
$this->assertEmpty($this->instance->getTask($task_name)->checks()->all());
$this->instance->addCheck($task_name, $check_1 = function () {
return 'baz';
});
$this->assertEquals([$check_1], $this->instance->getTask($task_name)->checks()->all());
$this->instance->setDescription($task_name, $description = 'foo bar');
$this->assertSame($description, $this->instance->getTask($task_name)->description());
$this->instance->addTask($second_task_name = 'bar baz', new Task);
$this->assertTrue($this->instance->exists($second_task_name));
}
/**
* @covers \Tarampampam\Tasker\Components\TasksStack::addTask
*
* @return void
*/
public function testExceptionOnDoubleTaskAppending()
{
$this->expectException(\InvalidArgumentException::class);
$this->instance->addTask($second_task_name = 'bar baz', new Task);
$this->instance->addTask($second_task_name, new Task);
}
/**
* @covers \Tarampampam\Tasker\Components\TasksStack::getIterator
*
* @return void
*/
public function testArrayIterator()
{
$this->instance->setTask($task_name = 'foobar', $task = new Task()); // Just one!
$iterated = false;
foreach ($this->instance as $current_task_name => $iterated_task) {
/* @var Task $task */
$this->assertInstanceOf(Task::class, $iterated_task);
$this->assertEquals($task_name, $current_task_name);
$this->assertEquals($task, $iterated_task);
$iterated = true;
}
$this->assertTrue($iterated);
}
}
<file_sep>/src/Components/Task.php
<?php
declare(strict_types = 1);
namespace Tarampampam\Tasker\Components;
use Tarampampam\Tasker\Support\Stack;
use Tarampampam\Tasker\Support\StackInterface;
use Tarampampam\Tasker\Support\Traits\StaticSelfFactoryTrait;
class Task implements TaskInterface
{
use StaticSelfFactoryTrait;
/**
* @var Stack
*/
protected $actions;
/**
* @var Stack
*/
protected $checks;
/**
* @var string|null
*/
protected $description;
/**
* ActionsStack constructor.
*
* @param callable[]|array $actions
* @param callable[]|array $checks
* @param string|null $description
*/
public function __construct(array $actions = [], array $checks = [], string $description = null)
{
$this->actions = new Stack(\array_filter(\array_merge($this->defaultActions(), $actions), '\is_callable'));
$this->checks = new Stack(\array_filter(\array_merge($this->defaultChecks(), $checks), '\is_callable'));
$this->description = $this->defaultDescription() ?? $description;
}
/**
* {@inheritdoc}
*/
public function defaultActions(): array
{
return [];
}
/**
* {@inheritdoc}
*/
public function defaultChecks(): array
{
return [];
}
/**
* {@inheritdoc}
*/
public function defaultDescription()
{
// return null
}
/**
* {@inheritdoc}
*/
public function actions(): StackInterface
{
return $this->actions;
}
/**
* {@inheritdoc}
*/
public function addAction(callable $action): self
{
$this->actions->add($action);
return $this;
}
/**
* {@inheritdoc}
*/
public function checks(): StackInterface
{
return $this->checks;
}
/**
* {@inheritdoc}
*/
public function addCheck(callable $check): self
{
$this->checks->add($check);
return $this;
}
/**
* {@inheritdoc}
*/
public function description()
{
return $this->description;
}
/**
* {@inheritdoc}
*/
public function setDescription(string $description): self
{
$this->description = $description;
return $this;
}
}
<file_sep>/tests/Support/Traits/MacroableMock.php
<?php
declare(strict_types = 1);
namespace Tarampampam\Tasker\Tests\Support\Traits;
use Tarampampam\Tasker\Support\Traits\MacroableTrait;
class MacroableMock
{
use MacroableTrait;
/**
* @return array
*/
public static function getMacroses(): array
{
return static::$macros;
}
}
<file_sep>/src/Commands/TaskCheckCommand.php
<?php
declare(strict_types = 1);
declare(ticks = 100);
namespace Tarampampam\Tasker\Commands;
use InvalidArgumentException;
use Tarampampam\Tasker\Support\Stack;
use Symfony\Component\Console\Input\InputOption;
use Tarampampam\Tasker\Components\TaskInterface;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface as Output;
class TaskCheckCommand extends AbstractRunCommand
{
// Start infinite loop option signature
const LOOP_OPTION_NAME = 'loop';
// Loop delay option signature
const LOOP_DELAY_OPTION_NAME = 'delay';
// Tries limitation option signature
const TRIES_LIMIT_OPTION_NAME = 'limit';
/**
* {@inheritdoc}
*/
public static function getCommandName(): string
{
return 'task:check';
}
/**
* {@inheritdoc}
*/
public static function getCommandDescription(): string
{
return 'Execute tasks <options=bold>checks</>';
}
/**
* {@inheritdoc}
*/
protected function configure()
{
parent::configure();
$this
->addOption(
static::LOOP_OPTION_NAME,
null,
InputOption::VALUE_NONE,
'Start infinite loop for waiting until all checks will be passed'
)
->addOption(
static::LOOP_DELAY_OPTION_NAME,
null,
InputOption::VALUE_OPTIONAL,
'Delay between infinite loop iterations (in seconds, "0" to disable)',
(string) 2 // "String" reason - Command::addOption
)
->addOption(
static::TRIES_LIMIT_OPTION_NAME,
null,
InputOption::VALUE_OPTIONAL,
'Loop iterations limit ("0" to disable)',
(string) 0 // "String" reason - Command::addOption
);
}
/**
* {@inheritdoc}
*
* @throws InvalidArgumentException
*
* @return int
*/
protected function execute(InputInterface $input, Output $output): int
{
parent::execute($input, $output);
$tasks = $this->getApplication()->getConfiguration()->tasks();
$task_names = (array) $input->getOption(static::TASK_NAME_OPTION_NAME);
$fast_stop = (bool) $input->getOption(static::FAST_STOP_OPTION_NAME);
$start_loop = (bool) $input->getOption(static::LOOP_OPTION_NAME);
$loop_delay = \is_scalar($input->getOption(static::LOOP_DELAY_OPTION_NAME))
? (int) $input->getOption(static::LOOP_DELAY_OPTION_NAME)
: 0;
$loop_limit = \is_scalar($input->getOption(static::TRIES_LIMIT_OPTION_NAME))
? (int) $input->getOption(static::TRIES_LIMIT_OPTION_NAME)
: 0;
$task_names = $this->selectTasksNames($task_names);
$this->log($output, sprintf('Tasks for a work: [<comment>%s</comment>]', \implode(', ', $task_names)));
$loop_counter = 0;
if (empty($task_names)) {
throw new InvalidArgumentException('Tasks was not found');
}
// Build "flat" callable stack from multidimensional array
$callable_stack = new Stack(\array_merge(...\array_filter(\array_map(function ($task_name) use ($tasks) {
$task = $tasks->getTask((string) $task_name);
if ($task instanceof TaskInterface) {
return $task->checks()->all();
}
}, $task_names))));
do {
// Execute each callable
$this->iterateCallableStack($callable_stack, $errors = new Stack, $output, $fast_stop);
if ($start_loop === true) {
$this->sleep($loop_delay);
}
$loop_counter++;
// Exit out loop if needed
if ($loop_limit > 0 && $loop_counter >= $loop_limit) {
break;
}
} while (
$errors->isNotEmpty() && $start_loop === true
);
// Show errors log (if exists)
if ($errors->isNotEmpty()) {
$this->error($output, $errors->all());
return 1;
}
return 0;
}
/**
* Make execution delay.
*
* @param int $seconds
*
* @return void
*/
protected function sleep(int $seconds = 0)
{
$seconds = \max($seconds, 0);
$coefficient = 10;
if ($seconds > 0) {
for ($i = 0; $i < $seconds * $coefficient; $i++) {
$this->doSleep(intdiv(1000000, $coefficient)); // 1000000 = 1 second
}
}
}
/**
* Make "native" sleep.
*
* @codeCoverageIgnore
*
* @see \usleep()
*
* @param int $micro_seconds
*
* @return void
*/
protected function doSleep(int $micro_seconds)
{
\usleep($micro_seconds);
}
}
<file_sep>/src/Components/TasksStack.php
<?php
declare(strict_types = 1);
namespace Tarampampam\Tasker\Components;
use Countable;
use ArrayIterator;
use IteratorAggregate;
use InvalidArgumentException;
use Tarampampam\Tasker\Support\Traits\MacroableTrait;
use Tarampampam\Tasker\Support\Traits\StaticSelfFactoryTrait;
class TasksStack implements Countable, IteratorAggregate
{
use MacroableTrait,
StaticSelfFactoryTrait;
/**
* Tasks stack.
*
* @var TaskInterface[]
*/
protected $tasks = [];
/**
* Get all of the items in the tasks stack.
*
* @return TaskInterface[]
*/
public function all(): array
{
return $this->tasks;
}
/**
* Get tasks names.
*
* @return string[]
*/
public function names(): array
{
return \array_keys($this->tasks);
}
/**
* Add action into named task.
*
* @param string $task_name
* @param callable $action
*
* @return $this
*/
public function addAction(string $task_name, callable $action): self
{
$this->initTaskIfNeeded($task_name);
$task = $this->getTask($task_name);
if ($task instanceof TaskInterface) {
$task->addAction($action);
}
return $this;
}
/**
* Make check - named task is exists?
*
* @param string $task_name
*
* @return bool
*/
public function exists(string $task_name): bool
{
return isset($this->tasks[$task_name]);
}
/**
* Get task instance by name.
*
* @param string $task_name
*
* @return null|TaskInterface
*/
public function getTask(string $task_name)
{
return $this->tasks[$task_name] ?? null;
}
/**
* Add named task.
*
* @param string $task_name
* @param TaskInterface $task
*
* @throws InvalidArgumentException
*
* @return $this
*/
public function addTask(string $task_name, TaskInterface $task): self
{
if ($this->exists($task_name)) {
throw new InvalidArgumentException("Task with name [{$task_name}] already exists");
}
$this->tasks[$task_name] = $task;
return $this;
}
/**
* Set named task.
*
* @param string $task_name
* @param TaskInterface $task
*
* @return $this
*/
public function setTask(string $task_name, TaskInterface $task): self
{
$this->tasks[$task_name] = $task;
return $this;
}
/**
* Add check into named task.
*
* @param string $task_name
* @param callable $action
*
* @return $this
*/
public function addCheck(string $task_name, callable $action): self
{
$this->initTaskIfNeeded($task_name);
$task = $this->getTask($task_name);
if ($task instanceof TaskInterface) {
$task->addCheck($action);
}
return $this;
}
/**
* Set description for named task.
*
* @param string $task_name
* @param string $description
*
* @return $this
*/
public function setDescription(string $task_name, string $description): self
{
$this->initTaskIfNeeded($task_name);
$task = $this->getTask($task_name);
if ($task instanceof TaskInterface) {
$task->setDescription($description);
}
return $this;
}
/**
* {@inheritdoc}
*/
public function count(): int
{
return \count($this->tasks);
}
/**
* Get an iterator for the tasks.
*
* @return ArrayIterator
*/
public function getIterator(): ArrayIterator
{
return new ArrayIterator($this->tasks);
}
/**
* Make named task stack initialization, if needed.
*
* @param string $stack_name
*
* @return void
*/
protected function initTaskIfNeeded(string $stack_name)
{
if (! $this->exists($stack_name)) {
$this->tasks[$stack_name] = new Task;
}
}
}
<file_sep>/tests/Support/Traits/StaticSelfFactoryTraitMock.php
<?php
declare(strict_types = 1);
namespace Tarampampam\Tasker\Tests\Support\Traits;
use Tarampampam\Tasker\Support\Traits\StaticSelfFactoryTrait;
class StaticSelfFactoryTraitMock
{
use StaticSelfFactoryTrait;
public $foo;
public function __construct($foo)
{
$this->foo = $foo;
}
}
<file_sep>/src/Commands/TaskExecuteCommand.php
<?php
declare(strict_types = 1);
namespace Tarampampam\Tasker\Commands;
use InvalidArgumentException;
use Tarampampam\Tasker\Support\Stack;
use Tarampampam\Tasker\Components\TaskInterface;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface as Output;
class TaskExecuteCommand extends AbstractRunCommand
{
/**
* {@inheritdoc}
*/
public static function getCommandName(): string
{
return 'task:exec';
}
/**
* {@inheritdoc}
*/
public static function getCommandDescription(): string
{
return 'Execute tasks <options=bold>actions</>';
}
/**
* {@inheritdoc}
*
* @throws InvalidArgumentException
*
* @return int
*/
protected function execute(InputInterface $input, Output $output): int
{
parent::execute($input, $output);
$tasks = $this->getApplication()->getConfiguration()->tasks();
$task_names = (array) $input->getOption(static::TASK_NAME_OPTION_NAME);
$fast_stop = (bool) $input->getOption(static::FAST_STOP_OPTION_NAME);
$task_names = $this->selectTasksNames($task_names);
$this->log($output, sprintf('Tasks for a work: [<comment>%s</comment>]', \implode(', ', $task_names)));
if (empty($task_names)) {
throw new InvalidArgumentException('Tasks was not found');
}
// Build callable stack
$callable_stack = new Stack(\array_merge(...\array_filter(\array_map(function ($task_name) use ($tasks) {
$task = $tasks->getTask((string) $task_name);
if ($task instanceof TaskInterface) {
return $task->actions()->all();
}
}, $task_names))));
// Execute each callable
$this->iterateCallableStack($callable_stack, $errors = new Stack, $output, $fast_stop);
// Show errors log (if exists)
if ($errors->isNotEmpty()) {
$this->error($output, $errors->all());
return 1;
}
return 0;
}
}
<file_sep>/tests/Commands/AbstractRunCommandTestCase.php
<?php
declare(strict_types = 1);
namespace Tarampampam\Tasker\Tests\Commands;
use Tarampampam\Tasker\Support\Stack;
use Tarampampam\Tasker\Components\Task;
use Symfony\Component\Console\Input\InputOption;
use Tarampampam\Tasker\Commands\AbstractRunCommand;
use Symfony\Component\Console\Output\BufferedOutput;
/**
* @covers \Tarampampam\Tasker\Commands\AbstractRunCommand
*/
abstract class AbstractRunCommandTestCase extends AbstractCommandTestCase
{
/**
* @var AbstractRunCommand
*/
protected $command;
/**
* @return void
*/
public function testConstants()
{
$this->assertSame('task-name', $this->command::TASK_NAME_OPTION_NAME);
$this->assertSame('fast-stop', $this->command::FAST_STOP_OPTION_NAME);
}
/**
* @covers \Tarampampam\Tasker\Commands\AbstractRunCommand::configure
*
* @return void
*/
public function testAbstractConfigure()
{
parent::testAbstractConfigure();
/** @var InputOption $task_name_option */
$task_name_option = $this->command->getDefinition()->getOption($this->command::TASK_NAME_OPTION_NAME);
$this->assertSame('t', $task_name_option->getShortcut());
$this->assertTrue($task_name_option->isArray());
$this->assertTrue($task_name_option->isValueOptional());
/** @var InputOption $fast_stop_option */
$fast_stop_option = $this->command->getDefinition()->getOption($this->command::FAST_STOP_OPTION_NAME);
$this->assertNull($fast_stop_option->getShortcut());
$this->assertFalse($fast_stop_option->acceptValue());
}
/**
* @covers \Tarampampam\Tasker\Commands\AbstractRunCommand::selectTasksNames
*
* @return void
*/
public function testSelectTasksNames()
{
$this->app->getConfiguration()->tasks()->addTask($name_1 = 'foo', Task::make());
$this->app->getConfiguration()->tasks()->addTask($name_2 = 'bar', Task::make());
$method_name = 'selectTasksNames';
$this->assertSame([], $this->callMethod($this->command, $method_name, [['baz']]));
$this->assertSame([$name_1, $name_2], $this->callMethod($this->command, $method_name, [[]]));
$this->assertSame([$name_1], $this->callMethod($this->command, $method_name, [[$name_1]]));
$this->assertSame([$name_1], $this->callMethod($this->command, $method_name, [[$name_1, 'baz']]));
}
/**
* @covers \Tarampampam\Tasker\Commands\AbstractRunCommand::iterateCallableStack
*
* @return void
*/
public function testIterateCallableStackWithCallbackFalseWithoutFastStop()
{
$callable = Stack::make()->add(function () {
return false;
});
$callable->add(function () {
return false;
});
$this->assertTrue($this->callMethod($this->command, 'iterateCallableStack', [
$callable,
$errors = new Stack,
$output = new BufferedOutput,
false,
]));
$this->assertSame(2, $errors->count());
$this->assertContains('error', $output->fetch());
}
/**
* @covers \Tarampampam\Tasker\Commands\AbstractRunCommand::iterateCallableStack
*
* @return void
*/
public function testIterateCallableStackWithCallbackFalse()
{
$callable = Stack::make()->add(function () {
return false;
});
$callable->add(function () {
return false;
});
$this->assertTrue($this->callMethod($this->command, 'iterateCallableStack', [
$callable,
$errors = new Stack,
$output = new BufferedOutput,
true,
]));
$this->assertSame(1, $errors->count());
$this->assertContains('returns false', $errors[0]);
$this->assertContains('error', $output->fetch());
}
/**
* @covers \Tarampampam\Tasker\Commands\AbstractRunCommand::iterateCallableStack
*
* @return void
*/
public function testIterateCallableStackWithException()
{
$this->assertTrue($this->callMethod($this->command, 'iterateCallableStack', [
$callable = Stack::make()->add(function () {
throw new \Exception('blah blah error');
}),
$errors = new Stack,
$output = new BufferedOutput,
true,
]));
$this->assertSame(1, $errors->count());
$this->assertContains('blah blah error', $errors[0]);
$this->assertContains('error', $output->fetch());
}
/**
* @covers \Tarampampam\Tasker\Commands\AbstractRunCommand::iterateCallableStack
*
* @return void
*/
public function testIterateCallableStackWithoutErrors()
{
$this->assertTrue($this->callMethod($this->command, 'iterateCallableStack', [
$callable = Stack::make()->add(function () {
//
}),
$errors = new Stack,
$output = new BufferedOutput,
]));
$this->assertSame(0, $errors->count());
$this->assertNotContains('error', $output->fetch());
}
/**
* @covers \Tarampampam\Tasker\Commands\AbstractRunCommand::iterateCallableStack
*
* @return void
*/
public function testIterateCallableStackWithEmptyStack()
{
$this->assertFalse($this->callMethod($this->command, 'iterateCallableStack', [
$callable = new Stack,
$errors = new Stack,
$output = new BufferedOutput,
]));
$this->assertSame(0, $errors->count());
$this->assertEmpty($output->fetch());
}
}
<file_sep>/Makefile
#!/usr/bin/make
# Makefile readme (ru): <http://linux.yaroslavl.ru/docs/prog/gnu_make_3-79_russian_manual.html>
# Makefile readme (en): <https://www.gnu.org/software/make/manual/html_node/index.html#SEC_Contents>
BASE_DIR := $(shell dirname $(realpath $(lastword $(MAKEFILE_LIST))))
SHELL = /bin/sh
PHP = $(shell command -v php 2> /dev/null)
CURL = $(shell command -v curl 2> /dev/null)
COMPOSER = $(shell command -v composer 2> /dev/null)
COMPOSER_FLAGS = --ansi --no-suggest --prefer-dist --quiet
.PHONY : help vendors test build clean
.DEFAULT_GOAL : help
# This will output the help for each task. thanks to https://marmelab.com/blog/2016/02/29/auto-documented-makefile.html
help: ## Show this help
@awk 'BEGIN {FS = ":.*?## "} /^[a-zA-Z_-]+:.*?## / {printf " \033[36m%-10s\033[0m %s\n", $$1, $$2}' $(MAKEFILE_LIST)
vendors: ## Install all project dependencies
$(PHP) $(COMPOSER) install $(COMPOSER_FLAGS)
build: clean ## Build PHAR archive
$(PHP) $(COMPOSER) install $(COMPOSER_FLAGS) --no-interaction --no-dev
@if [ ! -f $(BASE_DIR)/box.phar ]; then $(CURL) -LSs https://box-project.github.io/box2/installer.php | $(PHP) -d "phar.readonly=Off"; fi
$(PHP) -d "phar.readonly=Off" $(BASE_DIR)/box.phar build --configuration $(BASE_DIR)/box.json.dist
$(MAKE) vendors
test: vendors ## Execute application tests
$(PHP) $(COMPOSER) test
$(PHP) $(COMPOSER) phpstan
clean: ## Make clean in project directory
rm -f $(BASE_DIR)/clover-file $(BASE_DIR)/build/*.phar
rm -Rf $(BASE_DIR)/coverage $(BASE_DIR)/tests/temp $(BASE_DIR)/tests/tmp
<file_sep>/src/Support/Traits/StaticSelfFactoryTrait.php
<?php
declare(strict_types = 1);
namespace Tarampampam\Tasker\Support\Traits;
trait StaticSelfFactoryTrait
{
/**
* Create a new self instance.
*
* @param mixed ...$arguments
*
* @return static|self
*/
public static function make(...$arguments)
{
return new static(...$arguments);
}
}
<file_sep>/src/Support/StackInterface.php
<?php
namespace Tarampampam\Tasker\Support;
use Countable;
use ArrayAccess;
use IteratorAggregate;
interface StackInterface extends ArrayAccess, Countable, IteratorAggregate
{
/**
* Get all of the items in the stack.
*
* @return array
*/
public function all();
/**
* Remove an item from the stack by key.
*
* @param string|array $keys
*
* @return self
*/
public function forget($keys);
/**
* Get an item from the stack by key.
*
* @param mixed $key
* @param mixed $default
*
* @return mixed
*/
public function get($key, $default = null);
/**
* Put an item in the stack by key.
*
* @param mixed $key
* @param mixed $value
*
* @return self
*/
public function put($key, $value);
/**
* Add an item in the stack.
*
* @param mixed $value
*
* @return self
*/
public function add($value);
/**
* Determine if the stack is empty.
*
* @return bool
*/
public function isEmpty(): bool;
/**
* Determine if the stack is not empty.
*
* @return bool
*/
public function isNotEmpty(): bool;
/**
* Iterate each stack element using closure.
*
* @param callable $closure
*
* @return self
*/
public function each(callable $closure);
/**
* Get the keys of the stack items.
*
* @return string[]
*/
public function keys(): array;
/**
* Get the stack values.
*
* @return string[]
*/
public function values(): array;
}
<file_sep>/tests/Stubs/samples/configs/valid_configuration.php
<?php
use Tarampampam\Tasker\Components\Task;
use Tarampampam\Tasker\Components\TasksStack;
return TasksStack::make()
->addAction($foo_name = 'foo', function () {
return 'ok';
})
->addCheck($foo_name, function () {
return 'ok';
})
->addAction($foo_name, function () {
return 'ok';
})
->setDescription($foo_name, 'foo description')
->setTask('bar', Task::make()
->addAction(function () {
return 'ok';
}))
->setTask('baz', Task::make()
->addCheck(function () {
return 'ok';
}))
->setTask('nothing', Task::make()
->setDescription('Nothing is here'));
<file_sep>/src/Support/Stack.php
<?php
/**
* Parts of source code was taken from package "illuminate/support" .
*
* @license MIT
*
* @see https://github.com/illuminate/support
*
* @author <NAME> <<EMAIL>>
*/
declare(strict_types = 1);
namespace Tarampampam\Tasker\Support;
use ArrayIterator;
use Symfony\Component\VarDumper\VarDumper;
use Tarampampam\Tasker\Support\Traits\MacroableTrait;
use Tarampampam\Tasker\Support\Traits\StaticSelfFactoryTrait;
class Stack implements StackInterface
{
use MacroableTrait,
StaticSelfFactoryTrait;
/**
* The items contained in the stack.
*
* @var array
*/
protected $items = [];
/**
* Create a new stack.
*
* @param mixed $items
*
* @return void
*/
public function __construct($items = [])
{
$this->items = (array) $items;
}
/**
* {@inheritdoc}
*/
public function all()
{
return $this->items;
}
/**
* Dump the stack.
*
* IMPORTANT: Do not use this method in production!
*
* @codeCoverageIgnore
*
* @return $this
*/
public function dump()
{
VarDumper::dump($this->items);
return $this;
}
/**
* {@inheritdoc}
*/
public function forget($keys)
{
foreach ((array) $keys as $key) {
$this->offsetUnset($key);
}
return $this;
}
/**
* Unset the item at a given offset.
*
* @param string $key
*
* @return void
*/
public function offsetUnset($key)
{
unset($this->items[$key]);
}
/**
* {@inheritdoc}
*/
public function get($key, $default = null)
{
if ($this->offsetExists($key)) {
return $this->items[$key];
}
return $default;
}
/**
* Determine if an item exists at an offset.
*
* @param mixed $key
*
* @return bool
*/
public function offsetExists($key): bool
{
return \array_key_exists($key, $this->items);
}
/**
* {@inheritdoc}
*/
public function put($key, $value)
{
$this->offsetSet($key, $value);
return $this;
}
/**
* Set the item at a given offset.
*
* @param mixed $key
* @param mixed $value
*
* @return void
*/
public function offsetSet($key, $value)
{
if ($key === null) {
$this->items[] = $value;
} else {
$this->items[$key] = $value;
}
}
/**
* {@inheritdoc}
*/
public function add($value)
{
$this->items[] = $value;
return $this;
}
/**
* {@inheritdoc}
*/
public function isNotEmpty(): bool
{
return ! $this->isEmpty();
}
/**
* {@inheritdoc}
*/
public function isEmpty(): bool
{
return empty($this->items);
}
/**
* {@inheritdoc}
*/
public function each(callable $closure)
{
foreach ($this->items as &$item) {
$closure($item);
}
return $this;
}
/**
* {@inheritdoc}
*/
public function keys(): array
{
return \array_keys($this->items);
}
/**
* {@inheritdoc}
*/
public function values(): array
{
return \array_values($this->items);
}
/**
* Get an iterator for the stack items.
*
* @return ArrayIterator
*/
public function getIterator(): ArrayIterator
{
return new ArrayIterator($this->items);
}
/**
* Count the number of items in the stack.
*
* @return int
*/
public function count(): int
{
return \count($this->items);
}
/**
* Get an item at a given offset.
*
* @param mixed $key
*
* @return mixed
*/
public function offsetGet($key)
{
return $this->items[$key];
}
}
|
3fd1a96fbb31cda192f9d9e35e421a7e690f8d7a
|
[
"Markdown",
"Makefile",
"PHP"
] | 42
|
PHP
|
tarampampam/tasker-php
|
efcef9915d2084ad3d2f56d9b7a4a13b76f165a4
|
3162488c212a3ce5d7451a53c80cfdf57e4ed1f0
|
refs/heads/master
|
<repo_name>rosswd/todo-rails<file_sep>/app/controllers/todos_controller.rb
class TodosController < ApplicationController
def index
@todos = Todo.all
@todos = Todo.order(:updated_at).page params[:page]
end
def show
@todo = Todo.find(params[:id])
end
def new
@todo = Todo.new
end
def edit
@todo = Todo.find(params[:id])
end
def create
@todo = Todo.new(todos_params)
if @todo.save
flash[:notice] = 'Todo added successfully!'
redirect_to todos_path
else
flash[:notice] = 'Todo NOT created!'
render 'new'
end
end
def update
@todo = Todo.find(params[:id])
if @todo.update(todos_params)
flash[:notice] = 'Todo successfully updated!'
redirect_to todos_path
else
flash[:notice] = 'Todo NOT updated!'
render 'edit'
end
end
def destroy
@todo = Todo.find(params[:id])
if @todo.destroy
flash[:notice] = 'Todo successfully deleted!'
redirect_to todos_path
else
flash[:notice] = 'Todo not deleted. Try again.'
end
end
private
def todos_params
params.require(:todo).permit(:title, :description)
end
end
<file_sep>/config/routes.rb
Rails.application.routes.draw do
root 'home#index'
resources :todos
resources :contact
end
<file_sep>/app/helpers/application_helper.rb
module ApplicationHelper
# Helper for formatting the last modified field
def pretty_date(d)
d.strftime('%B %e, %Y %H:%M')
end
end
<file_sep>/README.md
[](https://travis-ci.org/rosswd/todo-rails)
# Todo-rails
A simple todo app built with Ruby on Rails.

## TODO
+ Change 'done' popup to a modal.
+ ~~Fix CSS spacing on forms~~
+ ~~Change create and update submit buttons~~
+ Add support for time zones [v2]
+ Add user registration and authentication [v2]
+ Create timezones on a per user basis [v2]
+ Add a deadline field or priority field [v2]
+ Add notifications by email for deadlines [v2]
<file_sep>/db/seeds.rb
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
Todo.create!(title: 'Jog 5 Miles', description: 'Jog 5 Miles every morning.')
Todo.create!(title: 'Pick up Clothes', description: 'Pick up dry cleaning before 5pm.')
Todo.create!(title: 'Start Business Report')
Todo.create!(title: 'Go Grocery Shopping', description: 'Do the weekly Grocery shop.')
Todo.create!(title: 'Lodge Cheques in Bank', description: 'Cheques go out of date soon.')<file_sep>/test/models/todo_test.rb
require 'test_helper'
class TodoTest < ActiveSupport::TestCase
end
|
14831ac9172bdda30674345e9c349ace93ca5a1a
|
[
"Markdown",
"Ruby"
] | 6
|
Ruby
|
rosswd/todo-rails
|
f7253b6046ab6e84c925b2fe6f496fa3a7e914fd
|
930458310c2d6a342f4976cb38e4e7aefcaf2341
|
refs/heads/master
|
<file_sep>#include <any>
#include <vector>
using namespace std;
// Tip: You can use el.type() == typeid(vector<any>) to check whether an item is a list
// or an integer.
int productSum(vector<any> array, int depth = 1) {
int sum = 0;
for (auto element:array){
if(element.type()==typeid(vector<any>)){
sum += productSum(any_cast<vector<any>>(element), depth + 1);
}
else {
sum += any_cast<int> (element);
}
}
return sum * depth;
}
<file_sep>#include <vector>
#include <algorithm>
using namespace std;
vector<vector<int>> threeNumberSum(vector<int> array, int targetSum) {
// Write your code here.
int left, right, currentsum;
vector<vector<int>> triplets;
sort(array.begin(), array.end());
for (int i = 0; i < array.size() - 2; i++) {
left = i + 1;
right = array.size() - 1;
while (left < right) {
currentsum = array[i] + array[left] + array[right];
if (currentsum < targetSum) {
left++;
}
else if (currentsum > targetSum) {
right--;
}
else {
triplets.push_back({ array[i],array[left],array[right] });
left++;
right--;
}
}
}
return triplets;
}
<file_sep>#include <vector>
#include <unordered_set>
using namespace std;
vector<int> twoNumberSum(vector<int> array, int targetSum) {
vector<int> result;
int numbertofind;
unordered_set<int> set;
for (int i = 0; i < array.size(); i++) {
numbertofind = targetSum - array[i];
if (set.find(numbertofind) != set.end()) {
if (numbertofind < array[i]) {
result.push_back(numbertofind);
result.push_back(array[i]);
}
else {
result.push_back(array[i]);
result.push_back(numbertofind);
}
}
else {
set.insert(array[i]);
}
}
return result;
}
//O(n) time and O(n) space complexity<file_sep>class BST {
public:
int value;
BST* left;
BST* right;
BST(int val);
BST& insert(int val);
};
int closestValue = INT_MAX;
int findClosestValueInBst(BST* tree, int target) {
BST* currentnode = tree;
while (currentnode != NULL) {
if (abs((currentnode->value) - target) < abs(closestValue - target)) {
closestValue = currentnode->value;
}
if (target < (currentnode->value)) {
currentnode = currentnode->left;
}
else if (target > (currentnode->value)) {
currentnode = currentnode->right;
}
else {
break;
}
}
return closestValue;
}<file_sep>using namespace std;
// This is the class of the input root. Do not edit it.
class BinaryTree {
public:
int value;
BinaryTree* left;
BinaryTree* right;
BinaryTree(int value) {
this->value = value;
left = NULL;
right = NULL;
}
};
void calculatebranchsum(BinaryTree* root, int runningsum, vector<int>& branchsums);
vector<int> branchSums(BinaryTree* root) {
// Write your code here.
vector<int> branchsums;
int runningsum;
calculatebranchsum(root, 0, branchsums);
return branchsums;
}
void calculatebranchsum(BinaryTree* node, int runningsum, vector<int>& branchsums) {
if (node == NULL) return;
runningsum = runningsum + node->value;
if (node->left == NULL && node->right == NULL) {
branchsums.push_back(runningsum);
}
calculatebranchsum(node->left, runningsum, branchsums);
calculatebranchsum(node->right, runningsum, branchsums);
//ILT do either iterative or recursive, generally recursive as it is much simpler
}
|
0047f31a1d81f272753dee72f17f486e0104c3dc
|
[
"C++"
] | 5
|
C++
|
ameyaamd96/data-structures-and-algorithms
|
272b2db10c22329d08bc92c69a8df554dfdeb168
|
ee5b089fbe0853ca9ebbee4584f9ee5b25528f84
|
refs/heads/master
|
<file_sep>#Sum square difference
#Problem 6
#The sum of the squares of the first ten natural numbers is,
#12 + 22 + ... + 102 = 385
#The square of the sum of the first ten natural numbers is,
#(1 + 2 + ... + 10)2 = 552 = 3025
#Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640.
#Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
def SumofSquares(num):
total = 0
for i in range(1, num + 1):
total += (i * i)
return total
def SquareofSum(num):
total = num * (num + 1) / 2
return total * total
def SumSqDiff(num):
return SquareofSum(num)-SumofSquares(num)
print(SumSqDiff(10))
print(SumSqDiff(100))
<file_sep>#Odd period square roots
#Problem 64
#All square roots are periodic when written as continued fractions and can be written in the form:
#√N = a0 +
#1
# a1 +
#1
# a2 +
#1
# a3 + ...
#For example, let us consider √23:
#√23 = 4 + √23 — 4 = 4 +
#1
# = 4 +
#1
#
#1
#√23—4
# 1 +
#√23 – 3
#7
#If we continue we would get the following expansion:
#√23 = 4 +
#1
# 1 +
#1
# 3 +
#1
# 1 +
#1
# 8 + ...
#The process can be summarised as follows:
#a0 = 4,
#1
#√23—4
# =
#√23+4
#7
# = 1 +
#√23—3
#7
#a1 = 1,
#7
#√23—3
# =
#7(√23+3)
#14
# = 3 +
#√23—3
#2
#a2 = 3,
#2
#√23—3
# =
#2(√23+3)
#14
# = 1 +
#√23—4
#7
#a3 = 1,
#7
#√23—4
# =
#7(√23+4)
#7
# = 8 + √23—4
#a4 = 8,
#1
#√23—4
# =
#√23+4
#7
# = 1 +
#√23—3
#7
#a5 = 1,
#7
#√23—3
# =
#7(√23+3)
#14
# = 3 +
#√23—3
#2
#a6 = 3,
#2
#√23—3
# =
#2(√23+3)
#14
# = 1 +
#√23—4
#7
#a7 = 1,
#7
#√23—4
# =
#7(√23+4)
#7
# = 8 + √23—4
#It can be seen that the sequence is repeating. For conciseness, we use the notation √23 = [4;(1,3,1,8)], to indicate that the block (1,3,1,8) repeats indefinitely.
#The first ten continued fraction representations of (irrational) square roots are:
#√2=[1;(2)], period=1
#√3=[1;(1,2)], period=2
#√5=[2;(4)], period=1
#√6=[2;(2,4)], period=2
#√7=[2;(1,1,1,4)], period=4
#√8=[2;(1,4)], period=2
#√10=[3;(6)], period=1
#√11=[3;(3,6)], period=2
#√12= [3;(2,6)], period=2
#√13=[3;(1,1,1,1,6)], period=5
#Exactly four continued fractions, for N ≤ 13, have an odd period.
#How many continued fractions for N ≤ 10000 have an odd period?
import math
import decimal
iterations = 0
append_list = []
frac_list = []
from decimal import *
def sqrfract(num):
m = 0
d = 1
root = Decimal(num)**Decimal(0.5)
a_0 = int(root)
a = a_0
append_list.append(a)
count = 0
while count < 500:
m = d*a - m
d = int((num - m**2) / d)
a = int((a_0 + m)/d)
append_list.append(a)
count += 1
return append_list[1:]
def period(fraclist):
period = 0
fracset = set(fraclist)
unionset = fracset.union(fracset)
if len(unionset) == 1:
return 1
half_len = int(len(fraclist) / 2)
for j in range(1, half_len):
if fraclist[0:j] == fraclist[j:2*j]:
k = int(j/2)
if fraclist[0:k] == fraclist[k:j] and k > 1:
fracset = set(fraclist[0:k])
if unionset.issubset(fracset) == True:
break
if period < j:
period = j
else:
continue
return period
def sqrnum(num):
root = math.sqrt(num)
a_0 = int(math.sqrt(num))
if root - a_0 == 0:
return True
return False
total = 0
for num in range(2, 10001):
if sqrnum(num) != True:
append_list = []
frac_list = sqrfract(num)
repeats = period(frac_list)
if repeats % 2 != 0:
total += 1
print(total)
<file_sep>#Coin sums
#Problem 31
#In England the currency is made up of pound, £, and pence, p, and there are eight coins in general circulation:
#1p, 2p, 5p, 10p, 20p, 50p, £1 (100p) and £2 (200p).
#It is possible to make £2 in the following way:
#1×£1 + 1×50p + 2×20p + 1×5p + 1×2p + 3×1p
#How many different ways can £2 be made using any number of coins?
#currency = [0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 1, 2]
ways = 0 # for 1x2, 2x1
target = 200
for a in range(200, -1, -200):
for b in range(a, -1, -100):
for c in range(b, -1, -50):
for d in range(c, -1, -20):
for e in range(d, -1, -10):
for f in range(e, -1, -5):
for g in range(f, -1, -2):
ways += 1
print(ways)
<file_sep>#Multiples of 3 and 5
#Problem 1
#If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
#Find the sum of all the multiples of 3 or 5 below 1000.
#! python3
total = 0
for i in range(1000):
if i%3 == 0 or i%5 == 0:
total += i;
print(total)
<file_sep>#1000-digit Fibonacci number
#Problem 25
#The Fibonacci sequence is defined by the recurrence relation:
#Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1.
#Hence the first 12 terms will be:
#F1 = 1
#F2 = 1
#F3 = 2
#F4 = 3
#F5 = 5
#F6 = 8
#F7 = 13
#F8 = 21
#F9 = 34
#F10 = 55
#F11 = 89
#F12 = 144
#The 12th term, F12, is the first term to contain three digits.
#What is the index of the first term in the Fibonacci sequence to contain 1000 digits?
maxlimit = 10 ** 1000
#print(len(str(maxlimit)))
fibonacci_list = [1, 1]
num = 1
i = 1
j = 1
while num < maxlimit:
num = i + j
fibonacci_list.append(num)
i = j
j = num
index = 0
length = len(str(fibonacci_list[index]))
while length != 1000:
length = len(str(fibonacci_list[index]))
index += 1
print(index)
<file_sep>#Powerful digit counts
#Problem 63
#The 5-digit number, 16807=75, is also a fifth power. Similarly, the 9-digit number, 134217728=89, is a ninth power.
#How many n-digit positive integers exist which are also an nth power?
def numDigits(number):
return len(str(number))
count = 0
for num in range(1, 10):
for power in range(1, 100):
power_num = num ** power
if power == numDigits(power_num):
count += 1
print(count)
<file_sep>#Powerful digit sum
#Problem 56
#A googol (10100) is a massive number: one followed by one-hundred zeros; 100100 is almost unimaginably large: one followed by two-hundred zeros. Despite their size, the sum of the digits in each number is only 1.
#Considering natural numbers of the form, ab, where a, b < 100, what is the maximum digital sum?
def digitsum(largenum):
string = str(largenum)
total = 0
for char in string:
total += int(char)
return total
max_val = 0
for a in range(1, 100):
for b in range(1, 100):
power_val = a ** b
sum_val = digitsum(power_val)
if sum_val > max_val:
max_val = sum_val
print(max_val)
<file_sep>#Prime pair sets
#Problem 60
#The primes 3, 7, 109, and 673, are quite remarkable. By taking any two primes and concatenating them in any order the result will always be prime. For example, taking 7 and 109, both 7109 and 1097 are prime. The sum of these four primes, 792, represents the lowest sum for a set of four primes with this property.
#Find the lowest sum for a set of five primes for which any two primes concatenate to produce another prime.
def isPrime(n):
if n == 0 or n == 1:
return False
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
return True
prime_list = []
for num in range(3, 10000):
if isPrime(num) == True:
prime_list.append(num)
#print(prime_list)
length = len(prime_list)
#print(length)
#concat_primes = {0}
list_of_tuples = []
for i in range(length):
for j in range(i+1, length):
string1 = str(prime_list[i]) + str(prime_list[j])
string2 = str(prime_list[j]) + str(prime_list[i])
if isPrime(int(string1)) == True and isPrime(int(string2)) == True:
#concat_primes.add(prime_list[i])
#concat_primes.add(prime_list[j])
num_tuple = (prime_list[i],prime_list[j])
list_of_tuples.append(num_tuple)
continue
#concat_primes = concat_primes.union(concat_primes)
#print(list_of_tuples)
#print(concat_primes)
total = 0
min_total = 0
for a,b in list_of_tuples:
for c,d in list_of_tuples:
if a == c and b == d:
continue
if (a,c) in list_of_tuples and (a,d) in list_of_tuples and (b,c) in list_of_tuples and (b,d) in list_of_tuples:
for e,f in list_of_tuples:
if (a == e and b == f) or (c == e and d == f):
continue
if (a,e) in list_of_tuples and (b,e) in list_of_tuples and (c,e) in list_of_tuples and (d,e) in list_of_tuples:
total = a + b + c + d + e
if total < min_total:
min_total = total
print(min_total)
#print(a,b,c,d,e)
if (a,f) in list_of_tuples and (b,f) in list_of_tuples and (c,f) in list_of_tuples and (d,f) in list_of_tuples:
total = a + b + c + d + f
if total < min_total:
min_total = total
print(min_total)
#print(a,b,c,d,f)
else:
continue
print('END')
<file_sep>#Spiral primes
#Problem 58
#Starting with 1 and spiralling anticlockwise in the following way, a square spiral with side length 7 is formed.
#37 36 35 34 33 32 31
#38 17 16 15 14 13 30
#39 18 5 4 3 12 29
#40 19 6 1 2 11 28
#41 20 7 8 9 10 27
#42 21 22 23 24 25 26
#43 44 45 46 47 48 49
#It is interesting to note that the odd squares lie along the bottom right diagonal, but what is more interesting is that 8 out of the 13 numbers lying along both diagonals are prime; that is, a ratio of 8/13 ≈ 62%.
#If one complete new layer is wrapped around the spiral above, a square spiral with side length 9 will be formed. If this process is continued, what is the side length of the square spiral for which the ratio of primes along both diagonals first falls below 10%?
def isPrime(n):
if n == 0 or n == 1:
return False
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
return True
def spiralPrime(num):
diag = 1
rval = 1
lval = 1
prime = 0
for i in range(num):
rval += 2 * (i)
if i%2 == 0:
lval += 4 * (i/2)
else:
lval += 4 * (i+1)/2
lval = int(lval)
#total += (int(lval) + rval)
#print(int(lval), rval)
if isPrime(lval) == True:
prime += 1
if isPrime(rval) == True:
prime += 1
if i > 0:
diag += 2
#print(prime * 100/diag)
return (prime * 100/diag)
for i in range(26201, 26300, 2): #Set by trials
if spiralPrime(i) < 10:
print(i)
break
<file_sep>#10001st prime
#Problem 7
#By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
#What is the 10001st prime number?
def isPrime(n):
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
return True
def nthPrime(n):
prime = 0
num = 2
while prime < n:
if isPrime(num) == True:
prime += 1
num += 1
return num - 1
print(nthPrime(10001))
<file_sep>#Convergents of e
#Problem 65
#The square root of 2 can be written as an infinite continued fraction.
#The infinite continued fraction can be written, √2 = [1;(2)], (2) indicates that 2 repeats ad infinitum. In a similar way, √23 = [4;(1,3,1,8)].
#It turns out that the sequence of partial values of continued fractions for square roots provide the best rational approximations. Let us consider the convergents for √2.
#Hence the sequence of the first ten convergents for √2 are:
#1, 3/2, 7/5, 17/12, 41/29, 99/70, 239/169, 577/408, 1393/985, 3363/2378, ...
#What is most surprising is that the important mathematical constant,
#e = [2; 1,2,1, 1,4,1, 1,6,1 , ... , 1,2k,1, ...].
#The first ten terms in the sequence of convergents for e are:
#2, 3, 8/3, 11/4, 19/7, 87/32, 106/39, 193/71, 1264/465, 1457/536, ...
#The sum of digits in the numerator of the 10th convergent is 1+4+5+7=17.
#Find the sum of digits in the numerator of the 100th convergent of the continued fraction for e.
def digitsum(num):
numstr = str(num)
total = 0
for char in numstr:
total += int(char)
return total
def converge_e(num):
num_prev = 2
num_cur = 3
for i in range(num - 2):
if i % 3 == 0:
mult = 2 * (i+3)//3
else:
mult = 1
new_num = mult * num_cur + num_prev
num_prev = num_cur
num_cur = new_num
return new_num
num = (converge_e(100))
print(digitsum(num))
<file_sep>#Odd period square roots
#Problem 64
#All square roots are periodic when written as continued fractions and can be written in the form:
#√N = a0 +
#1
# a1 +
#1
# a2 +
#1
# a3 + ...
#For example, let us consider √23:
#√23 = 4 + √23 — 4 = 4 +
#1
# = 4 +
#1
#
#1
#√23—4
# 1 +
#√23 – 3
#7
#If we continue we would get the following expansion:
#√23 = 4 +
#1
# 1 +
#1
# 3 +
#1
# 1 +
#1
# 8 + ...
#The process can be summarised as follows:
#a0 = 4,
#1
#√23—4
# =
#√23+4
#7
# = 1 +
#√23—3
#7
#a1 = 1,
#7
#√23—3
# =
#7(√23+3)
#14
# = 3 +
#√23—3
#2
#a2 = 3,
#2
#√23—3
# =
#2(√23+3)
#14
# = 1 +
#√23—4
#7
#a3 = 1,
#7
#√23—4
# =
#7(√23+4)
#7
# = 8 + √23—4
#a4 = 8,
#1
#√23—4
# =
#√23+4
#7
# = 1 +
#√23—3
#7
#a5 = 1,
#7
#√23—3
# =
#7(√23+3)
#14
# = 3 +
#√23—3
#2
#a6 = 3,
#2
#√23—3
# =
#2(√23+3)
#14
# = 1 +
#√23—4
#7
#a7 = 1,
#7
#√23—4
# =
#7(√23+4)
#7
# = 8 + √23—4
#It can be seen that the sequence is repeating. For conciseness, we use the notation √23 = [4;(1,3,1,8)], to indicate that the block (1,3,1,8) repeats indefinitely.
#The first ten continued fraction representations of (irrational) square roots are:
#√2=[1;(2)], period=1
#√3=[1;(1,2)], period=2
#√5=[2;(4)], period=1
#√6=[2;(2,4)], period=2
#√7=[2;(1,1,1,4)], period=4
#√8=[2;(1,4)], period=2
#√10=[3;(6)], period=1
#√11=[3;(3,6)], period=2
#√12= [3;(2,6)], period=2
#√13=[3;(1,1,1,1,6)], period=5
#Exactly four continued fractions, for N ≤ 13, have an odd period.
#How many continued fractions for N ≤ 10000 have an odd period?
import math
import decimal
iterations = 0
append_list = []
frac_list = []
from decimal import *
def sqrfract(num):
getcontext().prec = 200
root = Decimal(num)**Decimal(0.5)
#root = float(math.sqrt(num))
a_0 = int(math.sqrt(num))
den = Decimal(root) - Decimal(a_0)
a_1 = (Decimal(1)/Decimal(den))
#print(a_1)
#a_1 = format(a_1, '.17')
while len(append_list) < 106:
append_list.append(a_0)
sqrfract(Decimal(a_1) ** 2)
#print(a_0, a_1)
#print(append_list)
#return append_list
return append_list[1:]
def period(fraclist):
#print(fraclist)
period = 0
i = 1
fracset = set(fraclist[:6])
fracset = fracset.union(fracset)
if len(fracset) == 1:
return 1
for j in range(2, len(fraclist)):
if fraclist[i:j] == fraclist[j:2*j-i]:
if period < (j-i):
#print('if')
period = j-i
elif period > 1:
break
else:
continue
#print('else')
return period
def sqrnum(num):
root = math.sqrt(num)
a_0 = int(math.sqrt(num))
if root - a_0 == 0:
return True
return False
total = 0
for num in range(2, 10001):
if sqrnum(num) != True:
append_list = []
#sqrfract(num)
frac_list = sqrfract(num)
repeats = period(frac_list)
#print(repeats)
if repeats % 2 != 0:
total += 1
print(total)
#print(sqrfract(2))
<file_sep>#Diophantine equation
#Problem 66
#Consider quadratic Diophantine equations of the form:
#x2 – Dy2 = 1
#For example, when D=13, the minimal solution in x is 6492 – 13×1802 = 1.
#It can be assumed that there are no solutions in positive integers when D is square.
#By finding minimal solutions in x for D = {2, 3, 5, 6, 7}, we obtain the following:
#32 – 2×22 = 1
#22 – 3×12 = 1
#92 – 5×42 = 1
#52 – 6×22 = 1
#82 – 7×32 = 1
#Hence, by considering minimal solutions in x for D ≤ 7, the largest x is obtained when D=5.
#Find the value of D ≤ 1000 in minimal solutions of x for which the largest value of x is obtained.
import math
def min_m(a, b, k, num):
min_m = 1
t = 1
m = 0
val_curr = abs(m ** 2 - num)
val_prev = val_curr + 1
while val_curr < val_prev:
val_prev = val_curr
val_curr = abs(m ** 2 - num)
m = abs(k) * t + 1
t += 1
#print(val_curr, val_prev, m)
m = abs(k) * (t - 1) + 1
return m
#Chakravala Method
def Pell(num):
a = round(math.sqrt(num))
b = 1
k = (a ** 2 - num * (b ** 2))
print(a,b,k)
print(min_m(a, b, k, num))
m = min_m(a, b, k, num)
a_new = int((a * m + num * b) / abs(k))
b_new = int((a + m * b) / abs(k))
k_new = int((m ** 2 - num)/k)
a = a_new
b = b_new
k = k_new
print(a,b,k)
print(min_m(a, b, k, num))
m = min_m(a, b, k, num)
Pell(53)
#D_List = []
#D_List = DPh_List(1000)
#print(DPh_Minimum(D_List))
#print(sqrfract(2))
<file_sep>#Double-base palindromes
#Problem 36
#The decimal number, 585 = 10010010012 (binary), is palindromic in both bases.
#Find the sum of all numbers, less than one million, which are palindromic in base 10 and base 2.
#(Please note that the palindromic number, in either base, may not include leading zeros.)
def isPalindrome(string):
length = len(string)
newstr = ''
for i in range(length - 1, -1, -1):
newstr += string[i]
if newstr == string:
return True
else:
return False
total = 0
for num in range(1, 1000000):
decstr = str(num)
binstr = str(bin(num))
binstr = binstr[2:]
if isPalindrome(decstr) == True:
if isPalindrome(binstr) == True:
total += num
print(total)
<file_sep>#Summation of primes
#Problem 10
#The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
#Find the sum of all the primes below two million.
def isPrime(n):
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
return True
def sumPrime(n):
primesum = 0
num = 2
while num < n:
if isPrime(num) == True:
primesum += num
num += 1
return primesum
print(sumPrime(2000000))
<file_sep>#Circular primes
#Problem 35
#The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime.
#There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97.
#How many circular primes are there below one million?
def isPrime(n):
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
return True
def circPrime():
circset = {2, 3, 5, 7}
for num in range(10, 1000000): #0000):
numstr = str(num)
length = len(numstr)
while length > 0:
if isPrime(num) == False:
break
length -= 1
numstr = numstr[1:] + numstr[0]
num = int(numstr)
#print(num)
if length == 0:
circset.add(num)
#print(circlist)
circset = circset.union(circset)
#print(circset)
print(len(circset))
circPrime()
<file_sep>#Digit factorials
#Problem 34
#145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145.
#Find the sum of all numbers which are equal to the sum of the factorial of their digits.
#Note: as 1! = 1 and 2! = 2 are not sums they are not included.
def fact(num):
product = 1
if num == 0:
return 1
for i in range(1, num+1):
product *= i
return product
for num in range(10, 10000000):
numstr = str(num)
total = 0
for char in numstr:
total += fact(int(char))
if total == num:
print(num)
<file_sep>#Largest palindrome product
#Problem 4
#A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
#Find the largest palindrome made from the product of two 3-digit numbers.
def isPalindrome(myString):
length = len(myString)
revString = ''
for i in range(length):
revString += myString[length - i - 1]
#print(revString)
if revString == myString:
return True
else:
return False
def Palindrome():
palindrome = 0
for i in range(999, 99, -1):
for j in range(999, 99, -1):
product = i * j
numstr = str(product)
if isPalindrome(numstr) == True:
if palindrome < product:
palindrome = product
return palindrome
print(Palindrome())
<file_sep>#Factorial digit sum
#Problem 20
#n! means n × (n − 1) × ... × 3 × 2 × 1
#For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800,
#and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
#Find the sum of the digits in the number 100!
def factorial(num):
mult = 1
for n in range(1, num+1):
mult *= n
return mult
def digitsum(num):
numstr = str(factorial(num))
total = 0
for char in numstr:
total += int(char)
print(total)
digitsum(100)
<file_sep>#Reciprocal cycles
#Problem 26
#A unit fraction contains 1 in the numerator. The decimal representation of the unit fractions with denominators 2 to 10 are given:
#1/2 = 0.5
#1/3 = 0.(3)
#1/4 = 0.25
#1/5 = 0.2
#1/6 = 0.1(6)
#1/7 = 0.(142857)
#1/8 = 0.125
#1/9 = 0.(1)
#1/10 = 0.1
#Where 0.1(6) means 0.166666..., and has a 1-digit recurring cycle. It can be seen that 1/7 has a 6-digit recurring cycle.
#Find the value of d < 1000 for which 1/d contains the longest recurring cycle in its decimal fraction part.
import time
from decimal import *
getcontext().prec = 1500 #or 1500
max_num = 0
max_repeat = 0
for i in range(2, 1000):
quot = Decimal(1) / Decimal(i)
quot_str = str(quot)
length = len(quot_str)
if length > 1000:
start_index = 2
a = start_index
b = start_index + 1
while a < (start_index + 5): # a = 2 / 3 / 4 / 5 / 6
if quot_str[a] == quot_str[b] and quot_str[a+1] == quot_str[b+1] and quot_str[a+2] == quot_str[b+2]: #Check for 3 character matches
break
else:
b += 1
if b == length - 2:
a += 1
b = a + 1
repeat = b - a
if repeat > max_repeat:
max_repeat = repeat
max_num = i
print('Number of digits in repetition: ' + str(max_repeat) + '; d: ' + str(max_num))
<file_sep>#Longest Collatz sequence
#Problem 14
#The following iterative sequence is defined for the set of positive integers:
#n → n/2 (n is even)
#n → 3n + 1 (n is odd)
#Using the rule above and starting with 13, we generate the following sequence:
#13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
#It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.
#Which starting number, under one million, produces the longest chain?
#NOTE: Once the chain starts the terms are allowed to go above one million.
def lencollatz(num):
total = 1
localnum = num
while localnum != 1:
if localnum % 2 == 0:
localnum /= 2
else:
localnum = 3 * localnum + 1
#print(localnum)
total += 1
return total
maxlen = 1
maxnum = 1
for i in range(1, 1000000):
if maxlen < lencollatz(i):
maxlen = lencollatz(i)
maxnum = i
print(maxnum, maxlen)
<file_sep>#Goldbach's other conjecture
#Problem 46
#It was proposed by <NAME> that every odd composite number can be written as the sum of a prime and twice a square.
#9 = 7 + 2×12
#15 = 7 + 2×22
#21 = 3 + 2×32
#25 = 7 + 2×32
#27 = 19 + 2×22
#33 = 31 + 2×12
#It turns out that the conjecture was false.
#What is the smallest odd composite that cannot be written as the sum of a prime and twice a square?
def isPrime(n):
if n == 0 or n == 1:
return False
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
return True
for num in range(3, 10000, 2):
if isPrime(num) == True:
continue
sqr_list = []
i = 1
inj = 0
while inj < num:
inj = int(2 * (i ** 2))
if inj < num:
sqr_list.append(inj)
i += 1
#print('Sqr List')
#print(sqr_list)
prime_list = []
for k in range(3, num, 2):
if isPrime(k) == True:
prime_list.append(k)
#print('Prime List')
#print(prime_list)
times = 0
for j in prime_list:
diff = int(num - j)
#print('Diff is')
#print(diff)
if diff in sqr_list:
times += 1
if times == 0:
print(num)
<file_sep>#Sub-string divisibility
#Problem 43
#The number, 1406357289, is a 0 to 9 pandigital number because it is made up of each of the digits 0 to 9 in some order, but it also has a rather interesting sub-string divisibility property.
#Let d1 be the 1st digit, d2 be the 2nd digit, and so on. In this way, we note the following:
#d2d3d4=406 is divisible by 2
#d3d4d5=063 is divisible by 3
#d4d5d6=635 is divisible by 5
#d5d6d7=357 is divisible by 7
#d6d7d8=572 is divisible by 11
#d7d8d9=728 is divisible by 13
#d8d9d10=289 is divisible by 17
#Find the sum of all 0 to 9 pandigital numbers with this property.
import itertools
numlist = ['0','1','2', '3', '4', '5', '6', '7', '8', '9']
permutations_str = list(itertools.permutations(numlist))
string_list = []
for num in range(len(permutations_str)):
newstr = ''
for element in range(len(numlist)):
newstr += permutations_str[num][element]
if newstr[0] != '0':
string_list.append(newstr)
total = 0
for numstr in string_list:
#numstr = str(num)
if int(numstr[1:4]) % 2 == 0 and int(numstr[2:5]) % 3 == 0 and int(numstr[3:6]) % 5 == 0 and int(numstr[4:7]) % 7 == 0 and int(numstr[5:8]) % 11 == 0 and int(numstr[6:9]) % 13 == 0 and int(numstr[7:]) % 17 == 0:
total += int(numstr)
print(total)
#def isPanDigital(mystr):
# length = len(mystr)
#
# if length != 10:
# return False
#for char in mystr:
# if int(char) > length:
# return False
#strdict = {}
#for i in range(0, 10):
# strdict[str(i)] = 0
#print(strdict)
#for char in mystr:
# strdict[char] = strdict[char] + 1
#print(strdict)
#for k, v in strdict.items():
# if v != 1:
# return False
#return True
<file_sep>#Pandigital products
#Problem 32
#We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once; for example, the 5-digit number, 15234, is 1 through 5 pandigital.
#The product 7254 is unusual, as the identity, 39 × 186 = 7254, containing multiplicand, multiplier, and product is 1 through 9 pandigital.
#Find the sum of all products whose multiplicand/multiplier/product identity can be written as a 1 through 9 pandigital.
#HINT: Some products can be obtained in more than one way so be sure to only include it once in your sum.
def isPanDigital(mystr):
strdict = {'0':0, '1':0,'2':0,'3':0,'4':0,'5':0,'6':0,'7':0,'8':0,'9':0}
for char in mystr:
strdict[char] = strdict[char] + 1
#print(strdict)
for k, v in strdict.items():
if k != '0':
if v != 1:
return False
if strdict['0'] != 0:
return False
return True
myStr = ''
mySet = {0}
for a in range(10000):
for b in range(1000):
product = a * b
myStr = str(product) + str(a) + str(b)
#print(myStr)
if isPanDigital(myStr) == True:
mySet.add(product)
#print(str(a) + ' X ' + str(b) + ' = ' + str(product))
mySet = mySet.union(mySet)
#print(mySet)
total = 0
for num in mySet:
total += num
print(total)
<file_sep>#Square root convergents
#Problem 57
#It is possible to show that the square root of two can be expressed as an infinite continued fraction.
#√ 2 = 1 + 1/(2 + 1/(2 + 1/(2 + ... ))) = 1.414213...
#By expanding this for the first four iterations, we get:
#1 + 1/2 = 3/2 = 1.5
#1 + 1/(2 + 1/2) = 7/5 = 1.4
#1 + 1/(2 + 1/(2 + 1/2)) = 17/12 = 1.41666...
#1 + 1/(2 + 1/(2 + 1/(2 + 1/2))) = 41/29 = 1.41379...
#The next three expansions are 99/70, 239/169, and 577/408, but the eighth expansion, 1393/985, is the first example where the number of digits in the numerator exceeds the number of digits in the denominator.##
#In the first one-thousand expansions, how many fractions contain a numerator with more digits than denominator?
def Digits(num):
numstr = str(num)
return len(numstr)
total = 0
num = 3
den = 2
for i in range(1000):
den_prev = den
den = num + den
num = den_prev + den
#print(num, den)
if Digits(num) > Digits(den):
total += 1
print(total)
<file_sep>#Highly divisible triangular number
#Problem 12
#The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:
#1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
#Let us list the factors of the first seven triangle numbers:
# 1: 1
# 3: 1,3
# 6: 1,2,3,6
#10: 1,2,5,10
#15: 1,3,5,15
#21: 1,3,7,21
#28: 1,2,4,7,14,28
#We can see that 28 is the first triangle number to have over five divisors.
#What is the value of the first triangle number to have over five hundred divisors?
import time
# returns the nth triangle number; that is, the sum of all the natural numbers less than, or equal to, n
def triangleNumber(n):
return sum ( [ i for i in range(1, n + 1) ] )
start = int(round(time.time() * 1000)) # starts the stopwatch
j = 0 # j represents the jth triangle number
n = 0 # n represents the triangle number corresponding to j
numberOfDivisors = 0 # number of divisors for triangle number n
while numberOfDivisors <= 500:
# resets numberOfDivisors because it's now checking a new triangle number
# and also sets n to be the next triangle number
numberOfDivisors = 0
j += 1
n = triangleNumber(j)
# for every number from 1 to the square root of this triangle number,
# count the number of divisors
i = 1
while i <= n**0.5:
if n % i == 0:
numberOfDivisors += 1
i += 1
# 1 to the square root of the number holds exactly half of the divisors
# so multiply it by 2 to include the other corresponding half
numberOfDivisors *= 2
finish = int(round(time.time() * 1000)) # stops the stopwatch
print (n)
print ("Time taken: " + str(finish-start) + " milliseconds")
#def len_factors(number):
# factors_list = [n for n in range(1, number + 1) if number % n == 0]
# print(len(factors_list))
# return len(factors_list)
#def highTriangle():
# for i in range(2000, 4000):
# i = 100000
# sigma = int(i * (i+1) / 2)
# print(sigma)
# if len_factors(sigma) > 500:
# return sigma
#print(highTriangle())
<file_sep>#Smallest multiple
#Problem 5
#2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
#What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
def gcd(a, b):
temp = 0
while b != 0:
t = b
b = a % b
a = t
return a
def lcm(a, b):
return (a * b) / gcd(a, b)
def lcmm(numlist):
if len(numlist) == 2:
return lcm(numlist[0], numlist[1])
else:
a = numlist[0]
numlist[0:] = numlist[1:]
return lcm(a, lcmm(numlist))
numlist = []
for i in range(1, 21):
numlist.append(i)
print(lcmm(numlist))
<file_sep>#Distinct primes factors
#Problem 47
#The first two consecutive numbers to have two distinct prime factors are:
#14 = 2 × 7
#15 = 3 × 5
#The first three consecutive numbers to have three distinct prime factors are:
#644 = 2² × 7 × 23
#645 = 3 × 5 × 43
#646 = 2 × 17 × 19.
#Find the first four consecutive integers to have four distinct prime factors. What is the first of these numbers?
#Ans: 134043
def isPrime(n):#
if n == 0 or n == 1:
return False
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
return True
def get_factors(number):
return [n for n in range(2, number) if number % n == 0 and isPrime(n) == True]
new_dict = {}
def get_all_factors(numbers_set):
#for i in numbers_set:
# new_dict[i] = get_factors(i)
#print(new_dict)
new_dict = {i:get_factors(i) for i in numbers_set}
return new_dict
#print(get_all_factors({14, 15}))
#print(get_all_factors({644, 645, 646}))
for i in range(130000, 140000):
a = i
b = i + 1
c = i + 2
d = i + 3
my_dict = get_all_factors({a,b,c,d})
total = 0
for k, v in my_dict.items():
if len(v) >= 4:
total += 1
if total == 4:
print(a)
<file_sep>#Prime digit replacements
#Problem 51
#By replacing the 1st digit of the 2-digit number *3, it turns out that six of the nine possible values: 13, 23, 43, 53, 73, and 83, are all prime.
#By replacing the 3rd and 4th digits of 56**3 with the same digit, this 5-digit number is the first example having seven primes among the ten generated numbers, yielding the family: 56003, 56113, 56333, 56443, 56663, 56773, and 56993. Consequently 56003, being the first member of this family, is the smallest prime with this property.
#Find the smallest prime which, by replacing part of the number (not necessarily adjacent digits) with the same digit, is part of an eight prime value family.
#Starting number and last prime can help in deducing first prime
def isPrime(n):
if n == 0 or n == 1:
return False
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
return True
prime_list = []
for num in range(100000, 200000):
if isPrime(num) == True:
prime_list.append(num)
#print(prime_list)
#print(len(prime_list))
for num in prime_list:
numstr = str(num)
length = len(numstr)
#1 digits
#1st digit
numprimes = 0
newstr = ''
for i in range(1, 10):
newstr = str(i) + numstr[1:]
newnum = int(newstr)
#print(num, newnum)
if isPrime(newnum) == True:
numprimes += 1
if numprimes >= 8:
print(num, newnum)
break
#2nd digit
numprimes = 0
newstr = ''
for i in range(10):
newstr = numstr[0] + str(i) + numstr[2:]
newnum = int(newstr)
#print(num, newnum)
if isPrime(newnum) == True:
numprimes += 1
if numprimes >= 8:
print(num, newnum)
break
#From 3rd digit
for k in range(2, length):
numprimes = 0
newstr = ''
for i in range(10):
newstr = numstr[0:k] + str(i) + numstr[k+1:]
newnum = int(newstr)
#print(num, newnum)
if isPrime(newnum) == True:
numprimes += 1
if numprimes >= 8:
print(num, newnum)
break
#2 digits
#6C2
numprimes = 0
newstr = ''
for i in range(1, 10): #1,2
newstr = str(i) + str(i) + numstr[2:]
newnum = int(newstr)
#print(num, newnum)
if isPrime(newnum) == True:
numprimes += 1
if numprimes >= 8:
print(num, newnum)
break
numprimes = 0
newstr = ''
for i in range(1, 10): #1,3
newstr = str(i) + numstr[1] + str(i) + numstr[3:]
newnum = int(newstr)
#print(num, newnum)
if isPrime(newnum) == True:
numprimes += 1
if numprimes >= 8:
print(num, newnum)
break
for j in range(3, length):
numprimes = 0
newstr = ''
for i in range(1, 10): #1,4..
newstr = str(i) + numstr[1:j] + str(i) + numstr[j+1:]
newnum = int(newstr)
#print(num, newnum)
if isPrime(newnum) == True:
numprimes += 1
if numprimes >= 8:
print(num, newnum)
break
numprimes = 0
newstr = ''
for i in range(10): #2,3
newstr = numstr[0] + str(i) + str(i) + numstr[3:]
newnum = int(newstr)
#print(num, newnum)
if isPrime(newnum) == True:
numprimes += 1
if numprimes >= 8:
print(num, newnum)
break
for j in range(3, length):
numprimes = 0
newstr = ''
for i in range(10): #2,4..
newstr = numstr[0] + str(i) + numstr[2:j] + str(i) + numstr[j+1:]
newnum = int(newstr)
#print(num, newnum)
if isPrime(newnum) == True:
numprimes += 1
if numprimes >= 8:
print(num, newnum)
break
numprimes = 0
newstr = ''
for i in range(10): #3,4
newstr = numstr[0:2] + str(i) + str(i) + numstr[4:]
newnum = int(newstr)
#print(num, newnum)
if isPrime(newnum) == True:
numprimes += 1
if numprimes >= 8:
print(num, newnum)
break
for j in range(4, length):
numprimes = 0
newstr = ''
for i in range(10): #3,5..
newstr = numstr[0:2] + str(i) + numstr[3:j] + str(i) + numstr[j+1:]
newnum = int(newstr)
#print(num, newnum)
if isPrime(newnum) == True:
numprimes += 1
if numprimes >= 8:
print(num, newnum)
break
numprimes = 0
newstr = ''
for i in range(10): #4,5
newstr = numstr[0:3] + str(i) + str(i) + numstr[5:]
newnum = int(newstr)
#print(num, newnum)
if isPrime(newnum) == True:
numprimes += 1
if numprimes >= 8:
print(num, newnum)
break
numprimes = 0
newstr = ''
for i in range(10): #4,6
newstr = numstr[0:3] + str(i) + numstr[4] + str(i)
newnum = int(newstr)
#print(num, newnum)
if isPrime(newnum) == True:
numprimes += 1
if numprimes >= 8:
print(num, newnum)
break
numprimes = 0
newstr = ''
for i in range(10): #5,6
newstr = numstr[0:4] + str(i) + str(i)
newnum = int(newstr)
#print(num, newnum)
if isPrime(newnum) == True:
numprimes += 1
if numprimes >= 8:
print(num, newnum)
break
#3 digits
#5C3
numprimes = 0
newstr = ''
for i in range(1, 10): #1,2,3
newstr = str(i) + str(i) + str(i) + numstr[3:]
newnum = int(newstr)
#print(num, newnum)
if isPrime(newnum) == True:
numprimes += 1
if numprimes >= 8:
print(num, newnum)
break
for j in range(3, length):
numprimes = 0
newstr = ''
for i in range(1, 10): #1,2,4..
newstr = str(i) + str(i) + numstr[2:j] + str(i) + numstr[j+1:]
newnum = int(newstr)
#print(num, newnum)
if isPrime(newnum) == True:
numprimes += 1
if numprimes >= 8:
print(num, newnum)
break
numprimes = 0
newstr = ''
for i in range(1, 10): #1,3,4
newstr = str(i) + numstr[1] + str(i) + str(i) + numstr[4:]
newnum = int(newstr)
#print(num, newnum)
if isPrime(newnum) == True:
numprimes += 1
if numprimes >= 8:
print(num, newnum)
break
numprimes = 0
newstr = ''
for i in range(1, 10): #1,3,5
newstr = str(i) + numstr[1] + str(i) + numstr[3] + str(i) + numstr[5]
newnum = int(newstr)
#print(num, newnum)
if isPrime(newnum) == True:
numprimes += 1
if numprimes >= 8:
print(num, newnum)
break
numprimes = 0
newstr = ''
for i in range(1, 10): #1,3,6
newstr = str(i) + numstr[1] + str(i) + numstr[3:5] + str(i)
newnum = int(newstr)
#print(num, newnum)
if isPrime(newnum) == True:
numprimes += 1
if numprimes >= 8:
print(num, newnum)
break
numprimes = 0
newstr = ''
for i in range(1, 10): #1,4,5
newstr = str(i) + numstr[1:3] + str(i) + str(i) + numstr[5]
newnum = int(newstr)
#print(num, newnum)
if isPrime(newnum) == True:
numprimes += 1
if numprimes >= 8:
print(num, newnum)
break
numprimes = 0
newstr = ''
for i in range(1, 10): #1,4,6
newstr = str(i) + numstr[1:3] + str(i) + numstr[4] + str(i)
newnum = int(newstr)
#print(num, newnum)
if isPrime(newnum) == True:
numprimes += 1
if numprimes >= 8:
print(num, newnum)
break
numprimes = 0
newstr = ''
for i in range(1, 10): #1,5,6
newstr = str(i) + numstr[1:4] + str(i) + str(i)
newnum = int(newstr)
#print(num, newnum)
if isPrime(newnum) == True:
numprimes += 1
if numprimes >= 8:
print(num, newnum)
break
numprimes = 0
newstr = ''
for i in range(10): #2,3,4
newstr = numstr[0] + str(i) + str(i) + str(i) + numstr[4:]
newnum = int(newstr)
#print(num, newnum)
if isPrime(newnum) == True:
numprimes += 1
if numprimes >= 8:
print(num, newnum)
break
numprimes = 0
newstr = ''
for i in range(10): #2,3,5
newstr = numstr[0] + str(i) + str(i) + numstr[3] + str(i) + numstr[5:]
newnum = int(newstr)
#print(num, newnum)
if isPrime(newnum) == True:
numprimes += 1
if numprimes >= 8:
print(num, newnum)
break
numprimes = 0
newstr = ''
for i in range(10): #2,3,6
newstr = numstr[0] + str(i) + str(i) + numstr[3:5] + str(i)
newnum = int(newstr)
#print(num, newnum)
if isPrime(newnum) == True:
numprimes += 1
if numprimes >= 8:
print(num, newnum)
break
numprimes = 0
newstr = ''
for i in range(10): #2,4,5
newstr = numstr[0] + str(i) + numstr[2] + str(i) + str(i) + numstr[5:]
newnum = int(newstr)
#print(num, newnum)
if isPrime(newnum) == True:
numprimes += 1
if numprimes >= 8:
print(num, newnum)
break
numprimes = 0
newstr = ''
for i in range(10): #2,4,6
newstr = numstr[0] + str(i) + numstr[2] + str(i) + numstr[4] + str(i)
newnum = int(newstr)
#print(num, newnum)
if isPrime(newnum) == True:
numprimes += 1
if numprimes >= 8:
print(num, newnum)
break
numprimes = 0
newstr = ''
for i in range(10): #2,5,6
newstr = numstr[0] + str(i) + numstr[2:4] + str(i) + str(i)
newnum = int(newstr)
#print(num, newnum)
if isPrime(newnum) == True:
numprimes += 1
if numprimes >= 8:
print(num, newnum)
break
numprimes = 0
newstr = ''
for i in range(10): #3,4,5
newstr = numstr[0:2] + str(i) + str(i) + str(i) + numstr[5:]
newnum = int(newstr)
#print(num, newnum)
if isPrime(newnum) == True:
numprimes += 1
if numprimes >= 8:
print(num, newnum)
break
numprimes = 0
newstr = ''
for i in range(10): #3,4,6
newstr = numstr[0:2] + str(i) + str(i) + numstr[4] + str(i)
newnum = int(newstr)
#print(num, newnum)
if isPrime(newnum) == True:
numprimes += 1
if numprimes >= 8:
print(num, newnum)
break
numprimes = 0
newstr = ''
for i in range(10): #3,5,6
newstr = numstr[0:2] + str(i) + numstr[3] + str(i) + str(i)
newnum = int(newstr)
#print(num, newnum)
if isPrime(newnum) == True:
numprimes += 1
if numprimes >= 8:
print(num, newnum)
break
numprimes = 0
newstr = ''
for i in range(10): #4,5,6
newstr = numstr[0:3] + str(i) + str(i) + str(i)
newnum = int(newstr)
#print(num, newnum)
if isPrime(newnum) == True:
numprimes += 1
if numprimes >= 8:
print(num, newnum)
break
#4 digits
#6C4
numprimes = 0
newstr = ''
for i in range(1,10): #1,2,3,4
newstr = str(i) + str(i) + str(i) + str(i) + numstr[4:]
newnum = int(newstr)
#print(num, newnum)
if isPrime(newnum) == True:
numprimes += 1
if numprimes >= 8:
print(num, newnum)
break
numprimes = 0
newstr = ''
for i in range(1,10): #1,2,3,5
newstr = str(i) + str(i) + str(i) + numstr[3] + str(i) + numstr[5]
newnum = int(newstr)
#print(num, newnum)
if isPrime(newnum) == True:
numprimes += 1
if numprimes >= 8:
print(num, newnum)
break
numprimes = 0
newstr = ''
for i in range(1,10): #1,2,3,6
newstr = str(i) + str(i) + str(i) + numstr[3:5] + str(i)
newnum = int(newstr)
#print(num, newnum)
if isPrime(newnum) == True:
numprimes += 1
if numprimes >= 8:
print(num, newnum)
break
numprimes = 0
newstr = ''
for i in range(1,10): #1,2,4,5
newstr = str(i) + str(i) + numstr[2] + str(i) + str(i) + numstr[5]
newnum = int(newstr)
#print(num, newnum)
if isPrime(newnum) == True:
numprimes += 1
if numprimes >= 8:
print(num, newnum)
break
numprimes = 0
newstr = ''
for i in range(1,10): #1,2,4,6
newstr = str(i) + str(i) + numstr[2] + str(i) + numstr[4] + str(i)
newnum = int(newstr)
#print(num, newnum)
if isPrime(newnum) == True:
numprimes += 1
if numprimes >= 8:
print(num, newnum)
break
numprimes = 0
newstr = ''
for i in range(1,10): #1,2,5,6
newstr = str(i) + str(i) + numstr[2:4] + str(i) + str(i)
newnum = int(newstr)
#print(num, newnum)
if isPrime(newnum) == True:
numprimes += 1
if numprimes >= 8:
print(num, newnum)
break
numprimes = 0
newstr = ''
for i in range(1,10): #1,3,4,5
newstr = str(i) + numstr[1] + str(i) + str(i) + str(i) + numstr[5]
newnum = int(newstr)
#print(num, newnum)
if isPrime(newnum) == True:
numprimes += 1
if numprimes >= 8:
print(num, newnum)
break
numprimes = 0
newstr = ''
for i in range(1,10): #1,3,4,6
newstr = str(i) + numstr[1] + str(i) + str(i) + numstr[4] + str(i)
newnum = int(newstr)
#print(num, newnum)
if isPrime(newnum) == True:
numprimes += 1
if numprimes >= 8:
print(num, newnum)
break
numprimes = 0
newstr = ''
for i in range(1,10): #1,3,5,6
newstr = str(i) + numstr[1] + str(i) + numstr[3] + str(i) + str(i)
newnum = int(newstr)
#print(num, newnum)
if isPrime(newnum) == True:
numprimes += 1
if numprimes >= 8:
print(num, newnum)
break
numprimes = 0
newstr = ''
for i in range(1,10): #1,4,5,6
newstr = str(i) + numstr[1:3] + str(i) + str(i) + str(i)
newnum = int(newstr)
#print(num, newnum)
if isPrime(newnum) == True:
numprimes += 1
if numprimes >= 8:
print(num, newnum)
break
numprimes = 0
newstr = ''
for i in range(10): #2,3,4,5
newstr = numstr[0] + str(i) + str(i) + str(i) + str(i) + numstr[5]
newnum = int(newstr)
#print(num, newnum)
if isPrime(newnum) == True:
numprimes += 1
if numprimes >= 8:
print(num, newnum)
break
numprimes = 0
newstr = ''
for i in range(10): #2,3,4,6
newstr = numstr[0] + str(i) + str(i) + str(i) + numstr[4] + str(i)
newnum = int(newstr)
#print(num, newnum)
if isPrime(newnum) == True:
numprimes += 1
if numprimes >= 8:
print(num, newnum)
break
numprimes = 0
newstr = ''
for i in range(10): #2,3,5,6
newstr = numstr[0] + str(i) + str(i) + numstr[3] + str(i) + str(i)
newnum = int(newstr)
#print(num, newnum)
if isPrime(newnum) == True:
numprimes += 1
if numprimes >= 8:
print(num, newnum)
break
numprimes = 0
newstr = ''
for i in range(10): #2,4,5,6
newstr = numstr[0] + str(i) + numstr[2] + str(i) + str(i) + str(i)
newnum = int(newstr)
#print(num, newnum)
if isPrime(newnum) == True:
numprimes += 1
if numprimes >= 8:
print(num, newnum)
break
numprimes = 0
newstr = ''
for i in range(10): #3,4,5,6
newstr = numstr[0:2] + str(i) + str(i) + str(i) + str(i)
newnum = int(newstr)
#print(num, newnum)
if isPrime(newnum) == True:
numprimes += 1
if numprimes >= 8:
print(num, newnum)
break
#5 digits
#6C5
numprimes = 0
newstr = ''
for i in range(10): #1,2,3,4,5
newstr = str(i) + str(i) + str(i) + str(i) + str(i) + numstr[5]
newnum = int(newstr)
#print(num, newnum)
if isPrime(newnum) == True:
numprimes += 1
if numprimes >= 8:
print(num, newnum)
break
numprimes = 0
newstr = ''
for i in range(10): #1,2,3,4,6
newstr = str(i) + str(i) + str(i) + str(i) + numstr[4] + str(i)
newnum = int(newstr)
#print(num, newnum)
if isPrime(newnum) == True:
numprimes += 1
if numprimes >= 8:
print(num, newnum)
break
numprimes = 0
newstr = ''
for i in range(10): #1,2,3,5,6
newstr = str(i) + str(i) + str(i) + numstr[3] + str(i) + str(i)
newnum = int(newstr)
#print(num, newnum)
if isPrime(newnum) == True:
numprimes += 1
if numprimes >= 8:
print(num, newnum)
break
numprimes = 0
newstr = ''
for i in range(10): #1,2,4,5,6
newstr = str(i) + str(i) + numstr[2] + str(i) + str(i) + str(i)
newnum = int(newstr)
#print(num, newnum)
if isPrime(newnum) == True:
numprimes += 1
if numprimes >= 8:
print(num, newnum)
break
numprimes = 0
newstr = ''
for i in range(10): #1,3,4,5,6
newstr = str(i) + numstr[1] + str(i) + str(i) + str(i) + str(i)
newnum = int(newstr)
#print(num, newnum)
if isPrime(newnum) == True:
numprimes += 1
if numprimes >= 8:
print(num, newnum)
break
numprimes = 0
newstr = ''
for i in range(10): #2,3,4,5,6
newstr = numstr[0] + str(i) + str(i) + str(i) + str(i) + str(i)
newnum = int(newstr)
#print(num, newnum)
if isPrime(newnum) == True:
numprimes += 1
if numprimes >= 8:
print(num, newnum)
break
<file_sep>#Permuted multiples
#Problem 52
#It can be seen that the number, 125874, and its double, 251748, contain exactly the same digits, but in a different order.
#Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits.
def digitdict(mystr):
length = len(mystr)
strdict = {}
for i in range(0, 10):
strdict[str(i)] = 0
#print(strdict)
for char in mystr:
strdict[char] = strdict[char] + 1
return strdict
for num in range(100000, 1000000):
dict_1 = digitdict(str(num * 1))
dict_2 = digitdict(str(num * 2))
dict_3 = digitdict(str(num * 3))
dict_4 = digitdict(str(num * 4))
dict_5 = digitdict(str(num * 5))
dict_6 = digitdict(str(num * 6))
if dict_1 == dict_2 and dict_3 == dict_4 and dict_5 == dict_6:
if dict_1 == dict_3 and dict_1 == dict_5:
print(num)
<file_sep>#Number spiral diagonals
#Problem 28
#Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows:
#21 22 23 24 25
#20 7 8 9 10
#19 6 1 2 11
#18 5 4 3 12
#17 16 15 14 13
#It can be verified that the sum of the numbers on the diagonals is 101.
#What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral formed in the same way?
#1, 3, 5, 7, 9, 13, 17, 21, 25........
def spiralDiagSum(num):
total = 0
rval = 1
lval = 1
for i in range(num):
rval += 2 * (i)
if i%2 == 0:
lval += 4 * (i/2)
else:
lval += 4 * (i+1)/2
total += (int(lval) + rval)
#print(int(lval), rval)
return total - 1
print(spiralDiagSum(1001))
<file_sep>#Prime permutations
#Problem 49
#The arithmetic sequence, 1487, 4817, 8147, in which each of the terms increases by 3330, is unusual in two ways: (i) each of the three terms are prime, and, (ii) each of the 4-digit numbers are permutations of one another.
#There are no arithmetic sequences made up of three 1-, 2-, or 3-digit primes, exhibiting this property, but there is one other 4-digit increasing sequence.
#What 12-digit number do you form by concatenating the three terms in this sequence?
##################################################################
#Generate a list of primes below between 1000 and 10000.
#Take two primes i and j with i < j and calculate k = j + (j-i).
#Check if k < 10000 and check if k is a prime, if not go to 2.
#Check if i and j are permutations of each other and check if i and k are permutations of each other. If not go to 2.
#Found the triple, so exit.
###################################################################
import itertools
numstr = ''
def digits(num):
numdigits = {}
for a in range(10):
numdigits[a] = 0
numstr = str(num)
for char in numstr:
b = int(char)
numdigits[b] += 1
return numdigits
def isPrime(n):#
if n == 0 or n == 1:
return False
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
return True
prime_list = []
for num in range(1000, 10000):
if isPrime(num) == True:
prime_list.append(num)
#print(prime_list)
#print(len(prime_list))
for i in range(len(prime_list) - 1):
for j in range(i+1, len(prime_list)):
k = prime_list[j] + prime_list[j] - prime_list[i]
if k not in prime_list:
continue
i_dict = digits(prime_list[i])
j_dict = digits(prime_list[j])
k_dict = digits(k)
if i_dict == j_dict:
if i_dict == k_dict:
print(prime_list[i], prime_list[j], k)
<file_sep>#Digit fifth powers
#Problem 30
#Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits:
#1634 = 14 + 64 + 34 + 44
#8208 = 84 + 24 + 04 + 84
#9474 = 94 + 44 + 74 + 44
#As 1 = 14 is not a sum it is not included.
#The sum of these numbers is 1634 + 8208 + 9474 = 19316.
#Find the sum of all the numbers that can be written as the sum of fifth powers of their digits.
result_list = []
total = 0
for num in range(2, 1000000):
digit_sum = 0
numstr = str(num)
for char in numstr:
digit_sum += (int(char) ** 5)
if num == digit_sum:
total += num
#result_list.append(num)
#print(result_list)
print(total)
<file_sep>#Diophantine equation
#Problem 66
#Consider quadratic Diophantine equations of the form:
#x2 – Dy2 = 1
#For example, when D=13, the minimal solution in x is 6492 – 13×1802 = 1.
#It can be assumed that there are no solutions in positive integers when D is square.
#By finding minimal solutions in x for D = {2, 3, 5, 6, 7}, we obtain the following:
#32 – 2×22 = 1
#22 – 3×12 = 1
#92 – 5×42 = 1
#52 – 6×22 = 1
#82 – 7×32 = 1
#Hence, by considering minimal solutions in x for D ≤ 7, the largest x is obtained when D=5.
#Find the value of D ≤ 1000 in minimal solutions of x for which the largest value of x is obtained.
import math
def isSqrNum(num):
root = int(math.sqrt(num))
if num != root ** 2:
return False
return True
def DPh_List(num):
d_list = []
for i in range(num+1):
if isSqrNum(i) == False:
d_list.append(i)
return d_list
def DPh_Minimum(DPh_List):
new_D = 0
max_x = 0
for DPh in DPh_List:
y = 1
soln = 3
while isSqrNum(soln) != True:
soln = DPh * (y**2) + 1
y += 1
x = int(math.sqrt(soln))
if max_x < x:
max_x = x
new_D = DPh
return new_D
D_List = []
D_List = DPh_List(1000)
print(DPh_Minimum(D_List))
<file_sep>#Special Pythagorean triplet
#Problem 9
#A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
#a2 + b2 = c2
#For example, 32 + 42 = 9 + 16 = 25 = 52.
#There exists exactly one Pythagorean triplet for which a + b + c = 1000.
#Find the product abc.
def isPythoTriplet(x, y, z):
c = max(x, y, z)
a = min(x, y, z)
b = (x+y+z) - (a+c)
if (a*a + b*b) == c*c:
return True
else:
return False
for a in range(1, 1000):
for b in range(1, 1000):
for c in range(1, 1000):
if a + b + c == 1000:
if isPythoTriplet(a, b, c) == True:
print(a*b*c)
<file_sep>#Number letter counts
#Problem 17
#If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.
#If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used?
#NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of "and" when writing out numbers is in compliance with British usage.
numletter_dict = {0:'',1:'one',2:'two',3:'three',4:'four',5:'five',6:'six',7:'seven',8:'eight',9:'nine',10:'ten',11:'eleven',12:'twelve',13:'thirteen',14:'fourteen',15:'fifteen',16:'sixteen',17:'seventeen',18:'eighteen',19:'nineteen',20:'twenty',30:'thirty',40:'forty',50:'fifty',60:'sixty',70:'seventy',80:'eighty',90:'ninety',100:'hundred'}
def numstr(number):
wordstr = ''
numstr = ''
if number < 21:
wordstr += numletter_dict[number]
return wordstr
if number < 100:
numstr = str(number)
unit = numstr[1]
tenstr = numstr[0] + '0'
#print(unit)
wordstr += numletter_dict[int(tenstr)]
wordstr += numletter_dict[int(unit)]
return wordstr
elif number == 1000:
wordstr += 'onethousand'
return wordstr
else:
numstr = str(number)
unit = numstr[2]
tenstr = numstr[1] + '0'
hunstr = numstr[0]
wordstr += numletter_dict[int(hunstr)]
wordstr += numletter_dict[100]
if tenstr[0] == '1':
wordstr += 'and'
wordstr += numletter_dict[int(tenstr[0] + unit)]
elif tenstr != '00':
wordstr += 'and'
wordstr += numletter_dict[int(tenstr)]
wordstr += numletter_dict[int(unit)]
if tenstr == '00' and unit != '0':
wordstr += 'and'
wordstr += numletter_dict[int(unit)]
return wordstr
total = 0
for i in range(1,1001):
total += len(numstr(i))
print(total)
for i in range(900,1001):
print(numstr(i), len(numstr(i)))
<file_sep>#Lattice paths
#Problem 15
#Starting in the top left corner of a 2×2 grid, and only being able to move to the right and down, there are exactly 6 routes to the bottom right corner.
#How many such routes are there through a 20×20 grid?
#m ways to traverse on left, n ways to traverse up, m+n ways to traverse the last node
# n
#m m+n
#Hence 6 X 6 grid - ways matrix
#1 1 1 1 1 1
#1 2 3 4 5 6
#1 3 6 10 15 21
#1 4 10 20 35 56
#1 5 15 35 70 126
#1 6 21 56 126 252
def latticeMatrix(num):
myMatrix = []
zerolist = []
for i in range(num):
zerolist.append(0)
for j in range(num):
myMatrix.append(zerolist)
for a in range(num):
myMatrix[a][0] = 1
myMatrix[0][a] = 1
for i in range(1, num):
for j in range(1, num):
myMatrix[i][j] = myMatrix[i-1][j] + myMatrix[i][j-1]
print(myMatrix[0])
latticeMatrix(21)
<file_sep>#Digit cancelling fractions
#Problem 33
#The fraction 49/98 is a curious fraction, as an inexperienced mathematician in attempting to simplify it may incorrectly believe that 49/98 = 4/8, which is correct, is obtained by cancelling the 9s.
#We shall consider fractions like, 30/50 = 3/5, to be trivial examples.
#There are exactly four non-trivial examples of this type of fraction, less than one in value, and containing two digits in the numerator and denominator.
#If the product of these four fractions is given in its lowest common terms, find the value of the denominator.
def reduce(num, den):
numstr = str(num)
denstr = str(den)
if numstr[0] == denstr[0]:
num = int(numstr[1])
den = int(denstr[1])
elif numstr[1] == denstr[1]:
num = int(numstr[0])
den = int(denstr[0])
elif numstr[0] == denstr[1]:
num = int(numstr[1])
den = int(denstr[0])
elif numstr[1] == denstr[0]:
num = int(numstr[0])
den = int(denstr[1])
result = [num, den]
return result
den_list = []
num_list = []
for a in range(10, 99):
for b in range(a+1, 100):
result = reduce(a, b)
if len(str(result[0])) == 1 and len(str(result[1])) == 1 and result[1] != 0:
if a/b == result[0]/result[1] and a%10 != 0:
den_list.append(result[1])
num_list.append(result[0])
#print(a, b, result[0], result[1])
product = 1
for i in range(len(num_list)):
product *= den_list[i]/num_list[i]
print(product)
<file_sep>#Truncatable primes
#Problem 37
#The number 3797 has an interesting property. Being prime itself, it is possible to continuously remove digits from left to right, and remain prime at each stage: 3797, 797, 97, and 7. Similarly we can work from right to left: 3797, 379, 37, and 3.
#Find the sum of the only eleven primes that are both truncatable from left to right and right to left.
#NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes.
def isPrime(n):
if n == 0 or n == 1:
return False
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
return True
def truncPrime(num):
numstr = str(num)
length = len(numstr)
while length > 0:
if isPrime(int(numstr)) == False:
return False
numstr = numstr[1:]
length -= 1
numstr = str(num)
length = len(numstr)
while length > 0:
if isPrime(int(numstr)) == False:
return False
length -= 1
numstr = numstr[:length]
return True
total = 0
for i in range(10, 1000000):
if truncPrime(i) == True:
#print(i)
total += i
print(total)
<file_sep>#Integer right triangles
#Problem 39
#If p is the perimeter of a right angle triangle with integral length sides, {a,b,c}, there are exactly three solutions for p = 120.
#{20,48,52}, {24,45,51}, {30,40,50}
#For which value of p ≤ 1000, is the number of solutions maximised?
def isRightTriangle(x, y, z):
c = max(x, y, z)
a = min(x, y, z)
b = (x+y+z) - (c+a)
if a**2 + b**2 == c**2:
return True
else:
return False
mydict = {}
for i in range(1, 1001):
mydict[i] = 0
for a in range(1, 1001):
for b in range(a+1, 1001):
#for c in range(1, 1001):
c = int((a ** 2 + b ** 2) ** 0.5)
if isRightTriangle(a, b, c) == True:
perimeter = a+b+c
if perimeter <= 1000:
mydict[perimeter] += 1
max_val = 0
max_key = 0
for k, v in mydict.items():
if v > max_val:
max_val = v
max_key = k
print(max_key, max_val)
<file_sep>#Cubic permutations
#Problem 62
#The cube, 41063625 (3453), can be permuted to produce two other cubes: 56623104 (3843) and 66430125 (4053). In fact, 41063625 is the smallest cube which has exactly three permutations of its digits which are also cube.
#Find the smallest cube for which exactly five permutations of its digits are cube.
def digits_dict(number):
digits = {}
for i in range(10):
digits[i] = 0
string = str(number)
for char in string:
unit = int(char)
digits[unit] += 1
return digits
#cube_list = []
dict_list = []
for num in range(1, 10000):
#cube_list.append(num ** 3)
cube = num ** 3
dict_list.append(digits_dict(cube))
#print(len(dict_list))
#for a in range(1000):
# for b in range(a, 1000):
cubes_list = []
length = len(dict_list)
for a in range(length - 1):
cubes_list = [a+1]
for b in range(a+1, length):
if dict_list[a] == dict_list[b]:
cubes_list.append(b+1)
if len(cubes_list) >= 5:
#print(cubes_list)
print(cubes_list[0] ** 3)
break
<file_sep>#Pandigital prime
#Problem 41
#We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once. For example, 2143 is a 4-digit pandigital and is also prime.
#What is the largest n-digit pandigital prime that exists?
def isPrime(n):
if n == 0 or n == 1:
return False
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
return True
def isPanDigital(mystr):
length = len(mystr)
for char in mystr:
if int(char) > length:
return False
strdict = {}
for i in range(0, length+1):
strdict[str(i)] = 0
#print(strdict)
for char in mystr:
strdict[char] = strdict[char] + 1
#print(strdict)
for k, v in strdict.items():
if k != '0':
if v != 1:
return False
if strdict['0'] != 0:
return False
return True
max_num = 0
for num in range(10000, 10000000): #, 100000):
if isPanDigital(str(num)) == True:
if isPrime(num) == True:
if num > max_num:
max_num = num
#print(num)
print(max_num)
<file_sep>#Champernowne's constant
#Problem 40
#An irrational decimal fraction is created by concatenating the positive integers:
#0.123456789101112131415161718192021...
#It can be seen that the 12th digit of the fractional part is 1.
#If dn represents the nth digit of the fractional part, find the value of the following expression.
#d1 × d10 × d100 × d1000 × d10000 × d100000 × d1000000
numstr = ''
for num in range(1, 200000):
numstr += str(num)
result = int(numstr[0]) * int(numstr[9]) * int(numstr[99]) * int(numstr[999]) * int(numstr[9999]) * int(numstr[99999]) * int(numstr[999999])
print(result)
<file_sep>#Combinatoric selections
#Problem 53
#There are exactly ten ways of selecting three from five, 12345:
#123, 124, 125, 134, 135, 145, 234, 235, 245, and 345
#In combinatorics, we use the notation, 5C3 = 10.
#In general,
#nCr =
#n!
#r!(n−r)!
#,where r ≤ n, n! = n×(n−1)×...×3×2×1, and 0! = 1.
#It is not until n = 23, that a value exceeds one-million: 23C10 = 1144066.
#How many, not necessarily distinct, values of nCr, for 1 ≤ n ≤ 100, are greater than one-million?
def factorial(num):
if num == 0:
return 1
mult = 1
for i in range(1, num+1):
mult *= i
return mult
def combinations(n, r):
comb = factorial(n) / (factorial(r) * factorial(n-r))
return int(comb)
total = 0
for n in range(1, 101):
for r in range(1, n+1):
if combinations(n, r) > 1000000:
total += 1
print(total)
<file_sep>#Lychrel numbers
#Problem 55
#If we take 47, reverse and add, 47 + 74 = 121, which is palindromic.
#Not all numbers produce palindromes so quickly. For example,
#349 + 943 = 1292,
#1292 + 2921 = 4213
#4213 + 3124 = 7337
#That is, 349 took three iterations to arrive at a palindrome.
#Although no one has proved it yet, it is thought that some numbers, like 196, never produce a palindrome. A number that never forms a palindrome through the reverse and add process is called a Lychrel number. Due to the theoretical nature of these numbers, and for the purpose of this problem, we shall assume that a number is Lychrel until proven otherwise. In addition you are given that for every number below ten-thousand, it will either (i) become a palindrome in less than fifty iterations, or, (ii) no one, with all the computing power that exists, has managed so far to map it to a palindrome. In fact, 10677 is the first number to be shown to require over fifty iterations before producing a palindrome: 4668731596684224866951378664 (53 iterations, 28-digits).
#Surprisingly, there are palindromic numbers that are themselves Lychrel numbers; the first example is 4994.
#How many Lychrel numbers are there below ten-thousand?
#NOTE: Wording was modified slightly on 24 April 2007 to emphasise the theoretical nature of Lychrel numbers.
def reverse(string):
revstr = ''
length = len(string)
for i in range(length - 1, -1, -1):
revstr += string[i]
return revstr
def isPalindrome(number):
string = str(number)
if reverse(string) == string:
return True
return False
def isLychrel(number):
numstr = str(number)
revstr = reverse(numstr)
a = int(numstr)
b = int(revstr)
total = a + b
if isPalindrome(total):
return False
for num in range(100):
a = total
a_str = str(a)
b_str = reverse(a_str)
b = int(b_str)
total = a + b
if isPalindrome(total):
return False
return True
lychrel = 0
for num in range(1, 10000):
if isLychrel(num):
lychrel += 1
print(lychrel)
<file_sep>#Non-abundant sums
#Problem 23
#A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number.
#A number n is called deficient if the sum of its proper divisors is less than n and it is called abundant if this sum exceeds n.
#As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest number that can be written as the sum of two abundant numbers is 24. By mathematical analysis, it can be shown that all integers greater than 28123 can be written as the sum of two abundant numbers. However, this upper limit cannot be reduced any further by analysis even though it is known that the greatest number that cannot be expressed as the sum of two abundant numbers is less than this limit.
#Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers.
def get_factors(number):
numlist = [n for n in range(1, number) if number % n == 0]
total = 0
for num in numlist:
total += num
return total
new_dict = {}
#def total(numlist):
# total = 0
# for num in numlist:
# total += num
# return total
def get_all_factors(numbers_set):
#for i in numbers_set:
# new_dict[i] = get_factors(i)
#print(new_dict)
new_dict = {i:get_factors(i) for i in numbers_set if i < get_factors(i)}
return new_dict
numset = {0}
for i in range(1, 28124):
numset.add(i)
numset.remove(0)
#print(numset)
my_dict = {}
my_dict = get_all_factors(numset)
#print(my_dict)
set_abundant = {0}
for k in my_dict.keys():
set_abundant.add(k)
set_abundant.remove(0)
#list_abundant.sort()
#print(list_abundant)
#print(len(set_abundant))
#print(set_abundant)
sumset = {0}
sumlist = []
list_abundant = list(set_abundant)
#print(list_abundant)
for m in range(len(list_abundant)):
for n in range(len(list_abundant)):
sumlist.append(list_abundant[m] + list_abundant[n])
sumset = set(sumlist)
sumset = sumset.union(sumset)
#print(sumset)
finalset = numset - sumset
finalset = list(finalset)
#print(finalset)
total = 0
for num in finalset:
total += num
print(total)
<file_sep>#Power digit sum
#Problem 16
#2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
#What is the sum of the digits of the number 2^1000?
number = 2 ** 1000
numstr = str(number)
#print(numstr)
total = 0
for char in numstr:
total += int(char)
print(total)
<file_sep>#Amicable numbers
#Problem 21
#Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n).
#If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable pair and each of a and b are called amicable numbers.
#For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220.
#Evaluate the sum of all the amicable numbers under 10000.
def get_factors(number):
return [n for n in range(1, number) if number % n == 0]
new_dict = {}
def total(numlist):
total = 0
for num in numlist:
total += num
return total
def get_all_factors(numbers_set):
#for i in numbers_set:
# new_dict[i] = get_factors(i)
#print(new_dict)
new_dict = {i:total(get_factors(i)) for i in numbers_set}
return new_dict
#get_all_factors({1, 2, 3, 4})
#get_all_factors({62, 293, 314})
numset = {0}
for i in range(1, 10000):
numset.add(i)
my_dict = {}
my_dict = get_all_factors(numset)
#print(my_dict)
list_of_tuples = []
list_of_unique_tuples = []
for k, v in my_dict.items():
if my_dict[k] < 10000:
if my_dict[v] == k:
if k != v:
list_of_tuples.append((k, v))
for i in range(1, len(list_of_tuples), 2):
list_of_unique_tuples.append(list_of_tuples[i])
print(list_of_unique_tuples)
total = 0
for i in range(len(list_of_unique_tuples)):
for j in range(2):
total += list_of_unique_tuples[i][j]
print(total)
<file_sep>#Pentagon numbers
#Problem 44
#Pentagonal numbers are generated by the formula, Pn=n(3n−1)/2. The first ten pentagonal numbers are:
#1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ...
#It can be seen that P4 + P7 = 22 + 70 = 92 = P8. However, their difference, 70 − 22 = 48, is not pentagonal.
#Find the pair of pentagonal numbers, Pj and Pk, for which their sum and difference are pentagonal and D = |Pk − Pj| is minimised; what is the value of D?
#P = n(3n - 1)/2
pent_list = []
for i in range(1, 3000):
pent = int(i * (3*i - 1) / 2)
pent_list.append(pent)
for j in range(len(pent_list) - 1):
for k in range(j, len(pent_list)):
add_val = pent_list[j] + pent_list[k]
sub_val = pent_list[k] - pent_list[j]
if add_val in pent_list:
if sub_val in pent_list:
print(pent_list[k] - pent_list[j])
<file_sep>#Counting Sundays
#Problem 19
#You are given the following information, but you may prefer to do some research for yourself.
#1 Jan 1900 was a Monday.
#Thirty days has September,
#April, June and November.
#All the rest have thirty-one,
#Saving February alone,
#Which has twenty-eight, rain or shine.
#And on leap years, twenty-nine.
#A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.
#How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?
import time
from datetime import date, timedelta
#def parse_date(date_string):
# return datetime.strptime(date_string, "%Y-%m-%d")
def daterange(start_date, end_date):
for n in range(int ((end_date - start_date).days)):
yield start_date + timedelta(n)
date1 = date(1901, 1, 1)
date2 = date(2000, 12, 31)
time_diff = abs(date2 - date1)
print(time_diff.days)
print(date1.weekday())
total = 0
for single_date in daterange(date1, date2):
#print(single_date.strftime("%Y-%m-%d"))
#print(single_date.day)
if single_date.day == 1:
if single_date.weekday() == 6:
#print(single_date.strftime("%Y-%m-%d"))
total += 1
print(total)
#time.sleep(1)
#for n in range(time_diff.days):
# currdate = date1 + timedelta(n)
# weekday = currdate.weekday()
# print(date1.day)
# print(date1 + timedelta(n))
# time.sleep(1)
<file_sep>#Cyclical figurate numbers
#Problem 61
#Triangle, square, pentagonal, hexagonal, heptagonal, and octagonal numbers are all figurate (polygonal) numbers and are generated by the following formulae:
#Triangle P3,n=n(n+1)/2 1, 3, 6, 10, 15, ...
#Square P4,n=n2 1, 4, 9, 16, 25, ...
#Pentagonal P5,n=n(3n−1)/2 1, 5, 12, 22, 35, ...
#Hexagonal P6,n=n(2n−1) 1, 6, 15, 28, 45, ...
#Heptagonal P7,n=n(5n−3)/2 1, 7, 18, 34, 55, ...
#Octagonal P8,n=n(3n−2) 1, 8, 21, 40, 65, ...
#The ordered set of three 4-digit numbers: 8128, 2882, 8281, has three interesting properties.
#The set is cyclic, in that the last two digits of each number is the first two digits of the next number (including the last number with the first).
#Each polygonal type: triangle (P3,127=8128), square (P4,91=8281), and pentagonal (P5,44=2882), is represented by a different number in the set.
#This is the only set of 4-digit numbers with this property.
#Find the sum of the only ordered set of six cyclic 4-digit numbers for which each polygonal type: triangle, square, pentagonal, hexagonal, heptagonal, and octagonal, is represented by a different number in the set.
tri_list = []
sqr_list = []
pent_list = []
hex_list = []
hept_list = []
oct_list = []
num = 1
tri_num = 1
while tri_num < 10000:
tri_num = num * (num + 1) / 2
tri_num = int(tri_num)
if tri_num >= 1000 and tri_num < 10000:
tri_str = str(tri_num)
if tri_str[2] != '0':
tri_list.append((3, tri_num))
num += 1
num = 1
sqr_num = 1
while sqr_num < 10000:
sqr_num = num * num
sqr_num = int(sqr_num)
if sqr_num >= 1000 and sqr_num < 10000:
sqr_str = str(sqr_num)
if sqr_str[2] != '0':
sqr_list.append((4, sqr_num))
num += 1
num = 1
pent_num = 1
while pent_num < 10000:
pent_num = num * (3 * num - 1) / 2
pent_num = int(pent_num)
if pent_num >= 1000 and pent_num < 10000:
pent_str = str(pent_num)
if pent_str[2] != '0':
pent_list.append((5, pent_num))
num += 1
num = 1
hex_num = 1
while hex_num < 10000:
hex_num = num * (2 * num - 1)
hex_num = int(hex_num)
if hex_num >= 1000 and hex_num < 10000:
hex_str = str(hex_num)
if hex_str[2] != '0':
hex_list.append((6, hex_num))
num += 1
num = 1
hept_num = 1
while hept_num < 10000:
hept_num = num * (5 * num - 3) / 2
hept_num = int(hept_num)
if hept_num >= 1000 and hept_num < 10000:
hept_str = str(hept_num)
if hept_str[2] != '0':
hept_list.append((7, hept_num))
num += 1
num = 1
oct_num = 1
while oct_num < 10000:
oct_num = num * (3 * num - 2)
oct_num = int(oct_num)
if oct_num >= 1000 and oct_num < 10000:
oct_str = str(oct_num)
if oct_str[2] != '0':
oct_list.append((8, oct_num))
num += 1
tri_dict = {}
sqr_dict = {}
pent_dict = {}
hex_dict = {}
hept_dict = {}
oct_dict = {}
for tri_tuple in tri_list:
tri_dict[tri_tuple] = []
for tri_tuple in tri_list:
tristr = str(tri_tuple[1])
for sqr_tuple in sqr_list:
sqrstr = str(sqr_tuple[1])
if tristr[2:] == sqrstr[0:2]:
tri_dict[tri_tuple].append(sqr_tuple)
for pent_tuple in pent_list:
pentstr = str(pent_tuple[1])
if tristr[2:] == pentstr[0:2]:
tri_dict[tri_tuple].append(pent_tuple)
for hex_tuple in hex_list:
hexstr = str(hex_tuple[1])
if tristr[2:] == hexstr[0:2]:
tri_dict[tri_tuple].append(hex_tuple)
for hept_tuple in hept_list:
heptstr = str(hept_tuple[1])
if tristr[2:] == heptstr[0:2]:
tri_dict[tri_tuple].append(hept_tuple)
for oct_tuple in oct_list:
octstr = str(oct_tuple[1])
if tristr[2:] == octstr[0:2]:
tri_dict[tri_tuple].append(oct_tuple)
for sqr_tuple in sqr_list:
sqr_dict[sqr_tuple] = []
for sqr_tuple in sqr_list:
sqrstr = str(sqr_tuple[1])
for tri_tuple in tri_list:
tristr = str(tri_tuple[1])
if sqrstr[2:] == tristr[0:2]:
sqr_dict[sqr_tuple].append(tri_tuple)
for pent_tuple in pent_list:
pentstr = str(pent_tuple[1])
if sqrstr[2:] == pentstr[0:2]:
sqr_dict[sqr_tuple].append(pent_tuple)
for hex_tuple in hex_list:
hexstr = str(hex_tuple[1])
if sqrstr[2:] == hexstr[0:2]:
sqr_dict[sqr_tuple].append(hex_tuple)
for hept_tuple in hept_list:
heptstr = str(hept_tuple[1])
if sqrstr[2:] == heptstr[0:2]:
sqr_dict[sqr_tuple].append(hept_tuple)
for oct_tuple in oct_list:
octstr = str(oct_tuple[1])
if sqrstr[2:] == octstr[0:2]:
sqr_dict[sqr_tuple].append(oct_tuple)
for pent_tuple in pent_list:
pent_dict[pent_tuple] = []
for pent_tuple in pent_list:
pentstr = str(pent_tuple[1])
for tri_tuple in tri_list:
tristr = str(tri_tuple[1])
if pentstr[2:] == tristr[0:2]:
pent_dict[pent_tuple].append(tri_tuple)
for sqr_tuple in sqr_list:
sqrstr = str(sqr_tuple[1])
if pentstr[2:] == sqrstr[0:2]:
pent_dict[pent_tuple].append(sqr_tuple)
for hex_tuple in hex_list:
hexstr = str(hex_tuple[1])
if pentstr[2:] == hexstr[0:2]:
pent_dict[pent_tuple].append(hex_tuple)
for hept_tuple in hept_list:
heptstr = str(hept_tuple[1])
if pentstr[2:] == heptstr[0:2]:
pent_dict[pent_tuple].append(hept_tuple)
for oct_tuple in oct_list:
octstr = str(oct_tuple[1])
if pentstr[2:] == octstr[0:2]:
pent_dict[pent_tuple].append(oct_tuple)
for hex_tuple in hex_list:
hex_dict[hex_tuple] = []
for hex_tuple in hex_list:
hexstr = str(hex_tuple[1])
for tri_tuple in tri_list:
tristr = str(tri_tuple[1])
if hexstr[2:] == tristr[0:2]:
hex_dict[hex_tuple].append(tri_tuple)
for sqr_tuple in sqr_list:
sqrstr = str(sqr_tuple[1])
if hexstr[2:] == sqrstr[0:2]:
hex_dict[hex_tuple].append(sqr_tuple)
for hept_tuple in hept_list:
heptstr = str(hept_tuple[1])
if hexstr[2:] == heptstr[0:2]:
hex_dict[hex_tuple].append(hept_tuple)
for pent_tuple in pent_list:
pentstr = str(pent_tuple[1])
if hexstr[2:] == pentstr[0:2]:
hex_dict[hex_tuple].append(pent_tuple)
for oct_tuple in oct_list:
octstr = str(oct_tuple[1])
if hexstr[2:] == octstr[0:2]:
hex_dict[hex_tuple].append(oct_tuple)
for hept_tuple in hept_list:
hept_dict[hept_tuple] = []
for hept_tuple in hept_list:
heptstr = str(hept_tuple[1])
for tri_tuple in tri_list:
tristr = str(tri_tuple[1])
if heptstr[2:] == tristr[0:2]:
hept_dict[hept_tuple].append(tri_tuple)
for sqr_tuple in sqr_list:
sqrstr = str(sqr_tuple[1])
if heptstr[2:] == sqrstr[0:2]:
hept_dict[hept_tuple].append(sqr_tuple)
for hex_tuple in hex_list:
hexstr = str(hex_tuple[1])
if heptstr[2:] == hexstr[0:2]:
hept_dict[hept_tuple].append(hex_tuple)
for pent_tuple in pent_list:
pentstr = str(pent_tuple[1])
if heptstr[2:] == pentstr[0:2]:
hept_dict[hept_tuple].append(pent_tuple)
for oct_tuple in oct_list:
octstr = str(oct_tuple[1])
if heptstr[2:] == octstr[0:2]:
hept_dict[hept_tuple].append(oct_tuple)
for oct_tuple in oct_list:
oct_dict[oct_tuple] = []
for oct_tuple in oct_list:
octstr = str(oct_tuple[1])
for tri_tuple in tri_list:
tristr = str(tri_tuple[1])
if octstr[2:] == tristr[0:2]:
oct_dict[oct_tuple].append(tri_tuple)
for sqr_tuple in sqr_list:
sqrstr = str(sqr_tuple[1])
if octstr[2:] == sqrstr[0:2]:
oct_dict[oct_tuple].append(sqr_tuple)
for hex_tuple in hex_list:
hexstr = str(hex_tuple[1])
if octstr[2:] == hexstr[0:2]:
oct_dict[oct_tuple].append(hex_tuple)
for pent_tuple in pent_list:
pentstr = str(pent_tuple[1])
if octstr[2:] == pentstr[0:2]:
oct_dict[oct_tuple].append(pent_tuple)
for hept_tuple in hept_list:
heptstr = str(hept_tuple[1])
if octstr[2:] == heptstr[0:2]:
oct_dict[oct_tuple].append(hept_tuple)
all_dict = {}
all_dict.update(tri_dict)
all_dict.update(sqr_dict)
all_dict.update(pent_dict)
all_dict.update(hex_dict)
all_dict.update(hept_dict)
all_dict.update(oct_dict)
def total(link_list):
total = 0
for items in link_list:
total += items[1]
return total
cycle_list = []
key_list = []
def cycle(tuple_key, list_val):
cycle_list.append(tuple_key)
if tuple_key[0] not in key_list:
key_list.append(tuple_key[0])
for item in list_val:
if len(cycle_list) < 6:
if item[0] not in key_list:
key_list.append(item[0])
cycle(item, all_dict[item])
else:
if (cycle_list[5][1] % 100) == (cycle_list[0][1] // 100):
print(cycle_list, total(cycle_list))
del key_list[-1]
del cycle_list[-1]
return
if len(cycle_list) > 1:
del key_list[-1]
del cycle_list[-1]
return
for key in oct_list:
cycle(key, all_dict[key])
cycle_list = []
key_list = []
<file_sep>#Consecutive prime sum
#Problem 50
#The prime 41, can be written as the sum of six consecutive primes:
#41 = 2 + 3 + 5 + 7 + 11 + 13
#This is the longest sum of consecutive primes that adds to a prime below one-hundred.
#The longest sum of consecutive primes below one-thousand that adds to a prime, contains 21 terms, and is equal to 953.
#Which prime, below one-million, can be written as the sum of the most consecutive primes?
#Answer: 997651
def isPrime(n):#
if n == 0 or n == 1:
return False
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
return True
total = 0
prime_list = []
for num in range(1, 1000000):
if isPrime(num) == True:
prime_list.append(num)
prime_total = []
total = 0
for num in prime_list:
total += num
prime_total.append(total)
#print(prime_list)
#print(len(prime_total))
maxima = 0
numPrimes = 0
for i in range(1, len(prime_total)):
for j in range(i-(numPrimes+1), 0, -1):
diff = prime_total[i] - prime_total[j]
if diff >= 1000000:
break
if diff in prime_list:
numPrimes = i - j
if diff > maxima:
maxima = diff
print(maxima)
<file_sep>#Triangular, pentagonal, and hexagonal
#Problem 45
#Triangle, pentagonal, and hexagonal numbers are generated by the following formulae:
#Triangle Tn=n(n+1)/2 1, 3, 6, 10, 15, ...
#Pentagonal Pn=n(3n−1)/2 1, 5, 12, 22, 35, ...
#Hexagonal Hn=n(2n−1) 1, 6, 15, 28, 45, ...
#It can be verified that T285 = P165 = H143 = 40755.
#Find the next triangle number that is also pentagonal and hexagonal.
tria = {0}
pent = {0}
hexa = {0}
for num in range(1, 100000):
tria.add(int(num * (num + 1) / 2))
pent.add(int(num * (3 * num - 1) / 2))
hexa.add(int(num * (2 * num - 1)))
interset = {0, 1}
interset = tria.intersection(pent)
interset = interset.intersection(hexa)
interset -= {0, 1}
print(interset)
<file_sep>#Pandigital multiples
#Problem 38
#Take the number 192 and multiply it by each of 1, 2, and 3:
#192 × 1 = 192
#192 × 2 = 384
#192 × 3 = 576
#By concatenating each product we get the 1 to 9 pandigital, 192384576. We will call 192384576 the concatenated product of 192 and (1,2,3)
#The same can be achieved by starting with 9 and multiplying by 1, 2, 3, 4, and 5, giving the pandigital, 918273645, which is the concatenated product of 9 and (1,2,3,4,5).
#What is the largest 1 to 9 pandigital 9-digit number that can be formed as the concatenated product of an integer with (1,2, ... , n) where n > 1?
def isPanDigital(mystr):
strdict = {'0':0, '1':0,'2':0,'3':0,'4':0,'5':0,'6':0,'7':0,'8':0,'9':0}
for char in mystr:
strdict[char] = strdict[char] + 1
#print(strdict)
for k, v in strdict.items():
if k != '0':
if v != 1:
return False
if strdict['0'] != 0:
return False
return True
max_num = 0
for a in range(1, 100000):
for b in range(2, 15):
mystr = ''
for c in range(1, b+1):
product = a * c
mystr += str(product)
#print(mystr)
if isPanDigital(mystr) == True:
if int(mystr) > max_num:
max_num = int(mystr)
print(max_num)
<file_sep>#Maximum path sum I
#Problem 18
#By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23.
#3
#7 4
#2 4 6
#8 5 9 3
#That is, 3 + 7 + 4 + 9 = 23.
#Find the maximum total from top to bottom of the triangle below:
#75
#95 64
#17 47 82
#18 35 87 10
#20 04 82 47 65
#19 01 23 75 03 34
#88 02 77 73 07 63 67
#99 65 04 28 06 16 70 92
#41 41 26 56 83 40 80 70 33
#41 48 72 33 47 32 37 16 94 29
#53 71 44 65 25 43 91 52 97 51 14
#70 11 33 28 77 73 17 78 39 68 17 57
#91 71 52 38 17 14 91 43 58 50 27 29 48
#63 66 04 68 89 53 67 30 73 16 69 87 40 31
#04 62 98 27 23 09 70 98 73 93 38 53 60 04 23
#NOTE: As there are only 16384 routes, it is possible to solve this problem by trying every route. However, Problem 67, is the same challenge with a triangle containing one-hundred rows; it cannot be solved by brute force, and requires a clever method! ;o)
import sys
number = []
number.append(list('75'.split(' ')))
number.append(list('95 64'.split(' ')))
number.append(list('17 47 82'.split(' ')))
number.append(list('18 35 87 10'.split(' ')))
number.append(list('20 04 82 47 65'.split(' ')))
number.append(list('19 01 23 75 03 34'.split(' ')))
number.append(list('88 02 77 73 07 63 67'.split(' ')))
number.append(list('99 65 04 28 06 16 70 92'.split(' ')))
number.append(list('41 41 26 56 83 40 80 70 33'.split(' ')))
number.append(list('41 48 72 33 47 32 37 16 94 29'.split(' ')))
number.append(list('53 71 44 65 25 43 91 52 97 51 14'.split(' ')))
number.append(list('70 11 33 28 77 73 17 78 39 68 17 57'.split(' ')))
number.append(list('91 71 52 38 17 14 91 43 58 50 27 29 48'.split(' ')))
number.append(list('63 66 04 68 89 53 67 30 73 16 69 87 40 31'.split(' ')))
number.append(list('04 62 98 27 23 09 70 98 73 93 38 53 60 04 23'.split(' ')))
#for i in range(15):
# print(number[i])
for i in range(13, -1, -1):
for j in range(i+1):
number[i][j] = max((int(number[i][j]) + int(number[i+1][j])), (int(number[i][j]) + int(number[i+1][j+1])))
print(number)
<file_sep>#Quadratic primes
#Problem 27
#Euler discovered the remarkable quadratic formula:
#n² + n + 41
#It turns out that the formula will produce 40 primes for the consecutive values n = 0 to 39. However, when n = 40, 402 + 40 + 41 = 40(40 + 1) + 41 is divisible by 41, and certainly when n = 41, 41² + 41 + 41 is clearly divisible by 41.
#The incredible formula n² − 79n + 1601 was discovered, which produces 80 primes for the consecutive values n = 0 to 79. The product of the coefficients, −79 and 1601, is −126479.
#Considering quadratics of the form:
#n² + an + b, where |a| < 1000 and |b| < 1000
#where |n| is the modulus/absolute value of n
#e.g. |11| = 11 and |−4| = 4
#Find the product of the coefficients, a and b, for the quadratic expression that produces the maximum number of primes for consecutive values of n, starting with n = 0.
def isPrime(n):
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
return True
# -999 < a, b < 999
max_n = 0
product = 1
for a in range(999, -1000, -1):
for b in range(999, -1000, -1):
n = 0
eqn = b
if eqn <= 1:
break
else:
while isPrime(eqn) != False:
n += 1
eqn = (n * n) + (a * n) + b
if eqn <= 1:
break
if n > max_n:
max_n = n
product = a * b
print(product)
|
8ae9e1256677d1ec1afb7665c533107c7b7cb556
|
[
"Python"
] | 56
|
Python
|
Sonnenlicht/ProjectEuler
|
fdd14d68aa14e727d581330f43e6d7e5af36e366
|
cbac6d2b0d121aa2fa83652f50645f039ba03b41
|
refs/heads/main
|
<repo_name>bduran04/Code_Quiz<file_sep>/script.js
var questionIndex = 0;
var score = 0;
var timeLeft = 30;
var timer;
//this hold all of the final scores;
var finalScores = {data: []}
var startPage = document.querySelector(".startPage");
var startButton = document.querySelector(".startButton");
var questionsPage = document.querySelector(".questionsPage");
questionsPage.setAttribute("style", "display: none");
var endGamePage = document.querySelector(".endGamePage");
endGamePage.setAttribute("style", "display: none");
var timerEl = document.querySelector(".timer");
var questions = [
{
title: "Which of the following type of variable takes precedence over other if names are same?",
choices: ["Global variable", "Local variable", "Both of the above", "None of the above"],
answer: "Local variable"
},
{
title: "Which built-in method returns the string representation of the number's value?",
choices: ["toValue()", "toNUmber()", "toString()", "None of the above"],
answer: "toString()"
},
{
title: "Which of the following function of String object returns the index within the calling String object of the first occurrence of the specified value??",
choices: ["substr()", "search()", "lastIndexOf()", "indexOf()"],
answer: "indexOf()"
},
{
title: "Which of the following function of String object creates an HTML anchor that is used as a hypertext target?",
choices: ["anchor()", "link()", "blink()", "big()"],
answer: "anchor()"
},
{
title: "Which of the following function of String object causes a string to be italic, as if it were in an <i> tag?",
choices: ["fixed()", "fontcolor()", "fontsize()", "italics()"],
answer: "italics()"
}
]
function startQuiz() {
timerEl.textContent="Time left: " + timeLeft;
timer = setInterval(function() {
timeLeft--;
timerEl.textContent="Time left: " + timeLeft;
if (timeLeft === 0) {
endGame();
}
},1000)
startPage.setAttribute("style", "display:none");
questionsPage.setAttribute("style", "display:block");
questionsPage.removeAttribute("style");
displayNextQuestion();
//if it doesnt equal null then assign in finalscores
if (JSON.parse(localStorage.getItem("finalScores")) !== null) {
finalScores = JSON.parse(localStorage.getItem("finalScores"))
}
}
function displayNextQuestion() {
var questionsTitle = document.querySelector(".questionsTitle");
var questionsChoices = document.querySelector(".questionsChoices");
//grab questions from array & enables user to answer before moving on
questionsTitle.textContent=questions[questionIndex].title;
questionsChoices.innerHTML="";
questions[questionIndex].choices.forEach(function(choice) {
var inputEl = document.createElement("input")
inputEl.type = "radio";
var labelEl = document.createElement("label")
var breakEl = document.createElement("br")
labelEl.textContent = choice;
inputEl.value = choice;
inputEl.addEventListener('click', checkAnswer);
questionsChoices.appendChild(inputEl);
questionsChoices.appendChild(labelEl);
questionsChoices.appendChild(breakEl);
})
}
function checkAnswer(event) {
if (event.target.value === questions[questionIndex].answer) {
score++;
questionIndex++;
if (questionIndex === questions.length) {
endGame();
}
else {
displayNextQuestion();
}
}
else {
displayErrorMessage();
questionIndex++;
//if the timer is 10 or less, it deducts the remaining time left else it deducts 10
if (timeLeft < 10) {
// timeLeft = timeLeft - timeLeft
timeLeft = 0;
endGame();
}
else {
timeLeft-=10;
}
}
timerEl.textContent="Time left: " + timeLeft;
//display message incorrcet
}
function displayErrorMessage() {
document.querySelector(".errorMessage").textContent="Incorrect Answer!";
setTimeout(function () {
document.querySelector(".errorMessage").textContent="";
displayNextQuestion()
}, 1000);
// setTimeout(function() {...}, time in ms)
}
//calls the display the next question function
function endGame() {
questionsPage.setAttribute("style", "display:none");
endGamePage.setAttribute("style", "display:block");
clearInterval(timer);
var initials = prompt("What are your initials? ");
var finalScore = {
initials,
score
}
finalScores.data.push(finalScore);
createTable()
localStorage.setItem("finalScores", JSON.stringify(finalScores));
//responsible for end of the game
//populate the scoreboard & initially
}
function createTable() {
// create table
var tableEl = document.createElement("table");
var tableRowEl = document.createElement("tr");
// create table headers
var firstTableHeaderEl = document.createElement("th");
firstTableHeaderEl.textContent = "Player";
var secondTableHeaderEl = document.createElement("th");
secondTableHeaderEl.textContent = "Score";
// add table header to table element
tableRowEl.appendChild(firstTableHeaderEl);
tableRowEl.appendChild(secondTableHeaderEl);
tableEl.appendChild(tableRowEl);
// generic sort by value
finalScores.data.sort(function (a, b) {
return b.score - a.score;
});
// loop over data to create table rows
for (record of finalScores.data) {
// create table row with player and score info
var trEl = document.createElement("tr");
var td_player = document.createElement("td");
td_player.textContent = record.initials;
var td_score = document.createElement("td");
td_score.textContent = record.score;
trEl.appendChild(td_player);
trEl.appendChild(td_score);
// put new table row in table
tableEl.appendChild(trEl)
}
endGamePage.appendChild(tableEl);
}
//save initials into a local storage and display all the high scores on the page
//handle the endgame fucntion, what jhappens when reahc end of questions array <file_sep>/README.md
Description: This application prompts the user to complete a timed Javascript multiple choice quiz, which allows the user to save their score in a local storage.
Deployed site: https://bduran04.github.io/Code_Quiz/

|
cebbdb6da35c84e28801775fc192fd9a333b2250
|
[
"JavaScript",
"Markdown"
] | 2
|
JavaScript
|
bduran04/Code_Quiz
|
4d4f8e7c3132985b26091674d2a5278ae616cb57
|
7c69f9e99d3e6ae54e59f7f7d7487a5a9f837657
|
refs/heads/master
|
<repo_name>ray0sunshine/Tetris<file_sep>/src/viewer.hpp
/*
name: <NAME>
id: r7sun
student number: 20343049
*/
#ifndef CS488_VIEWER_HPP
#define CS488_VIEWER_HPP
#include <gtkmm.h>
#include <gtkglmm.h>
#include <vector>
#include "game.hpp"
class Viewer:public Gtk::GL::DrawingArea{
public:
//types of cubes to draw
enum cubeType {wire,face,multi};
enum transType {xrot,yrot,zrot,scl,none};
//struct for point containing normal
struct n3f{
float x;
float y;
float z;
};
struct pt3f{
float x;
float y;
float z;
n3f n;
};
struct pt{
float x;
float y;
float z;
float vx;
float vy;
float vz;
float r;
float g;
float b;
};
struct shineCube{
float x;
float y;
float d;
};
std::vector<shineCube> shines;
Viewer();
virtual ~Viewer();
//causes rerender
void invalidate();
//resets variables
void init();
void viewInit();
//called by timer
bool update();
bool updateGame();
//pre-computes un weighted vertex normals from the standard cube center
void preCompNorm();
//does initial transformations for rotation, scale and translation, lighting and floor should be independent of game well
void mainOrient();
void reflOrient();
//draws the "mirrored ground"
void drawGround();
//calls all the polygon drawing
void drawState();
void drawShine();
//inits the lights and draws the indicator
void lighting();
// Called when keys pressed
void keyHandle(GdkEventKey* e);
//draws unitcube at x,y,z of type w/e
void unitCube(float x, float y, float z, cubeType type);
void unitShine(float x, float y, float z, cubeType type);
//draws a 8 vertex polygon
void polyFace(pt3f p1, pt3f p2, pt3f p3, pt3f p4, pt3f p5, pt3f p6, pt3f p7, pt3f p8);
void polyWire(pt3f p1, pt3f p2, pt3f p3, pt3f p4, pt3f p5, pt3f p6, pt3f p7, pt3f p8);
//draws a triangle
void triFace(pt3f p1, pt3f p2, pt3f p3);
void triWire(pt3f p1, pt3f p2, pt3f p3);
//draw a hex on XZ plane
void heXYZ(float x, float y, float z);
void shine(pt3f p1, pt3f p2);
void particles();
void randPart(float x, float y, float z);
void randPart2(float x, float y, float z);
float rd(float high, float low);
float rad(float deg);
void newGame();
void setMode(cubeType type);
void toggleBlind();
private:
float angleAxisX;
float angleAxisY;
float angleAxisZ;
float angleAxisXActive;
float angleAxisYActive;
float angleAxisZActive;
float lightX;
float lightY;
float lightZ;
float vX;
float mx;
float mbx;
float mBaseX;
bool mDown;
float scale;
float baseScale;
cubeType renderMode;
transType trans;
Game* game;
bool gameEnd;
bool blinding;
std::vector<pt> pts;
//normals
n3f nftrx,nftry,nftrz,nftlx,nftly,nftlz,nfbrx,nfbry,nfbrz,nfblx,nfbly,nfblz,nbtrx,nbtry,nbtrz,nbtlx,nbtly,nbtlz,nbbrx,nbbry,nbbrz,nbblx,nbbly,nbblz;
protected:
// Called when GL is first initialized
virtual void on_realize();
// Called when our window needs to be redrawn
virtual bool on_expose_event(GdkEventExpose* event);
// Called when the window is resized
virtual bool on_configure_event(GdkEventConfigure* event);
// Called when a mouse button is pressed
virtual bool on_button_press_event(GdkEventButton* event);
// Called when a mouse button is released
virtual bool on_button_release_event(GdkEventButton* event);
// Called when the mouse moves
virtual bool on_motion_notify_event(GdkEventMotion* event);
};
#endif
<file_sep>/src/viewer.cpp
/*
name: <NAME>
id: r7sun
student number: 20343049
*/
#include "viewer.hpp"
#include <iostream>
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>
#define boardHeight 20
#define boardWidth 10
#define mainColor 0.8
#define subColor 0.2
#define floorHeight -13
#define floorRadius 18
#define edge 0.5 //edge offset from center
#define coff 0.25 //corner offset
#define faceWeight 0.7 //weight of normal using face normal
#define vertWeight 0.3 //weight of normal using vertex to center normal
#define brt 3
#define damp 10
#define minZoom 0.6
#define maxZoom 3
#define xOff 6.0
#define yOff 12.0
#define grav -0.01
#define timeSlow 0.9
//read games public remove list, remember to reset all the elements to -1 afterwards
//do reading on update 60fps
//also update particles
Viewer::Viewer(){
Glib::RefPtr<Gdk::GL::Config> glconfig;
glconfig = Gdk::GL::Config::create(Gdk::GL::MODE_RGB | Gdk::GL::MODE_DEPTH | Gdk::GL::MODE_DOUBLE);
if(glconfig == 0){std::cerr << "Unable to setup OpenGL Configuration!" << std::endl;abort();}
set_gl_capability(glconfig);
add_events(Gdk::BUTTON1_MOTION_MASK | Gdk::BUTTON2_MOTION_MASK | Gdk::BUTTON3_MOTION_MASK | Gdk::BUTTON_PRESS_MASK | Gdk::BUTTON_RELEASE_MASK | Gdk::VISIBILITY_NOTIFY_MASK);
init();
}
Viewer::~Viewer(){}
void Viewer::invalidate(){
Gtk::Allocation allocation = get_allocation();
get_window()->invalidate_rect( allocation, false);
}
void Viewer::on_realize(){
// Do some OpenGL setup:
// First, let the base class do whatever it needs to
Gtk::GL::DrawingArea::on_realize();
Glib::RefPtr<Gdk::GL::Drawable> gldrawable = get_gl_drawable();
if (!gldrawable) return;
if (!gldrawable->gl_begin(get_gl_context())) return;
// Just enable depth testing and set the background colour.
glEnable(GL_DEPTH_TEST);
glEnable (GL_BLEND);
glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
//glBlendFunc(GL_SRC_ALPHA, GL_SRC_ALPHA);
glClearColor(0.4, 0.4, 0.8, 0.0);
gldrawable->gl_end();
}
bool Viewer::on_configure_event(GdkEventConfigure* event){
Glib::RefPtr<Gdk::GL::Drawable> gldrawable = get_gl_drawable();
if (!gldrawable) return false;
if (!gldrawable->gl_begin(get_gl_context())) return false;
// Set up perspective projection, using current size and aspect ratio of display
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glViewport(0, 0, event->width, event->height);
gluPerspective(40.0, (GLfloat)event->width/(GLfloat)event->height, 0.1, 1000.0);
// Reset to modelview matrix mode
glMatrixMode(GL_MODELVIEW);
gldrawable->gl_end();
return true;
}
void Viewer::preCompNorm(){
nftrx.x = (edge-coff)*vertWeight; nftrx.y = (edge)*vertWeight; nftrx.z = (edge)*vertWeight;
nftry.x = (edge)*vertWeight; nftry.y = (edge-coff)*vertWeight; nftry.z = (edge)*vertWeight;
nftrz.x = (edge)*vertWeight; nftrz.y = (edge)*vertWeight; nftrz.z = (edge-coff)*vertWeight;
nftlx.x = (-edge+coff)*vertWeight; nftlx.y = (edge)*vertWeight; nftlx.z = (edge)*vertWeight;
nftly.x = (-edge)*vertWeight; nftly.y = (edge-coff)*vertWeight; nftly.z = (edge)*vertWeight;
nftlz.x = (-edge)*vertWeight; nftlz.y = (edge)*vertWeight; nftlz.z = (edge-coff)*vertWeight;
nfbrx.x = (edge-coff)*vertWeight; nfbrx.y = (-edge)*vertWeight; nfbrx.z = (edge)*vertWeight;
nfbry.x = (edge)*vertWeight; nfbry.y = (-edge+coff)*vertWeight; nfbry.z = (edge)*vertWeight;
nfbrz.x = (edge)*vertWeight; nfbrz.y = (-edge)*vertWeight; nfbrz.z = (edge-coff)*vertWeight;
nfblx.x = (-edge+coff)*vertWeight; nfblx.y = (-edge)*vertWeight; nfblx.z = (edge)*vertWeight;
nfbly.x = (-edge)*vertWeight; nfbly.y = (-edge+coff)*vertWeight; nfbly.z = (edge)*vertWeight;
nfblz.x = (-edge)*vertWeight; nfblz.y = (-edge)*vertWeight; nfblz.z = (edge-coff)*vertWeight;
nbtrx.x = (edge-coff)*vertWeight; nbtrx.y = (edge)*vertWeight; nbtrx.z = (-edge)*vertWeight;
nbtry.x = (edge)*vertWeight; nbtry.y = (edge-coff)*vertWeight; nbtry.z = (-edge)*vertWeight;
nbtrz.x = (edge)*vertWeight; nbtrz.y = (edge)*vertWeight; nbtrz.z = (-edge+coff)*vertWeight;
nbtlx.x = (-edge+coff)*vertWeight; nbtlx.y = (edge)*vertWeight; nbtlx.z = (-edge)*vertWeight;
nbtly.x = (-edge)*vertWeight; nbtly.y = (edge-coff)*vertWeight; nbtly.z = (-edge)*vertWeight;
nbtlz.x = (-edge)*vertWeight; nbtlz.y = (edge)*vertWeight; nbtlz.z = (-edge+coff)*vertWeight;
nbbrx.x = (edge-coff)*vertWeight; nbbrx.y = (-edge)*vertWeight; nbbrx.z = (-edge)*vertWeight;
nbbry.x = (edge)*vertWeight; nbbry.y = (-edge+coff)*vertWeight; nbbry.z = (-edge)*vertWeight;
nbbrz.x = (edge)*vertWeight; nbbrz.y = (-edge)*vertWeight; nbbrz.z = (-edge+coff)*vertWeight;
nbblx.x = (-edge+coff)*vertWeight; nbblx.y = (-edge)*vertWeight; nbblx.z = (-edge)*vertWeight;
nbbly.x = (-edge)*vertWeight; nbbly.y = (-edge+coff)*vertWeight; nbbly.z = (-edge)*vertWeight;
nbblz.x = (-edge)*vertWeight; nbblz.y = (-edge)*vertWeight; nbblz.z = (-edge+coff)*vertWeight;
}
void Viewer::init(){
game = new Game(boardWidth,boardHeight);
game->reset();
viewInit();
blinding = false;
renderMode = Viewer::face;
trans = Viewer::none;
preCompNorm();
gameEnd = false;
}
void Viewer::viewInit(){
angleAxisX = 0.0;
angleAxisY = 0.0;
angleAxisZ = 0.0;
angleAxisXActive = 0.0;
angleAxisYActive = 0.0;
angleAxisZActive = 0.0;
lightX = 8.0;
lightY = 16.0;
lightZ = 8.0;
mDown = false;
vX = 0;
mx = 0;
mbx = 0;
scale = 1;
baseScale = 1;
}
bool Viewer::updateGame(){
int stat = game->tick();
if(stat < 0){
gameEnd = true;
}
return true;
}
bool Viewer::update(){
if(mDown){
if(mx-mbx == 0){
vX /= 3;
}else{
vX = (mx - mbx)/damp;
if(vX > 1){
vX = std::sqrt(vX);
}else if(vX < -1){
vX = -std::sqrt(abs(vX));
}
}
mbx = mx;
switch(trans){
case Viewer::none:
break;
case Viewer::xrot:
angleAxisXActive = angleAxisX + (mx - mBaseX)/damp;break;
case Viewer::yrot:
angleAxisYActive = angleAxisY + (mx - mBaseX)/damp;break;
case Viewer::zrot:
angleAxisZActive = angleAxisZ + (mx - mBaseX)/damp;break;
case Viewer::scl:
float nscl = baseScale + 0.002*(mx - mBaseX);
if(nscl > minZoom && nscl < maxZoom){
scale = nscl;
}else if(nscl > maxZoom){
scale = maxZoom;
}else if(nscl < minZoom){
scale = minZoom;
}
break;
}
}else{
switch(trans){
case Viewer::xrot:
angleAxisXActive += vX;
angleAxisX = angleAxisXActive;
break;
case Viewer::yrot:
angleAxisYActive += vX;
angleAxisY = angleAxisYActive;
break;
case Viewer::zrot:
angleAxisZActive += vX;
angleAxisZ = angleAxisZActive;
break;
case Viewer::none:
case Viewer::scl:
break;
}
}
invalidate();
return true;
}
void Viewer::toggleBlind(){
if(!blinding){
viewInit();
}
blinding = !blinding;
}
bool Viewer::on_expose_event(GdkEventExpose* event){
Glib::RefPtr<Gdk::GL::Drawable> gldrawable = get_gl_drawable();
if (!gldrawable) return false;
if (!gldrawable->gl_begin(get_gl_context())) return false;
// Clear the screen
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Modify the current projection matrix so that we move the camera away from the origin. We'll draw the game at the origin, and we need to back up to see it.
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glTranslated(0.0, 0.0, -42.0);
// Reset the matrix to identity
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
lighting();
mainOrient();
drawState();
glLoadIdentity();
reflOrient();
drawState();
glLoadIdentity();
glScaled(scale,scale,scale);
drawGround();
particles();
glLoadIdentity();
mainOrient();
if(blinding){
glBegin(GL_QUADS);
glNormal3f(0,5,0);
float midOff = 2;
for(float a=1; a>=0; a-=0.1){
glColor4f(1,1,1,a);
glVertex3f(0+a+midOff,0+a+midOff,-1);
glVertex3f(0+a+midOff,2*yOff-a-midOff,-1);
glVertex3f(2*xOff-a-midOff,2*yOff-a-midOff,-1);
glVertex3f(2*xOff-a-midOff,0+a+midOff,-1);
}
glEnd();
}
glLoadIdentity();
mainOrient();
if(blinding){
drawShine();
}
// We pushed a matrix onto the PROJECTION stack earlier, we need to pop it.
glMatrixMode(GL_PROJECTION);
glPopMatrix();
// Swap the contents of the front and back buffers so we see what we just drew. This should only be done if double buffering is enabled.
gldrawable->swap_buffers();
gldrawable->gl_end();
return true;
}
float Viewer::rd(float high, float low){
return low + (((float)rand())/((float)RAND_MAX))*(high-low);
}
float Viewer::rad(float deg){
return deg*3.141592653589793/180;
}
void Viewer::randPart(float x, float y, float z){
Viewer::pt npt;
npt.x = x;
npt.y = y;
npt.z = z;
npt.vx = rd(0.5,-0.5);
npt.vy = rd(0.5,-0.1);
npt.vz = rd(0.5,-0.5);
npt.r = rd(1 , 0.8);
npt.g = rd(1 , 0.4);
npt.b = rd(1 , 0);
pts.push_back(npt);
}
void Viewer::randPart2(float x, float y, float z){
Viewer::pt npt;
npt.x = x;
npt.y = y;
npt.z = z;
npt.vx = rd(0.15,-0.15);
npt.vy = rd(0.25, 0);
npt.vz = rd(0.15,-0.15);
npt.r = rd(1 , 0.5);
npt.g = rd(1 , 0.2);
npt.b = rd(1 , 0);
pts.push_back(npt);
}
void Viewer::particles(){
for(int i=0; i<4; i++){
int r = game->rem[i];
if(r >= 0){
for(float x=-xOff+1; x<xOff-1; x+=1){
float xx = x;
float z = 0;
float y = 1.5 + r - yOff;
float nx, ny, nz;
float rads;
rads = rad(angleAxisZActive);
nx = xx*cos(rads) - y*sin(rads);
ny = xx*sin(rads) + y*cos(rads);
xx = nx;
y = ny;
rads = rad(angleAxisYActive);
nz = z*cos(rads) - xx*sin(rads);
nx = z*sin(rads) + xx*cos(rads);
z = nz;
xx = nx;
rads = rad(angleAxisXActive);
ny = y*cos(rads) - z*sin(rads);
nz = y*sin(rads) + z*cos(rads);
y = ny;
z = nz;
for(int c=0; c<40; c++){
randPart2(xx,y,z);
}
for(int c=0; c<20; c++){
randPart(xx,y,z);
}
}
game->rem[i] = -1;
}
}
std::vector<Viewer::pt> npts;
glLineWidth(rd(3 , 1));
glBegin(GL_LINES);
for(uint i=0; i<pts.size(); i++){
glColor4f(pts[i].r,pts[i].g,pts[i].b,1);
glVertex3f(pts[i].x,pts[i].y,pts[i].z);
pts[i].vy += grav;
pts[i].x += (pts[i].vx)/timeSlow;
pts[i].y += (pts[i].vy)/timeSlow;
pts[i].z += (pts[i].vz)/timeSlow;
glVertex3f(pts[i].x,pts[i].y,pts[i].z);
if(pts[i].y > floorHeight){
npts.push_back(pts[i]);
}else if(pts[i].vy < -0.2){
pts[i].vy = -0.33*pts[i].vy;
pts[i].y = floorHeight;
npts.push_back(pts[i]);
}
}
glEnd();
pts.swap(npts);
}
void Viewer::mainOrient(){
glScaled(scale,scale,scale);
glRotated(angleAxisXActive, 1.0, 0.0, 0.0);
glRotated(angleAxisYActive, 0.0, 1.0, 0.0);
glRotated(angleAxisZActive, 0.0, 0.0, 1.0);
glTranslated(-xOff, -yOff, 0.0);
}
void Viewer::reflOrient(){
glScaled(scale,-scale,scale);
glTranslated(0, 26.0, 0);
glRotated(angleAxisXActive, 1.0, 0.0, 0.0);
glRotated(angleAxisYActive, 0.0, 1.0, 0.0);
glRotated(angleAxisZActive, 0.0, 0.0, 1.0);
glTranslated(-xOff, -yOff, 0);
}
void Viewer::drawGround(){
glBegin(GL_QUADS);
glColor4f(0,0,0,1.0);
glVertex3f(-3*floorRadius,floorHeight,2*floorRadius);
glVertex3f(3*floorRadius,floorHeight,2*floorRadius);
glColor4f(0,0,0,0);
glVertex3f(3*floorRadius,floorHeight,-2*floorRadius);
glVertex3f(-3*floorRadius,floorHeight,-2*floorRadius);
glEnd();
glLineWidth(1);
glColor4f(1,1,1,0.2);
for(float x=-3*floorRadius; x<3*floorRadius; x+=4){
for(float z=-2*floorRadius; z<2*floorRadius; z+=3){
heXYZ(x,floorHeight + 0.1,z);
}
}
for(float x=-3*floorRadius+2; x<3*floorRadius+2; x+=4){
for(float z=-2*floorRadius-1.5; z<2*floorRadius; z+=3){
heXYZ(x,floorHeight + 0.1,z);
}
}
glBegin(GL_QUADS);
glColor4f(0.4,0.4,0.8,0);
glVertex3f(-3*floorRadius,floorHeight+0.2,-1*floorRadius);
glVertex3f(3*floorRadius,floorHeight+0.2,-1*floorRadius);
glColor4f(0.4,0.4,0.8,1.0);
glVertex3f(3*floorRadius,floorHeight+0.2,-2*floorRadius-3);
glVertex3f(-3*floorRadius,floorHeight+0.2,-2*floorRadius-3);
glEnd();
}
void Viewer::lighting(){
glShadeModel (GL_SMOOTH);
GLfloat mat_specular[] = {0.0, 0.0, 0.0, 1.0};
GLfloat mat_shininess[] = {50.0};
GLfloat light_position[] = {lightX, lightY, lightZ, 1};
glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular);
glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess);
glLightfv(GL_LIGHT0, GL_POSITION, light_position);
glLightf(GL_LIGHT1, GL_SPOT_CUTOFF, 10.0);
glLightf(GL_LIGHT1, GL_SPOT_EXPONENT, 2.0);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glEnable(GL_COLOR_MATERIAL);
glBegin(GL_TRIANGLES);
glVertex3f(lightX-0.2, lightY-0.2, lightZ);
glVertex3f(lightX+0.2, lightY-0.2, lightZ);
glVertex3f(lightX, lightY+0.2, lightZ);
glEnd();
}
// You'll be drawing unit cubes, so the game will have width 10 and height 24 (game = 20, stripe = 4). Let's translate the game so that we can draw it starting at (0,0) but have it appear centered in the window.
// Well edges: X[0 to 10] y[0 to 20]
// split drawstate with draw reflexion and draw extra
void Viewer::drawState(){
glColor4f(0.4,0.4,0.4,1);
for(float x=0.5; x<12; x+=1){
unitCube(x,0.5,0,renderMode);
}
for(float y=1.5; y<21; y+=1){
unitCube(0.5,y,0,renderMode);
unitCube(11.5,y,0,renderMode);
}
for(int x=0; x<boardWidth; x++){
for(int y=0; y<boardHeight+4; y++){
if(game->get(y,x) >= 0){
switch(game->get(y,x)){
case 0:
glColor4f(mainColor,mainColor,mainColor,1);
break;
case 1:
glColor4f(mainColor,mainColor,subColor,1);
break;
case 2:
glColor4f(mainColor,subColor,mainColor,1);
break;
case 3:
glColor4f(mainColor,subColor,subColor,1);
break;
case 4:
glColor4f(subColor,mainColor,mainColor,1);
break;
case 5:
glColor4f(subColor,mainColor,subColor,1);
break;
case 6:
glColor4f(subColor,subColor,mainColor,1);
break;
case 7:
glColor4f(subColor,subColor,subColor,1);
break;
}
unitCube((float)x+1.5,(float)y+1.5,0,renderMode);
}
}
}
}
struct compClass{
bool operator() (Viewer::shineCube a, Viewer::shineCube b){
return a.d > b.d;
}
}compare;
void Viewer::drawShine(){
shines.clear();
for(int x=0; x<boardWidth; x++){
for(int y=0; y<boardHeight+2; y++){
if(game->get(y,x) < 0){
Viewer::shineCube nc;
nc.x = (float)x+1.5;
nc.y = (float)y+1.5;
nc.d = (xOff - nc.x)*(xOff - nc.x) + (yOff - nc.y)*(yOff - nc.y);
shines.push_back(nc);
}
}
}
//sort based so that be can render those with furthest distance first
std::sort(shines.begin(), shines.end(), compare);
//loop and call unitShine
for(uint i=0; i<shines.size(); i++){
unitShine(shines[i].x, shines[i].y, 0, renderMode);
}
}
void Viewer::newGame(){
gameEnd = false;
game->reset();
}
void Viewer::setMode(Viewer::cubeType type){
renderMode = type;
}
void Viewer::keyHandle(GdkEventKey* e){
float move = 0.5;
switch (e->keyval){
case 'w':case 'W':
renderMode = Viewer::wire;break;
case 'i':case 'I':
lightY += move;break;
case 'j':case 'J':
lightX -= move;break;
case 'k':case 'K':
lightY -= move;break;
case 'l':case 'L':
lightX += move;break;
case 'r':case 'R':
viewInit();break;
case 'n':case 'N':
newGame();break;
case 'f':case 'F':
renderMode = Viewer::face;break;
case 'm':case 'M':
renderMode = Viewer::multi;break;
case 't':case 'T':
game->rem[0] = 0;
game->rem[1] = 18;
break;
case ' ':
if(!gameEnd){
game->drop();
game->tick();
}
break;
case GDK_Left:
if(!gameEnd)
game->moveLeft();break;
case GDK_Right:
if(!gameEnd)
game->moveRight();break;
case GDK_Up:
if(!gameEnd)
game->rotateCCW();break;
case GDK_Down:
if(!gameEnd)
game->rotateCW();break;
}
}
bool Viewer::on_button_press_event(GdkEventButton* e){
mBaseX = e->x;
mx = mBaseX;
mbx = mBaseX;
mDown = true;
angleAxisXActive = angleAxisX;
angleAxisYActive = angleAxisY;
angleAxisZActive = angleAxisZ;
scale = baseScale;
if(e->state & GDK_SHIFT_MASK){
trans = Viewer::scl;
}else{
switch(e->button){
case 1:
trans = Viewer::xrot;break;
case 2:
trans = Viewer::yrot;break;
case 3:
trans = Viewer::zrot;break;
}
}
vX = 0;
return true;
}
bool Viewer::on_button_release_event(GdkEventButton* e){
mDown = false;
angleAxisX = angleAxisXActive;
angleAxisY = angleAxisYActive;
angleAxisZ = angleAxisZActive;
baseScale = scale;
return true;
}
bool Viewer::on_motion_notify_event(GdkEventMotion* e){
mx = e->x;
return true;
}
void Viewer::heXYZ(float x, float y, float z){
glBegin(GL_LINE_LOOP);
float h = 1.4;
float v = 0.4;
glNormal3f(0,brt*scale,0);
glVertex3f(x-h,y,z);
glVertex3f(x-v,y,z-h);
glVertex3f(x+v,y,z-h);
glVertex3f(x+h,y,z);
glVertex3f(x+v,y,z+h);
glVertex3f(x-v,y,z+h);
glEnd();
}
//gotta fix faces to have weighted normals
void Viewer::polyFace(pt3f p1, pt3f p2, pt3f p3, pt3f p4, pt3f p5, pt3f p6, pt3f p7, pt3f p8){
float mx = ((p1.n.x + p2.n.x + p3.n.x + p4.n.x + p5.n.x + p6.n.x + p7.n.x + p8.n.x)/8)*faceWeight;
float my = ((p1.n.y + p2.n.y + p3.n.y + p4.n.y + p5.n.y + p6.n.y + p7.n.y + p8.n.y)/8)*faceWeight;
float mz = ((p1.n.z + p2.n.z + p3.n.z + p4.n.z + p5.n.z + p6.n.z + p7.n.z + p8.n.z)/8)*faceWeight;
glBegin(GL_POLYGON);
glNormal3f((p1.n.x+mx)*brt*scale,(p1.n.y+my)*brt*scale,(p1.n.z+mz)*brt*scale);
glVertex3f(p1.x,p1.y,p1.z);
glNormal3f((p2.n.x+mx)*brt*scale,(p2.n.y+my)*brt*scale,(p2.n.z+mz)*brt*scale);
glVertex3f(p2.x,p2.y,p2.z);
glNormal3f((p3.n.x+mx)*brt*scale,(p3.n.y+my)*brt*scale,(p3.n.z+mz)*brt*scale);
glVertex3f(p3.x,p3.y,p3.z);
glNormal3f((p4.n.x+mx)*brt*scale,(p4.n.y+my)*brt*scale,(p4.n.z+mz)*brt*scale);
glVertex3f(p4.x,p4.y,p4.z);
glNormal3f((p5.n.x+mx)*brt*scale,(p5.n.y+my)*brt*scale,(p5.n.z+mz)*brt*scale);
glVertex3f(p5.x,p5.y,p5.z);
glNormal3f((p6.n.x+mx)*brt*scale,(p6.n.y+my)*brt*scale,(p6.n.z+mz)*brt*scale);
glVertex3f(p6.x,p6.y,p6.z);
glNormal3f((p7.n.x+mx)*brt*scale,(p7.n.y+my)*brt*scale,(p7.n.z+mz)*brt*scale);
glVertex3f(p7.x,p7.y,p7.z);
glNormal3f((p8.n.x+mx)*brt*scale,(p8.n.y+my)*brt*scale,(p8.n.z+mz)*brt*scale);
glVertex3f(p8.x,p8.y,p8.z);
glEnd();
}
void Viewer::polyWire(pt3f p1, pt3f p2, pt3f p3, pt3f p4, pt3f p5, pt3f p6, pt3f p7, pt3f p8){
float mx = ((p1.n.x + p2.n.x + p3.n.x + p4.n.x + p5.n.x + p6.n.x + p7.n.x + p8.n.x)/8)*faceWeight;
float my = ((p1.n.y + p2.n.y + p3.n.y + p4.n.y + p5.n.y + p6.n.y + p7.n.y + p8.n.y)/8)*faceWeight;
float mz = ((p1.n.z + p2.n.z + p3.n.z + p4.n.z + p5.n.z + p6.n.z + p7.n.z + p8.n.z)/8)*faceWeight;
glBegin(GL_LINE_LOOP);
glNormal3f((p1.n.x+mx)*brt*scale,(p1.n.y+my)*brt*scale,(p1.n.z+mz)*brt*scale);
glVertex3f(p1.x,p1.y,p1.z);
glNormal3f((p2.n.x+mx)*brt*scale,(p2.n.y+my)*brt*scale,(p2.n.z+mz)*brt*scale);
glVertex3f(p2.x,p2.y,p2.z);
glNormal3f((p3.n.x+mx)*brt*scale,(p3.n.y+my)*brt*scale,(p3.n.z+mz)*brt*scale);
glVertex3f(p3.x,p3.y,p3.z);
glNormal3f((p4.n.x+mx)*brt*scale,(p4.n.y+my)*brt*scale,(p4.n.z+mz)*brt*scale);
glVertex3f(p4.x,p4.y,p4.z);
glNormal3f((p5.n.x+mx)*brt*scale,(p5.n.y+my)*brt*scale,(p5.n.z+mz)*brt*scale);
glVertex3f(p5.x,p5.y,p5.z);
glNormal3f((p6.n.x+mx)*brt*scale,(p6.n.y+my)*brt*scale,(p6.n.z+mz)*brt*scale);
glVertex3f(p6.x,p6.y,p6.z);
glNormal3f((p7.n.x+mx)*brt*scale,(p7.n.y+my)*brt*scale,(p7.n.z+mz)*brt*scale);
glVertex3f(p7.x,p7.y,p7.z);
glNormal3f((p8.n.x+mx)*brt*scale,(p8.n.y+my)*brt*scale,(p8.n.z+mz)*brt*scale);
glVertex3f(p8.x,p8.y,p8.z);
glEnd();
}
void Viewer::triFace(pt3f p1, pt3f p2, pt3f p3){
float mx = ((p1.n.x + p2.n.x + p3.n.x)/3)*faceWeight;
float my = ((p1.n.y + p2.n.y + p3.n.y)/3)*faceWeight;
float mz = ((p1.n.z + p2.n.z + p3.n.z)/3)*faceWeight;
glNormal3f((p1.n.x+mx)*brt*scale,(p1.n.y+my)*brt*scale,(p1.n.z+mz)*brt*scale);
glVertex3f(p1.x,p1.y,p1.z);
glNormal3f((p2.n.x+mx)*brt*scale,(p2.n.y+my)*brt*scale,(p2.n.z+mz)*brt*scale);
glVertex3f(p2.x,p2.y,p2.z);
glNormal3f((p3.n.x+mx)*brt*scale,(p3.n.y+my)*brt*scale,(p3.n.z+mz)*brt*scale);
glVertex3f(p3.x,p3.y,p3.z);
}
void Viewer::triWire(pt3f p1, pt3f p2, pt3f p3){
float mx = ((p1.n.x + p2.n.x + p3.n.x)/3)*faceWeight;
float my = ((p1.n.y + p2.n.y + p3.n.y)/3)*faceWeight;
float mz = ((p1.n.z + p2.n.z + p3.n.z)/3)*faceWeight;
glBegin(GL_LINE_LOOP);
glNormal3f((p1.n.x+mx)*brt*scale,(p1.n.y+my)*brt*scale,(p1.n.z+mz)*brt*scale);
glVertex3f(p1.x,p1.y,p1.z);
glNormal3f((p2.n.x+mx)*brt*scale,(p2.n.y+my)*brt*scale,(p2.n.z+mz)*brt*scale);
glVertex3f(p2.x,p2.y,p2.z);
glNormal3f((p3.n.x+mx)*brt*scale,(p3.n.y+my)*brt*scale,(p3.n.z+mz)*brt*scale);
glVertex3f(p3.x,p3.y,p3.z);
glEnd();
}
void Viewer::shine(pt3f p1, pt3f p2){
glNormal3f(0,5,0);
glColor4f(1,1,1,0);
glVertex3f(p1.x,p1.y,p1.z);
glVertex3f(p2.x,p2.y,p2.z);
glColor4f(1,1,1,0.3);
glVertex3f(p2.x,p2.y,p2.z+20);
glVertex3f(p1.x,p1.y,p1.z+20);
glVertex3f(p1.x,p1.y,p1.z+20);
glVertex3f(p2.x,p2.y,p2.z+20);
glColor4f(1,1,1,0);
glVertex3f(p2.x,p2.y,p2.z+60);
glVertex3f(p1.x,p1.y,p1.z+60);
}
void Viewer::unitShine(float x, float y, float z, Viewer::cubeType type){
Viewer::pt3f btrz; btrz.x = x+edge; btrz.y = y+edge; btrz.z = z-edge+coff; btrz.n = nbtrz;
Viewer::pt3f btlz; btlz.x = x-edge; btlz.y = y+edge; btlz.z = z-edge+coff; btlz.n = nbtlz;
Viewer::pt3f bbrz; bbrz.x = x+edge; bbrz.y = y-edge; bbrz.z = z-edge+coff; bbrz.n = nbbrz;
Viewer::pt3f bblz; bblz.x = x-edge; bblz.y = y-edge; bblz.z = z-edge+coff; bblz.n = nbblz;
//send in naive normal and calculate weighted normal in the actual draw
switch(type){
case Viewer::wire:
break;
case Viewer::face:
glBegin(GL_QUADS);
shine(btlz,bblz);
shine(btlz,btrz);
shine(bbrz,btrz);
shine(bbrz,bblz);
glEnd();
break;
case Viewer::multi:
break;
}
}
void Viewer::unitCube(float x, float y, float z, Viewer::cubeType type){
Viewer::pt3f ftrx; ftrx.x = x+edge-coff; ftrx.y = y+edge; ftrx.z = z+edge; ftrx.n = nftrx;
Viewer::pt3f ftry; ftry.x = x+edge; ftry.y = y+edge-coff; ftry.z = z+edge; ftry.n = nftry;
Viewer::pt3f ftrz; ftrz.x = x+edge; ftrz.y = y+edge; ftrz.z = z+edge-coff; ftrz.n = nftrz;
Viewer::pt3f ftlx; ftlx.x = x-edge+coff; ftlx.y = y+edge; ftlx.z = z+edge; ftlx.n = nftlx;
Viewer::pt3f ftly; ftly.x = x-edge; ftly.y = y+edge-coff; ftly.z = z+edge; ftly.n = nftly;
Viewer::pt3f ftlz; ftlz.x = x-edge; ftlz.y = y+edge; ftlz.z = z+edge-coff; ftlz.n = nftlz;
Viewer::pt3f fbrx; fbrx.x = x+edge-coff; fbrx.y = y-edge; fbrx.z = z+edge; fbrx.n = nfbrx;
Viewer::pt3f fbry; fbry.x = x+edge; fbry.y = y-edge+coff; fbry.z = z+edge; fbry.n = nfbry;
Viewer::pt3f fbrz; fbrz.x = x+edge; fbrz.y = y-edge; fbrz.z = z+edge-coff; fbrz.n = nfbrz;
Viewer::pt3f fblx; fblx.x = x-edge+coff; fblx.y = y-edge; fblx.z = z+edge; fblx.n = nfblx;
Viewer::pt3f fbly; fbly.x = x-edge; fbly.y = y-edge+coff; fbly.z = z+edge; fbly.n = nfbly;
Viewer::pt3f fblz; fblz.x = x-edge; fblz.y = y-edge; fblz.z = z+edge-coff; fblz.n = nfblz;
Viewer::pt3f btrx; btrx.x = x+edge-coff; btrx.y = y+edge; btrx.z = z-edge; btrx.n = nbtrx;
Viewer::pt3f btry; btry.x = x+edge; btry.y = y+edge-coff; btry.z = z-edge; btry.n = nbtry;
Viewer::pt3f btrz; btrz.x = x+edge; btrz.y = y+edge; btrz.z = z-edge+coff; btrz.n = nbtrz;
Viewer::pt3f btlx; btlx.x = x-edge+coff; btlx.y = y+edge; btlx.z = z-edge; btlx.n = nbtlx;
Viewer::pt3f btly; btly.x = x-edge; btly.y = y+edge-coff; btly.z = z-edge; btly.n = nbtly;
Viewer::pt3f btlz; btlz.x = x-edge; btlz.y = y+edge; btlz.z = z-edge+coff; btlz.n = nbtlz;
Viewer::pt3f bbrx; bbrx.x = x+edge-coff; bbrx.y = y-edge; bbrx.z = z-edge; bbrx.n = nbbrx;
Viewer::pt3f bbry; bbry.x = x+edge; bbry.y = y-edge+coff; bbry.z = z-edge; bbry.n = nbbry;
Viewer::pt3f bbrz; bbrz.x = x+edge; bbrz.y = y-edge; bbrz.z = z-edge+coff; bbrz.n = nbbrz;
Viewer::pt3f bblx; bblx.x = x-edge+coff; bblx.y = y-edge; bblx.z = z-edge; bblx.n = nbblx;
Viewer::pt3f bbly; bbly.x = x-edge; bbly.y = y-edge+coff; bbly.z = z-edge; bbly.n = nbbly;
Viewer::pt3f bblz; bblz.x = x-edge; bblz.y = y-edge; bblz.z = z-edge+coff; bblz.n = nbblz;
//send in naive normal and calculate weighted normal in the actual draw
switch(type){
case Viewer::wire:
glLineWidth(1);
polyWire(ftly,ftlx,ftrx,ftry,fbry,fbrx,fblx,fbly);
polyWire(btly,btlx,btrx,btry,bbry,bbrx,bblx,bbly);
polyWire(btlz,btlx,btrx,btrz,ftrz,ftrx,ftlx,ftlz);
polyWire(bblz,bblx,bbrx,bbrz,fbrz,fbrx,fblx,fblz);
polyWire(ftry,ftrz,btrz,btry,bbry,bbrz,fbrz,fbry);
polyWire(ftly,ftlz,btlz,btly,bbly,bblz,fblz,fbly);
triWire(ftrx,ftry,ftrz);
triWire(ftlx,ftly,ftlz);
triWire(fbrx,fbry,fbrz);
triWire(fblx,fbly,fblz);
triWire(btrx,btry,btrz);
triWire(btlx,btly,btlz);
triWire(bbrx,bbry,bbrz);
triWire(bblx,bbly,bblz);
break;
case Viewer::face:
polyFace(ftly,ftlx,ftrx,ftry,fbry,fbrx,fblx,fbly);
polyFace(btly,btlx,btrx,btry,bbry,bbrx,bblx,bbly);
polyFace(btlz,btlx,btrx,btrz,ftrz,ftrx,ftlx,ftlz);
polyFace(bblz,bblx,bbrx,bbrz,fbrz,fbrx,fblx,fblz);
polyFace(ftry,ftrz,btrz,btry,bbry,bbrz,fbrz,fbry);
polyFace(ftly,ftlz,btlz,btly,bbly,bblz,fblz,fbly);
glBegin(GL_TRIANGLES);
triFace(ftrx,ftry,ftrz);
triFace(ftlx,ftly,ftlz);
triFace(fbrx,fbry,fbrz);
triFace(fblx,fbly,fblz);
triFace(btrx,btry,btrz);
triFace(btlx,btly,btlz);
triFace(bbrx,bbry,bbrz);
triFace(bblx,bbly,bblz);
glEnd();
break;
case Viewer::multi:
glColor4f(mainColor,mainColor,subColor,1);
polyFace(ftly,ftlx,ftrx,ftry,fbry,fbrx,fblx,fbly);
glColor4f(mainColor,subColor,mainColor,1);
polyFace(btly,btlx,btrx,btry,bbry,bbrx,bblx,bbly);
glColor4f(mainColor,subColor,subColor,1);
polyFace(btlz,btlx,btrx,btrz,ftrz,ftrx,ftlx,ftlz);
glColor4f(subColor,mainColor,mainColor,1);
polyFace(bblz,bblx,bbrx,bbrz,fbrz,fbrx,fblx,fblz);
glColor4f(subColor,mainColor,subColor,1);
polyFace(ftry,ftrz,btrz,btry,bbry,bbrz,fbrz,fbry);
glColor4f(subColor,subColor,mainColor,1);
polyFace(ftly,ftlz,btlz,btly,bbly,bblz,fblz,fbly);
glBegin(GL_TRIANGLES);
glColor4f(mainColor,mainColor,subColor,1);
triFace(ftrx,ftry,ftrz);
triFace(ftlx,ftly,ftlz);
triFace(fbrx,fbry,fbrz);
triFace(fblx,fbly,fblz);
glColor4f(mainColor,subColor,mainColor,1);
triFace(btrx,btry,btrz);
triFace(btlx,btly,btlz);
triFace(bbrx,bbry,bbrz);
triFace(bblx,bbly,bblz);
glEnd();
break;
}
}
<file_sep>/src/appwindow.hpp
/*
name: <NAME>
id: r7sun
student number: 20343049
*/
#ifndef APPWINDOW_HPP
#define APPWINDOW_HPP
#include <gtkmm.h>
#include "viewer.hpp"
class AppWindow : public Gtk::Window {
public:
AppWindow();
protected:
virtual bool on_key_press_event( GdkEventKey *ev );
private:
// A "vertical box" which holds everything in our window
Gtk::VBox m_vbox;
// The menubar, with all the menus at the top of the window
Gtk::MenuBar m_menubar;
Gtk::RadioButtonGroup tools;
Gtk::RadioButtonGroup speeds;
Glib::RefPtr<Gtk::RadioMenuItem> m_low_elem;
Glib::RefPtr<Gtk::RadioMenuItem> m_med_elem;
Glib::RefPtr<Gtk::RadioMenuItem> m_high_elem;
Glib::RefPtr<Gtk::RadioMenuItem> m_face_elem;
Glib::RefPtr<Gtk::RadioMenuItem> m_wire_elem;
Glib::RefPtr<Gtk::RadioMenuItem> m_mult_elem;
Gtk::Menu_Helpers::RadioMenuElem m_low;
Gtk::Menu_Helpers::RadioMenuElem m_med;
Gtk::Menu_Helpers::RadioMenuElem m_high;
Gtk::Menu_Helpers::RadioMenuElem m_face;
Gtk::Menu_Helpers::RadioMenuElem m_wire;
Gtk::Menu_Helpers::RadioMenuElem m_mult;
// Each menu itself
Gtk::Menu m_menu_app;
Gtk::Menu m_menu_draw;
Gtk::Menu m_menu_speed;
Gtk::Menu m_menu_blind;
// The main OpenGL area
Viewer m_viewer;
sigc::slot1<void, Viewer::cubeType> mode_slot;
sigc::slot1<void, int> speed_slot;
sigc::slot0<bool> tick;
sigc::slot0<bool> tickGame;
sigc::connection tickConn;
void speed(int s);
void dmode(int t);
void reMenu();
};
#endif
<file_sep>/src/appwindow.cpp
/*
name: <NAME>
id: r7sun
student number: 20343049
*/
#include "appwindow.hpp"
#include <iostream>
AppWindow::AppWindow():
m_low(speeds,"_Slow", Gtk::AccelKey("1"), sigc::bind(sigc::mem_fun(*this, &AppWindow::speed), 500)),
m_med(speeds,"_Med", Gtk::AccelKey("2"), sigc::bind(sigc::mem_fun(*this, &AppWindow::speed), 300)),
m_high(speeds,"_High", Gtk::AccelKey("3"), sigc::bind(sigc::mem_fun(*this, &AppWindow::speed), 100)),
m_face(tools,"_Face", Gtk::AccelKey("f"), sigc::bind(sigc::mem_fun(*this, &AppWindow::dmode), 1)),
m_wire(tools,"_Wire-frame", Gtk::AccelKey("w"), sigc::bind(sigc::mem_fun(*this, &AppWindow::dmode), 2)),
m_mult(tools,"_Multicolored", Gtk::AccelKey("m"), sigc::bind(sigc::mem_fun(*this, &AppWindow::dmode), 3))
{
//set_title("488 Tetrominoes on the Wall");
set_title("GTKmm gave me terminal cancer");
// A utility class for constructing things that go into menus, which we'll set up next.
using Gtk::Menu_Helpers::MenuElem;
using Gtk::Menu_Helpers::RadioMenuElem;
//update timer
tick = sigc::mem_fun(m_viewer, &Viewer::update);
Glib::signal_timeout().connect(tick, 15);
tickGame = sigc::mem_fun(m_viewer, &Viewer::updateGame);
tickConn = Glib::signal_timeout().connect(tickGame, 500);
// Set up the application menu:
// The slot we use here just causes AppWindow::hide() on this, which shuts down the application.
m_menu_app.items().push_back(MenuElem("_Quit", Gtk::AccelKey("q"), sigc::mem_fun(*this, &AppWindow::hide)));
m_menu_app.items().push_back(MenuElem("_New Game", Gtk::AccelKey("n"), sigc::mem_fun(m_viewer, &Viewer::newGame)));
m_menu_app.items().push_back(MenuElem("_Reset", Gtk::AccelKey("r"), sigc::mem_fun(m_viewer, &Viewer::viewInit)));
m_menu_draw.items().push_back(m_face);
m_menu_draw.items().push_back(m_wire);
m_menu_draw.items().push_back(m_mult);
m_face_elem = Glib::RefPtr<Gtk::RadioMenuItem>::cast_dynamic<Gtk::MenuItem>(m_face.get_child());
m_wire_elem = Glib::RefPtr<Gtk::RadioMenuItem>::cast_dynamic<Gtk::MenuItem>(m_wire.get_child());
m_mult_elem = Glib::RefPtr<Gtk::RadioMenuItem>::cast_dynamic<Gtk::MenuItem>(m_mult.get_child());
m_menu_speed.items().push_back(m_low);
m_menu_speed.items().push_back(m_med);
m_menu_speed.items().push_back(m_high);
m_low_elem = Glib::RefPtr<Gtk::RadioMenuItem>::cast_dynamic<Gtk::MenuItem>(m_low.get_child());
m_med_elem = Glib::RefPtr<Gtk::RadioMenuItem>::cast_dynamic<Gtk::MenuItem>(m_med.get_child());
m_high_elem = Glib::RefPtr<Gtk::RadioMenuItem>::cast_dynamic<Gtk::MenuItem>(m_high.get_child());
m_menu_blind.items().push_back(MenuElem("_Toggle Blinding Light", Gtk::AccelKey("b"), sigc::mem_fun(m_viewer, &Viewer::toggleBlind)));
// Set up the menu bar
m_menubar.items().push_back(Gtk::Menu_Helpers::MenuElem("_Application", m_menu_app));
m_menubar.items().push_back(Gtk::Menu_Helpers::MenuElem("_Draw Mode", m_menu_draw));
m_menubar.items().push_back(Gtk::Menu_Helpers::MenuElem("_Speed", m_menu_speed));
m_menubar.items().push_back(Gtk::Menu_Helpers::MenuElem("_Blinding Mode", m_menu_blind));
// Pack in our widgets:
// First add the vertical box as our single "top" widget
add(m_vbox);
// Put the menubar on the top, and make it as small as possible
m_vbox.pack_start(m_menubar, Gtk::PACK_SHRINK);
// Put the viewer below the menubar. pack_start "grows" the widget by default, so it'll take up the rest of the window.
m_viewer.set_size_request(400,600);
m_vbox.pack_start(m_viewer);
show_all();
}
void AppWindow::speed(int s){
tickConn.disconnect();
tickConn = Glib::signal_timeout().connect(tickGame, s);
}
void AppWindow::dmode(int type){
switch(type){
case 1:
m_viewer.setMode(Viewer::face);
break;
case 2:
m_viewer.setMode(Viewer::wire);
break;
case 3:
m_viewer.setMode(Viewer::multi);
break;
}
}
void AppWindow::reMenu(){
m_menu_speed.items().pop_back();
m_menu_speed.items().pop_back();
m_menu_speed.items().pop_back();
m_menu_draw.items().pop_back();
m_menu_draw.items().pop_back();
m_menu_draw.items().pop_back();
m_menu_speed.items().push_back(m_low);
m_menu_speed.items().push_back(m_med);
m_menu_speed.items().push_back(m_high);
m_menu_draw.items().push_back(m_face);
m_menu_draw.items().push_back(m_wire);
m_menu_draw.items().push_back(m_mult);
}
bool AppWindow::on_key_press_event(GdkEventKey *e){
switch(e->keyval){
case '1':
m_low_elem->set_active(true);
//reMenu();
break;
case '2':
m_med_elem->set_active(true);
//reMenu();
break;
case '3':
m_high_elem->set_active(true);
//reMenu();
break;
case 'w':case 'W':
m_wire_elem->set_active(true);
//reMenu();
break;
case 'f':case 'F':
m_face_elem->set_active(true);
//reMenu();
break;
case 'm':case 'M':
m_mult_elem->set_active(true);
//reMenu();
break;
}
m_viewer.keyHandle(e);
return Gtk::Window::on_key_press_event(e);
}
|
d6b9398cac501d6b3e1f3702eb371df2da9a0dc1
|
[
"C++"
] | 4
|
C++
|
ray0sunshine/Tetris
|
57c50640d52c0e1295c7a0040c2f21cdf92dbeb2
|
e007c698244a519c544b24c0fb63dfbe052b9575
|
refs/heads/master
|
<repo_name>mytrile/bank_account_tools<file_sep>/bank_account_tools.gemspec
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'bank_account_tools/version'
Gem::Specification.new do |spec|
spec.name = 'bank_account_tools'
spec.version = BankAccountTools::VERSION
spec.authors = ['<NAME>', 'Kevin']
spec.email = ['<EMAIL>', '<EMAIL>']
spec.summary = %q{Bank account tools for dealing with IBANs/BICs}
spec.description = %q{Bank account tools for dealing with IBANs/BICs: information, validation and formatting.}
spec.homepage = 'https://github.com/mytrile/bank_account_tools'
spec.license = 'MIT'
spec.files = `git ls-files`.split($/)
spec.test_files = spec.files.grep(%r{^spec/})
spec.require_paths = ['lib']
spec.add_development_dependency 'bundler', '~> 1.13'
spec.add_development_dependency 'rake', '~> 12.0'
spec.add_development_dependency 'rspec', '~> 3.5'
spec.add_development_dependency 'activemodel', '~> 4.0'
end
<file_sep>/spec/iban_spec.rb
require 'spec_helper'
describe BankAccountTools::IBAN do
let(:iban) { BankAccountTools::IBAN.new('FR14 2004 1010 0505 0001 3M026 06') }
it 'is valid from class method' do
expect(BankAccountTools::IBAN.valid?('FR14 2004 1010 0505 0001 3M026 06')).to be_truthy
end
it 'loads the validation rules' do
expect(BankAccountTools.load_specifications(:iban)).to be_present
expect(BankAccountTools.load_specifications(:iban)).to be_kind_of(Hash)
end
it 'should return the county code' do
expect(iban.country_code).to eq('FR')
end
it 'should return the check digits' do
expect(iban.check_digits).to eq('14')
end
it 'should return the BBAN' do
expect(iban.bban).to be_a(BankAccountTools::BBAN)
expect(iban.bban.to_s).to eq('20041010050500013M02606')
end
it 'should convert to integer value' do
expect(iban.to_i).to eq(200410100505000132202606152714)
end
it 'should convert to string' do
expect(iban.to_s).to eq('FR1420041010050500013M02606')
end
it 'should convert to formatted string' do
expect(iban.to_s(true)).to eq('FR14 2004 1010 0505 0001 3M02 606')
end
it 'respond_to? account_number' do
expect(iban.respond_to?(:account_number)).to be_truthy
end
it 'returns account_number' do
expect(iban.account_number).to eq('0500013M026')
end
it 'returns bank_identifier' do
expect(iban.bank_identifier).to eq('20041')
end
it 'returns branch_identifier' do
expect(iban.branch_identifier).to eq('01005')
end
it 'knows which countries use IBAN' do
expect(iban.country_applies_iban?).to be_truthy
expect(BankAccountTools::IBAN.new('ZZ99 123456790').country_applies_iban?).to be_falsey
end
[
'AL47212110090000000235698741',
'AD12 00012030200359100100',
'AT611904300234573201',
'BE68539007547034',
'BA391290079401028494',
'BG80BNBG96611020345678',
'HR1210010051863000160',
'CY17002001280000001200527600',
'CZ6508000000192000145399',
'DK5000400440116243',
'EE382200221020145685',
'FO1464600009692713',
'FI2112345600000785',
'FR1420041010050500013M02606',
'GE29NB0000000101904917',
'DE89370400440532013000',
'GI75NWBK000000007099453',
'GR1601101250000000012300695',
'GL8964710001000206',
'HU42117730161111101800000000',
'IS140159260076545510730339',
'IE29AIBK93115212345678',
'IT60X0542811101000000123456',
'LV80BANK0000435195001',
'LI21088100002324013AA',
'LT121000011101001000',
'LU280019400644750000',
'MK07300000000042425',
'MT84MALT011000012345MTLCAST001S',
'MD24AG000225100013104168',
'MC5813488000010051108001292',
'ME25505000012345678951',
'NL91ABNA0417164300',
'NO9386011117947',
'PL27114020040000300201355387',
'PT50000201231234567890154',
'RO49AAAA1B31007593840000',
'SM86U0322509800000000270100',
'RS35260005601001611379',
'SK3112000000198742637541',
'SI56191000000123438',
'ES9121000418450200051332',
'SE3550000000054910000003',
'CH9300762011623852957',
'UA573543470006762462054925026',
'GB29NWBK60161331926819',
'DZ4000400174401001050486',
'AO06000600000100037131174',
'AZ21NABZ00000000137010001944',
'BH29BMAG1299123456BH00',
'BJ11B00610100400271101192591',
'BR9700360305000010009795493P1',
'VG96VPVG0000012345678901',
'BF1030134020015400945000643',
'BI43201011067444',
'CM2110003001000500000605306',
'CV64000300004547069110176',
'FR7630007000110009970004942',
'CG5230011000202151234567890',
'CR0515202001026284066',
'DO28BAGR00000001212453611324',
'EG1100006001880800100014553',
'GA2140002000055602673300064',
'GT82TRAJ01020000001210029690',
'IR580540105180021273113007',
'IL620108000000099999999',
'CI05A00060174100178530011852',
'KZ176010251000042993',
'KW74NBOK0000000000001000372151',
'LB30099900000001001925579115',
'MG4600005030010101914016056',
'ML03D00890170001002120000447',
'MR1300012000010000002037372',
'MU17BOMM0101101030300200000MUR',
'MZ59000100000011834194157',
'PK24SCBL0000001171495101',
'PS92PALS000000000400123456702',
'PT50000200000163099310355',
'SA0380000000608010167519',
'SN12K00100152000025690007542',
'TN5914207207100707129648',
'TR330006100519786457841326',
'AE260211000000230064016',
'XK051212012345678906',
'JO94CBJO0010000000000131000302',
'QA58DOHB00001234567890ABCDEFG',
'TL380030000000025923744',
'SC18SSCB11010000000000001497USD',
'ST23000200000289355710148',
'LC55HEMM000100010012001200023015',
].each do |code|
describe code do
it 'is valid' do
expect(BankAccountTools::IBAN.new(code)).to be_valid
end
end
end
end
<file_sep>/spec/spec_helper.rb
require 'active_model'
require 'bank_account_tools/iban'
require 'bank_account_tools/bic'
require 'bank_account_tools/contact'
<file_sep>/README.md
# BankAccountTools
IBAN & BIC information, validation and formatting. Ships with ActiveModel validators.
Fork of [https://github.com/max-power/bank](max-power/bank) with rspec and custom matchers
## Installation
Add this line to your application's Gemfile:
gem 'bank_account_tools'
And then execute:
$ bundle
## Usage
### BankAccountTools::IBAN
#### General usage
```ruby
require 'bank_account_tools/iban'
iban = BankAccountTools::IBAN.new('DE89 3704 0044 0532 0130 00')
iban.country_code # 'DE'
iban.check_digits # '89'
iban.bban # <BankAccountTools::BBAN...>
iban.bban.to_s # '370400440532013000'
iban.account_number # '0532013000'
iban.bank_identifier # '37040044'
iban.valid? # true
iban.to_s # 'DE89370400440532013000'
iban.to_s(true) # 'DE89 3704 0044 0532 0130 00'
iban.to_i # 370400440532013000131489
# or
BankAccountTools::IBAN.valid? 'DE89 3704 0044 0532 0130 00' # true
```
#### ActiveModel Validator
```ruby
class BankAccount
include ActiveModel::Model
validates :iban, iban: true
end
```
#### RSpec matcher
```ruby
describe BankAccount do
it { should validae_iban(:iban) }
end
```
---
### BankAccountTools::BIC
#### General usage
```ruby
require 'bank_account_tools/bic'
bic = BankAccountTools::BIC.new('BYLADEM1203')
bic.bank_code # "BYLA"
bic.country_code # "DE"
bic.location_code # "M1"
bic.branch_code # "203"
bic.to_s # "BYLADEM1203"
bic.to_s(true) # "BYLA DE M1 203"
bic.valid? # true
# or
BankAccountTools::IBAN.valid? 'DE89 3704 0044 0532 0130 00' # true
```
#### ActiveModel Validator
```ruby
class BankAccount
include ActiveModel::Model
validates :bic, bic: true
end
```
#### RSpec matcher
```ruby
describe BankAccount do
it { should validae_bic(:bic) }
end
```
### BankAccountTools::Contact
```ruby
require 'bank_account_tools/contact' # this requires 'iban' and 'bic'
# paramters: IBAN, BIC
contact = BankAccountTools::Contact.new('DE89 3704 0044 0532 0130 00', 'BYLADEM1203')
contact.iban # <BankAccountTools::IBAN...>
contact.bic # <BankAccountTools::BIC...>
contact.to_h # {:iban=>"DE89370400440532013000", :bic=>"BYLADEM1203"}
contact.to_a # ["DE89370400440532013000", "BYLADEM1203"]
contact.valid? # true
```
## Testing
The default rake task will run the rspec suite
```sh
$ rake
```
## Contributing
1. Fork it ( http://github.com/mytrile/bank_account_tools/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request
## Credits
Enhanced and maintained by [<NAME>](https://github.com/mytrile) [<EMAIL>](mailto:<EMAIL>)
Many thanks to original - [https://github.com/max-power/bank](max-power/bank)
<file_sep>/lib/bank_account_tools/matchers/active_model/have_valid_iban.rb
RSpec::Matchers.define :have_valid_iban do |attribute|
match do |actual|
expect(actual).to be_invalid
expect(actual.errors[attribute.to_sym]).to include('is of invalid format')
end
end
<file_sep>/spec/activemodel_spec.rb
require 'spec_helper'
class BankAccount
include ActiveModel::Model
attr_accessor :iban_required, :iban_optional
validates :iban_required, iban: true
validates :iban_optional, iban: true, allow_nil: true
end
describe IbanValidator do
let(:model) { BankAccount.new }
it 'is valid' do
model.iban_required = 'FR1420041010050500013M02606'
expect(model).to be_valid
end
it 'is not valid' do
model.iban_required = 'FR1420041010050500013'
expect(model).to be_invalid
expect(model.errors[:iban_required]).to include('is invalid')
end
it 'does not validate with nil value' do
model.iban_required = 'FR1420041010050500013M02606'
model.iban_optional = nil
expect(model).to be_valid
end
end
<file_sep>/lib/bank_account_tools/matchers/rspec.rb
require_relative 'active_model/have_valid_iban'
require_relative 'active_model/have_valid_bic'
<file_sep>/spec/bic_spec.rb
require 'spec_helper'
describe BankAccountTools::BIC do
let(:bic) { described_class.new('ABNACHZ8XXX')}
it 'returns the right bank code' do
expect(bic.bank_code).to eq('ABNA')
end
it 'returns the right country code' do
expect(bic.country_code).to eq('CH')
end
it 'returns the right location code' do
expect(bic.location_code).to eq('Z8')
end
it 'returns the right branch code' do
expect(bic.branch_code).to eq('XXX')
end
[
'UCJAES2MXXX',
'ABAGATWWXXX',
'UCJAES2MXXX'
].each do |code|
describe code do
it 'has a valid format' do
expect(BankAccountTools::BIC.new(code)).to be_valid
end
end
end
[
'12341234', # only digits
'UCJAES2MXAA', # branch code starts with 'X'
'UCJAES2MAA', # too short
'UCJAES2M0001' # too long
].each do |code|
describe code do
it 'has an invalid format' do
expect(BankAccountTools::BIC.new(code)).not_to be_valid
end
end
end
end
<file_sep>/lib/bank_account_tools.rb
require 'bank_account_tools/version'
require 'bank_account_tools/iban'
require 'bank_account_tools/bic'
require 'bank_account_tools/bban'
require 'bank_account_tools/contact'
require 'pathname'
require 'yaml'
if defined?(::ActiveModel)
require 'bank_account_tools/validators/bic_validator'
require 'bank_account_tools/validators/iban_validator'
end
module BankAccountTools
def self.load_specifications(name)
YAML.load_file Pathname.new(__FILE__).dirname.parent + 'data' + "#{name}.yml"
end
end
<file_sep>/spec/contact_spec.rb
require 'spec_helper'
describe BankAccountTools::Contact do
let(:iban) { BankAccountTools::IBAN.new('FR14 2004 1010 0505 0001 3M026 06') }
let(:bic) { BankAccountTools::BIC.new('BYLADEM1203') }
let(:contact) { BankAccountTools::Contact.new(iban, bic) }
it 'is validate' do
expect(contact).to be_valid
end
it 'has the right types' do
expect(contact.iban).to be_kind_of(BankAccountTools::IBAN)
expect(contact.bic).to be_kind_of(BankAccountTools::BIC)
end
it 'exports to_h' do
expect(contact.to_h).to eq(
iban: 'FR1420041010050500013M02606',
bic: 'BYLADEM1203'
)
end
it 'exports to_a' do
expect(contact.to_a).to eq(['FR1420041010050500013M02606', 'BYLADEM1203'])
end
end
|
6f3d91a7eca79916cd4d001b283803f4786d08c3
|
[
"Markdown",
"Ruby"
] | 10
|
Ruby
|
mytrile/bank_account_tools
|
c6db9064faf4aad1fcf392a8e06aa72ae89f88ba
|
5840ae744f4498e1133baef17bfe70fc2885d25c
|
refs/heads/master
|
<file_sep>export const STUDENT_INFO = {
candidateNumber: 'CANDIDATE_NUMBER',
school: 'SCHOOL',
name: 'NAME',
class: 'CLASS',
studentNumber: 'STUDENT_NUMBER'
}
export const STUDENT_INFO_LABEL = {
[STUDENT_INFO.candidateNumber]: '考号',
[STUDENT_INFO.school]: '学校',
[STUDENT_INFO.name]: '姓名',
[STUDENT_INFO.class]: '班级',
[STUDENT_INFO.studentNumber]: '学号'
}
export default class Student {
constructor (attrs = [STUDENT_INFO.candidateNumber, STUDENT_INFO.name], sheet) {
this.sheet = sheet
this.updateInfos(attrs)
}
updateInfos (attrs = []) {
Object.values(STUDENT_INFO).forEach((attr) => {
this[attr] = attrs.includes(attr)
})
}
toJSON () {
return Object.values(STUDENT_INFO).reduce((acc, key) => {
if (this[key]) acc.push(key)
return acc
}, [])
}
}
<file_sep>import Vue from 'vue'
import Student from './student'
export const SHEET_SIZE = {
A3: 'A3',
A4: 'A4'
}
export const SHEET_SIZE_LABEL = {
[SHEET_SIZE.A4]: 'A4/B5纸',
[SHEET_SIZE.A3]: 'A3/B4/8K纸'
}
export const PAGE_SIZE = 1165
const PAGE_SIZE_MAP = {
[SHEET_SIZE.A3]: Math.SQRT2,
[SHEET_SIZE.A4]: Math.SQRT1_2
}
export const SHEET_COLUMN = {
[SHEET_SIZE.A3]: [2, 3],
[SHEET_SIZE.A4]: [1]
}
// 只有符合 compare 条件的答题卡尺寸才能使用对应的 range
const SHEET_NUMBER_RANGES = [
{
range: [4, 9],
compare ({ size, column }) {
return (size === SHEET_SIZE.A3) && (column === SHEET_COLUMN[SHEET_SIZE.A3][1])
}
},
{
range: [4, 12],
compare ({ size, column }) {
return (size !== SHEET_SIZE.A3) || (column !== SHEET_COLUMN[SHEET_SIZE.A3][1])
}
},
{
// 默认的考号范围,该值一定要放最后,以确保前面的匹配不到的时候才会使用该值
range: [4, 12],
compare () {
return true
}
}
]
export default class AnswerSheet {
static get AllowedSheetSize () {
return Object.values(SHEET_SIZE)
}
static get Precautions () {
return [
'答题前请将姓名、班级、考场、座号和准考证号填写清楚。',
'客观题答题,必须使用2B铅笔填涂,修改时用橡皮擦干净。',
'主观题必须使用黑色签字笔书写。',
'必须在题号对应的答题区域内作答,超出答题区域书写无效。',
'保持答卷清洁完整。'
]
}
constructor (attrs = {}) {
const settings = attrs.settings || {}
this.title = attrs.title || ''
this.settings = {}
this.student = new Student(attrs.student, this)
this.updateSettings({
size: this.constructor.AllowedSheetSize.includes(settings.size)
? settings.size
: SHEET_SIZE.A3,
column: settings.column
})
this.setSheetNumberLength(attrs.sheetNumberLength || 8)
this.questions = []
}
get sheetSize () {
const { size, column } = this.settings
return PAGE_SIZE_MAP[size] * PAGE_SIZE / column
}
// 最近可用的小题编号
get avaliableSubquestionSerialNumber () {
let count = 1
while (!this.isSubquestionSerialNumberVaild(count)) {
count += 1
}
return count
}
// 最近可用的大题编号
get avaliableQuestionSerialNumber () {
let count = 0
while (this.questions[count]) {
count += 1
}
return count
}
// 准考证号的范围
get sheetNumberRange () {
return SHEET_NUMBER_RANGES.find(range => range.compare(this.settings)).range
}
get allowedColumns () {
return SHEET_COLUMN[this.settings.size]
}
// 判断一个数字是否可以作为小题编号
isSubquestionSerialNumberVaild (number) {
return this.questions.filter(Boolean).every(
question => !question.serialNumberSet.has(number)
)
}
updateSettings ({
size,
column
}) {
if (this.constructor.AllowedSheetSize.includes(size)) {
if (this.settings.size !== size) {
this.settings.size = size
this.settings.column = this.allowedColumns.includes(column)
? column
: this.allowedColumns.includes(this.settings.column)
? this.settings.column
: this.allowedColumns[0]
}
if (this.allowedColumns.includes(column)) {
this.settings.column = column
}
}
this.setSheetNumberLength(this.sheetNumberLength)
}
addQuestion (question) {
question.sheet = this
Vue.set(this.questions, question.serialNumber, question)
}
removeQuestion (question) {
Vue.set(this.questions, question.serialNumber, undefined)
}
// 设置准考证号的长度
setSheetNumberLength (length) {
const [min, max] = this.sheetNumberRange
this.sheetNumberLength = Math.min(Math.max(min, length), max)
}
toJSON () {
return {
...(['title', 'settings', 'sheetNumberLength'].reduce((acc, attr) => {
acc[attr] = this[attr]
return acc
}, {})),
student: this.student.toJSON(),
questions: this.questions.filter(Boolean).map(question => question.toJSON())
}
}
}
<file_sep>import Question from './base'
import JudgmentChoiceQuestion from './judgment-choice'
import MultipleChoiceQuestion from './multiple-choice'
import SingleChoiceQuestion from './single-choice'
export default class ObjectiveQuestion extends Question {
static get Title () {
return '客观题'
}
constructor (attrs, sheet) {
super(attrs, sheet)
this.title = attrs.title || ObjectiveQuestion.Title
this.groupSize = attrs.groupSize || 5
this.subquestions = {
singleChoice: new SingleChoiceQuestion(attrs.subquestions.singleChoice, sheet),
multipleChoice: new MultipleChoiceQuestion(attrs.subquestions.multipleChoice, sheet),
judgmentChoice: new JudgmentChoiceQuestion(attrs.subquestions.judgmentChoice, sheet)
}
}
get totalScore () {
return Object.values(this.subquestions).reduce((acc, question) => {
return acc + question.totalScore
}, 0)
}
get serialNumberSet () {
return new Set([
...this.subquestions.singleChoice.serialNumberSet,
...this.subquestions.multipleChoice.serialNumberSet,
...this.subquestions.judgmentChoice.serialNumberSet
])
}
get avaliableSubquestionSerialNumber () {
let number = this.sheet.avaliableSubquestionSerialNumber
while (
!this.sheet.isSubquestionSerialNumberVaild(number) ||
!this.isSerialNumberValid(number)
) {
number += 1
}
return number
}
toJSON () {
return {
uuid: this.uuid,
title: this.title,
type: this.constructor.name,
serialNumber: this.serialNumber,
groupSize: this.groupSize,
subquestions: {
singleChoice: this.subquestions.singleChoice.toJSON(),
multipleChoice: this.subquestions.multipleChoice.toJSON(),
judgmentChoice: this.subquestions.judgmentChoice.toJSON()
}
}
}
}
<file_sep>import Choice from './index'
export default class SwitchChoice extends Choice {
static get MaxOptionLength () {
return 2
}
static get OptionLabelQueue () {
return ['T', 'F']
}
constructor (attrs) {
if (attrs instanceof SwitchChoice) return attrs
super(attrs)
}
}
<file_sep>import Choice from './index'
export default class MultipleChoice extends Choice {
constructor (attrs) {
if (attrs instanceof MultipleChoice) return attrs
super(attrs)
this.halfScore = attrs.halfScore
}
toJSON () {
const supper = super.toJSON()
return {
...supper,
halfScore: this.halfScore
}
}
}
<file_sep>import ChoiceQuestion from './choice_question'
import SwitchChoice from './choice/switch-choice'
export default class JudgmentChoiceQuestion extends ChoiceQuestion {
static get Title () {
return '判断题'
}
buildSubquestion (attrs) {
return new SwitchChoice(attrs)
}
}
<file_sep>import MulitpleChoice from './choice/multiple-choice'
import ChoiceQuestion from './choice_question'
export default class MultipleChoiceQuestion extends ChoiceQuestion {
static get Title () {
return '多选题'
}
buildSubquestion (attrs) {
return new MulitpleChoice(attrs)
}
}
|
b3ab0c81938cb5993a092cc8a6897c7c74586786
|
[
"JavaScript"
] | 7
|
JavaScript
|
AiXinqing/answer-card
|
b8610189eab4f763a1400c8e431361c7d9ccca2e
|
354da3903c379d2e845b537c1ff239fc57e24734
|
refs/heads/master
|
<file_sep>var navigation =
[{
Link: '/Music',
Text: 'Music',
Nav: [{
Link: '/Songs',
Text: 'Songs'
},
{
Link: '/Artists',
Text: 'Artists'
},
{
Link: '/Albums',
Text: 'Albums'
},
{
Link: '/Genres',
Text: 'Genres'
}]
},
{
Link: '/Videos',
Text: 'Videos',
Nav: []
},
{
Link: '/Pictures',
Text: 'Pictures',
Nav: []
}];
module.exports = {
getNavigation: function(){
return navigation;
}
}<file_sep>var express = require('express');
var mainRouter = express.Router();
var audioRouter = express.Router();
var videoRouter = express.Router();
var pictureRouter = express.Router();
module.exports = {
getRouting: function(){
return mainrouter, audioRouter, videoRouter, pictureRouter;
}
// setUpMainRouter: function(){
// app.get('/', function(req, res){
// res.render('index', {
// title: 'hello from render',
// nav: navigation
// });
// });
// },
// setUpAudioRouter: function(){
// return
// }
}
|
d71362e8a1f6d2427693aa8570a34eef93d5f561
|
[
"JavaScript"
] | 2
|
JavaScript
|
MotionComplex/library
|
606765f889da568184d324806b62788ae83b434f
|
c77c40fbf3f9724258bfe59df05c7fb4d319efe3
|
refs/heads/master
|
<file_sep># CDV_Data_Science
This is a repository with various assignments I had to complete for Collegium Da Vinci Data Science curriculum
<file_sep>library(tidyverse)
library(reshape2)
options(repr.plot.width=400, repr.plot.height = 100)
data = list.files(path='data', pattern = '*.csv', full.names="TRUE", recursive="FALSE")
df_list = list()
for (i in 1:length(data)) {
dataframe = read.csv(data[[i]], sep=";")
df_list[[i]] = dataframe
}
df = do.call(rbind, df_list)
df = subset(df, select = -c(Kod, Cena.i.wskaźniki, Jednostka.miary, Atrybut, X))
grouped = group_by(df, Rodzaje.towarów.i.usług, Nazwa)
ordered = grouped[order(grouped$Nazwa, grouped$Rok, grouped$Rodzaje.towarów.i.usług), ]
ordered = transform(ordered, Wartosc = as.numeric(sub(',', '.', as.character(Wartosc))))
ggplot()
for (voivodeship in unique(ordered$Nazwa)) {
subdata <- ordered[ordered$Nazwa == voivodeship, ]
products = c()
meanPrice = c()
year = c();
for (product in unique(subdata$Rodzaje.towarów.i.usług)) {
productSubdata = subdata[subdata$Rodzaje.towarów.i.usług == product, ]
for (yr in unique(productSubdata$Rok)) {
data = productSubdata[productSubdata$Rok == yr, ]
mv = mean(data$Wartosc)
products = c(products, product)
year = c(year, yr)
meanPrice = c(meanPrice, mv)
}
}
data = data.frame(products, year, meanPrice)
ggplot(data=data, aes(x=year)) +
geom_line(aes(y=meanPrice, col=products))+
labs(title="Średnie ceny wybranych produktów w latach 2006-2019",
subtitle=paste("Województwo", voivodeship),
x="Rok",
y="Średnia cena produktu/usługi") +
theme(legend.position = "bottom")
ggsave(paste(voivodeship, "png", sep="."), scale=4)
}
voivodeships = c()
products = c()
meanPrice = c()
deviation = c()
year = c();
for (product in unique(ordered$Rodzaje.towarów.i.usług)) {
subdata <- ordered[ordered$Rodzaje.towarów.i.usług == product, ]
for (voivodeship in unique(subdata$Nazwa)) {
voivSubdata = subdata[subdata$Nazwa == voivodeship, ]
for (yr in unique(voivSubdata$Rok)) {
data = voivSubdata[voivSubdata$Rok == yr, ]
mv = mean(data$Wartosc)
sd = sd(data$Wartosc)
voivodeships = c(voivodeships, voivodeship)
products = c(products, product)
year = c(year, yr)
meanPrice = c(meanPrice, mv)
deviation = c(deviation, sd)
}
}
data = data.frame(voivodeships, products, year, meanPrice, deviation)
ggplot(data, aes(x=products, y=meanPrice, fill=voivodeships)) +
geom_bar(stat="identity", color="black",
position=position_dodge()) +
geom_errorbar(aes(ymin=meanPrice-deviation, ymax=meanPrice+deviation), width=.2,
position=position_dodge(.9)) +
labs(title="Średnie ceny wybranych produktów w latach 2006-2019",
x="Produkt",
y="Średnia cena produktu/usługi") +
theme(axis.text.x = element_text(angle=45, hjust=1))
}
ggsave("Średnie wartości produktów lub usług w poszczególnych województwach.png", scale=4)
<file_sep>Matrix project:
- Refactor
- Implement 'flatten' method
- Use list elements in iterators rather than ranges where possible
- Make sure that the given matrix has a dimension of maximum 3 by 3 (or implement logic for higher dimensions)
- Encapsulate logic in smaller, more precise methods
- Test inplace feature
|
e13e63733d9261da3ad12c302af2a87e1350c599
|
[
"Markdown",
"R"
] | 3
|
Markdown
|
marcinsola/CDV_Data_Science
|
1b276e6339c4a091018fc571082d6efb73dc5a19
|
a75cfcc245c10752db7bfb7af29f97b2505e9403
|
refs/heads/master
|
<repo_name>wangbog/docker_idp_ldap<file_sep>/Dockerfile
FROM centos:7.2.1511
ENV container docker
RUN (cd /lib/systemd/system/sysinit.target.wants/; for i in *; do [ $i == \
systemd-tmpfiles-setup.service ] || rm -f $i; done); \
rm -f /lib/systemd/system/multi-user.target.wants/*;\
rm -f /etc/systemd/system/*.wants/*;\
rm -f /lib/systemd/system/local-fs.target.wants/*; \
rm -f /lib/systemd/system/sockets.target.wants/*udev*; \
rm -f /lib/systemd/system/sockets.target.wants/*initctl*; \
rm -f /lib/systemd/system/basic.target.wants/*;\
rm -f /lib/systemd/system/anaconda.target.wants/*;
VOLUME [ "/sys/fs/cgroup" ]
CMD ["/usr/sbin/init"]
RUN yum -y install httpd; \
rm -f /etc/httpd/conf.d/welcome.conf; \
rm -f /etc/httpd/conf.d/autoindex.conf; \
yum -y install mod_ssl java-1.8.0-openjdk java-1.8.0-openjdk-devel; \
yum -y install tomcat wget; \
echo "" >> /etc/profile; \
echo "export JAVA_HOME=/etc/alternatives/java_sdk_1.8.0" >> /etc/profile; \
echo "export PATH=$PATH:$JAVA_HOME/bin" >> /etc/profile; \
echo "export CLASSPATH=.:$JAVA_HOME/jre/lib:$JAVA_HOME/lib:$JAVA_HOME/lib/tools.jar" >> /etc/profile; \
source /etc/profile; \
yum -y install epel-release; \
yum --enablerepo=epel -y install certbot; \
yum -y install crontabs; \
sed -i '/session required pam_loginuid.so/c\#session required pam_loginuid.so' /etc/pam.d/crond;
COPY idp3config /root/inst/idp3config/
<file_sep>/README.md
# docker_idp_ldap
1. 配置宿主机环境(参考https://wiki.carsi.edu.cn/pages/viewpage.action?pageId=1671214)
配置本机IP
修改主机域名 vi /etc/hostname 及 hostname命令
关闭SELinux
开放本机端口(如firewall-cmd)
设置时间同步(NTP配置,IdP必须要求时间同步)
2. 配置Docker环境(如宿主机已安装配置好docker环境,则忽略)
sudo yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo
sudo yum -y install -y yum-utils device-mapper-persistent-data lvm2
sudo yum -y install docker-ce docker-ce-cli containerd.io
sudo systemctl start docker
可以用hello-world docker镜像验证一下环境(这一步可以不做): sudo docker run hello-world
3. 在宿主机上启动IdP的docker
sudo -y install git
git clone https://github.com/carsi-cernet/docker_idp_ldap.git
cd docker_idp_ldap
docker build --rm -t local/carsi-idp-ldap .
docker run -itd -v /opt/shibboleth-idp/:/opt/shibboleth-idp/ -v /etc/localtime:/etc/localtime:ro -v /etc/hostname:/etc/hostname -v /sys/fs/cgroup:/sys/fs/cgroup:ro -p 80:80 -p 443:443 -p 8443:8443 --privileged=true local/carsi-idp-ldap
查询container_id:
docker ps -a
进入该镜像的bash环境:
docker exec -it <container_id> /bin/bash
如需停止容器:
docker stop <container_id> - 停止docker daemon
4. 在容器bash内执行
首先确认: hostname命令确认一下域名是否已识别;date命令确认一下时间及时区是否正确。
修改/root/inst/idp3config/autoconfig.sh中的admin_mail为运维管理员的邮箱地址(此处是在Let's Encrypt申请网站证书时使用的)。
sh /root/inst/idp3config/autoconfig.sh (注意执行中需要输入idp域名,并多次输入证书密码。另外改配置自动回生成Let's Encript 证书)
根据本校LDAP的实际配置,修改/opt/shibboleth-idp/conf/路径下的 ldap.properties 及 attribute-resolver.xml两个文件, 修改完毕后重启tomcat:systemctl status tomcat, 重启后访问一下https://<idp域名>/idp/ 应该可以看到“No services are available at this location.”的提示。
将/opt/shibboleth-idp/metadata/idp-metadata.xml通过CARSI自服务系统上传到联盟(docker容器启动时已与宿主机同步了/opt/shibboleth-idp/路径,因此直接在宿主机中即可找到该文件)
sh /root/inst/idp3config/startidp.sh
之后即可在预上线环境中进行测试了(具体参考:https://wiki.carsi.edu.cn/pages/viewpage.action?pageId=2261000)。
<file_sep>/idp3config/autoconfig.sh
source /etc/profile
# config httpd
\cp -f /root/inst/idp3config/httpd.conf /etc/httpd/conf/httpd.conf
\cp -f /root/inst/idp3config/index.html /var/www/html/index.html
\cp -f /root/inst/idp3config/ports.conf /etc/httpd/conf.d/ports.conf
\cp -f /root/inst/idp3config/idp80.conf /etc/httpd/conf.d/idp80.conf
systemctl restart httpd
# config tomcat
\cp -f /root/inst/idp3config/idp.xml /etc/tomcat/Catalina/localhost/idp.xml
\cp -f /root/inst/idp3config/server.xml /etc/tomcat/server.xml
\cp -f /root/inst/idp3config/javax.servlet.jsp.jstl-api-1.2.1.jar /usr/share/tomcat/lib/javax.servlet.jsp.jstl-api-1.2.1.jar
\cp -f /root/inst/idp3config/javax.servlet.jsp.jstl-1.2.1.jar /usr/share/tomcat/lib/javax.servlet.jsp.jstl-1.2.1.jar
systemctl restart tomcat
# config https
hostname=`hostname`
admin_mail="<EMAIL>"
certbot certonly --agree-tos --no-eff-email -m $admin_mail -d $hostname --webroot -w /var/www/html
systemctl restart crond
echo "0 0 1 * * certbot renew >/dev/null 2>&1" >> /var/spool/cron/root
\cp -f /root/inst/idp3config/ssl.conf /etc/httpd/conf.d/ssl.conf
\cp -f /root/inst/idp3config/idp.conf /etc/httpd/conf.d/idp.conf
sed -i "s/MY_IDP_HOSTNAME/$hostname/g" /etc/httpd/conf.d/idp.conf
sed -i "s/#Listen 443/Listen 443/g" /etc/httpd/conf.d/ports.conf
systemctl restart httpd
# config idp
rm -rf /root/inst/idp3config/shibboleth-identity-provider-3.4.3/
cd /root/inst/idp3config/
tar xzf shibboleth-identity-provider-3.4.3.tar.gz
sh /root/inst/idp3config/shibboleth-identity-provider-3.4.3/bin/install.sh
openssl pkcs12 -in /opt/shibboleth-idp/credentials/idp-backchannel.p12 -out /opt/shibboleth-idp/credentials/idp-backchannel.key -nocerts -nodes
\cp -f /root/inst/idp3config/metadata-providers-pre.xml /opt/shibboleth-idp/conf/metadata-providers.xml
\cp -f /root/inst/idp3config/attribute-resolver.xml /opt/shibboleth-idp/conf/attribute-resolver.xml
salt=`openssl rand 32 -base64`
sed -i "s/xxxxxxxxxxxxxxxxxxxx/$salt/g" /opt/shibboleth-idp/conf/attribute-resolver.xml
\cp -f /root/inst/idp3config/audit.xml /opt/shibboleth-idp/conf/audit.xml
\cp -f /root/inst/idp3config/consent-intercept-config.xml /opt/shibboleth-idp/conf/intercept/consent-intercept-config.xml
\cp -f /root/inst/idp3config/relying-party.xml /opt/shibboleth-idp/conf/relying-party.xml
\cp -f /root/inst/idp3config/attribute-filter.xml /opt/shibboleth-idp/conf/attribute-filter.xml
\cp -f /root/inst/idp3config/dsmeta.pem /opt/shibboleth-idp/credentials/
sed -i "s/#idp.consent.allowPerAttribute = false/idp.consent.allowPerAttribute = true/g" /opt/shibboleth-idp/conf/idp.properties
wget -P /opt/shibboleth-idp/metadata/ https://dspre.carsi.edu.cn/carsifed-metadata-pre.xml
chown -R tomcat.tomcat /opt/shibboleth-idp
systemctl restart httpd
systemctl restart tomcat
|
09d83f6ba2b252b25aa0aaae3caa527e720eb8c8
|
[
"Markdown",
"Dockerfile",
"Shell"
] | 3
|
Dockerfile
|
wangbog/docker_idp_ldap
|
d76baa5a84964da783d73de8c6b72b5f67492aae
|
09f12b95ce404df9cd4076e6065e3cc369be6b76
|
refs/heads/master
|
<repo_name>GoZSY/-Adjust-the-numbers-of-array<file_sep>/README.md
# -Adjust-the-numbers-of-array
输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有的奇数位于数组的前半部分,所有的偶数位于位于数组的后半部分,并保证奇数和奇数,偶数和偶数之间的相对位置不变。
<file_sep>/code.cpp
/*************************************************************
方法一、循环改变相邻位置前边为偶数后边为奇数的情况O(n)
*************************************************************/
class Solution {
public:
void reOrderArray(vector<int> &array)
{
if(array.size()<1)
return;
for(int i = 0; i < array.size() - 1; ++i)
for(int j = 0; j < array.size() -i- 1; ++j)
{
if(array[j]%2 == 0 && array[j+1]%2 == 1)
{
int temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
}
};
/*************************************************************
方法二、与法一类似,但是这次是找到奇数在偶数后边的情况,然后
奇数偶数之间的数字整体后移,为奇数的插入腾出空间
*************************************************************/
class Solution {
public:
void reOrderArray(vector<int> &array)
{
int length = array.size();
int i = 0;
int j = 0;
while(i < length && j < length)
{
while(array[i]%2 == 1)
i++;
while(array[j]%2 == 0)
j++;
if(j>i && i < length && j < length)
{
int temp = array[j];
for(int k = j;k > i;--k)
{
array[k] = array[k-1];
}
array[i] = temp;
}
else
{
j++;
}
}
}
};
|
3a6eb8f76386547913bd2d29fb1765b5a05585c5
|
[
"Markdown",
"C++"
] | 2
|
Markdown
|
GoZSY/-Adjust-the-numbers-of-array
|
dc8ec71f6bac36c400d4c0111ea2ce1395093887
|
1db38120000ab5f72e599f9e4378858f1bb331a6
|
refs/heads/main
|
<file_sep>from bs4 import BeautifulSoup
import requests
import re
from contextlib import closing
import pymysql
from pymysql.cursors import DictCursor
from environs import Env
env = Env()
env.read_env("mysql.env")
user = env.str("user")
password = env.str("password")
def get_html(url):
headers = {'accept-language': 'ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7,be;q=0.6'}
r = requests.get(url, headers=headers)
return r.text
def get_all_links(html):
soup = BeautifulSoup(html, 'html.parser')
imdb = soup.find('tbody', class_='lister-list')
imdb250 = imdb.find_all('tr')
results = []
regexp = r'\d{4}'
for item in imdb250:
names = item.find('a').next_element.next_element
title = names.get('alt')
release_year = item.find(text=re.compile(regexp)).strip()
rank_films = item.find('strong').next
results.append({
'title': title,
'release_year': release_year,
'rank_films': rank_films
})
return results
def create_db():
with closing(pymysql.connect(
host='localhost',
user=user,
password=<PASSWORD>,
charset='utf8mb4',
cursorclass=DictCursor
)) as connection:
with connection.cursor() as cursor:
query = """
CREATE DATABASE IF NOT EXISTS films_imdb
"""
cursor.execute(query)
def create_table():
with closing(pymysql.connect(
host='localhost',
user=user,
password=<PASSWORD>,
charset='utf8mb4',
db='films_imdb',
cursorclass=DictCursor
)) as connection:
with connection.cursor() as cursor:
query = """
CREATE TABLE IF NOT EXISTS films_imdb250
(id int(11) NOT NULL AUTO_INCREMENT,
title varchar(100) DEFAULT NULL COMMENT "text",
release_year varchar(100) DEFAULT NULL COMMENT "text",
rank_films varchar(100) DEFAULT NULL COMMENT "text",
PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8
"""
cursor.execute(query)
def insert_into_table(results):
with closing(pymysql.connect(
host='localhost',
user=user,
password=<PASSWORD>,
charset='utf8mb4',
db='films_imdb',
cursorclass=DictCursor
)) as conn:
with conn.cursor() as cursor:
for i in results:
fs = ','.join(list(map(lambda x: '`' + x + '`', [*i.keys()])))
vs = ','.join(list(map(lambda x: '%(' + x + ')s', [*i.keys()])))
query = 'INSERT INTO films_imdb250 %(fs)s VALUES %(vs)s', {'fs': fs, 'vs': vs}
cursor.executemany(query, results)
conn.commit()
def main():
url = f'https://www.imdb.com/chart/top/?ref_=nv_mv_250'
html = get_html(url)
results = get_all_links(html)
create_db()
create_table()
insert_into_table(results)
if __name__ == '__main__':
main()
<file_sep>from bs4 import BeautifulSoup
import requests
import json
import re
headers = {'accept-language': 'ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7,be;q=0.6'}
regexp = r'\d{4}'
def get_html(url):
r = requests.get(url, headers=headers)
return r.text
def get_all_links(html):
soup = BeautifulSoup(html, 'html.parser')
imdb = soup.find('tbody', class_='lister-list')
imdb250 = imdb.find_all('tr')
results = []
for item in imdb250:
place = item.find('td', class_='titleColumn').next.strip()
names = item.find('a').next_element.next_element
name = names.get('alt')
year = item.find(text=re.compile(regexp))
rank = item.find('strong').next
# print(rank)
results.append({
'place': place,
'name': name,
'year': year,
'rank': rank
})
return results
def write_json(results):
with open('imdb250function.json', 'w') as file:
json.dump(results, file, indent=2)
def main():
url = f'https://www.imdb.com/chart/top/?ref_=nv_mv_250'
html = get_html(url)
results = get_all_links(html)
write_json(results)
if __name__ == '__main__':
main()
|
ea9992c7ad0d5c9ae87457d2890c0163197f29e7
|
[
"Python"
] | 2
|
Python
|
thunder03026/mini-projects
|
5f41af37479cfd22183097ca674bc7576c3d5a9a
|
a916a990afc5cf28ec115fe8864dbf744a355e7c
|
refs/heads/master
|
<repo_name>mixu/npm_push<file_sep>/lib/cache.js
var fs = require('fs'),
path = require('path'),
mkdirp = require('mkdirp'),
Client = require('mixu_minimal').Client,
Lifecycle = require('./lifecycle.js');
// configuration
var basePath, // path to cache directory
cacheAge = 60 * 60 * 1000; // max age in cache
// index of last updated (so we always do one refresh on restart, then after cacheAge or if restarted)
var lastUpdated = {},
guard = new Lifecycle();
function Cache() { }
Cache.configure = function(config) {
basePath = config.cacheDirectory;
cacheAge = (!isNaN(config.cacheAge) ? config.cacheAge : cacheAge);
return Cache;
};
Cache.has = function(pname, file) {
// index.json has special handling
if(file == 'index.json') {
var maxAge = new Date() - cacheAge,
isUpToDate = (lastUpdated[pname] && lastUpdated[pname] > maxAge);
if(!isUpToDate) {
console.log('Forcing index refresh, last update: '
+ (lastUpdated[pname] ? lastUpdated[pname].toLocaleString() : 'never')
+' max age: '+new Date(maxAge).toLocaleString());
return false;
}
}
return path.existsSync(basePath + pname + '/' + file);
};
Cache.get = function(pname, file, callback) {
var filename = basePath + pname + '/' + file;
if(Cache.has(pname, file)) {
fs.readFile(filename, function(err, data) {
if (err) throw err;
// console.log('[done] Read index file from cache: '+ filename);
callback && callback(undefined, data);
});
} else {
if(file == 'index.json') {
// fetch index
Cache._fetch('http://registry.npmjs.org/'+pname, pname, file, callback);
} else {
Cache._fetch('http://registry.npmjs.org/'+pname+'/-/'+file, pname, file, callback);
}
}
};
Cache.add = function(pname, file, content, callback) {
var dirname = basePath + pname +'/';
mkdirp(dirname, function (err) {
if (err) throw err;
if(path.existsSync(dirname + file)) {
fs.unlinkSync(dirname + file);
}
fs.writeFile(dirname + file, content, function(err) {
if (err) throw err;
lastUpdated[pname] = new Date();
console.log('Cache file '+ dirname + file);
callback && callback();
});
});
};
Cache._fetch = function(resource, pname, file, callback) {
console.log('Cache miss: ', pname, file, ', GET '+resource);
guard.onRelease(resource, function() {
console.log('GET');
// now fetch
Cache.get(pname, file, callback);
})
if(guard.isBlocking(resource)) {
return;
}
guard.block(resource);
var dirname = basePath + pname +'/';
mkdirp(dirname, function (err) {
if (err) throw err;
var outputStream = fs.createWriteStream(dirname + file);
Client
.get(resource)
.end(function(err, res) {
res.on('end', function() {
if(file == 'index.json') {
lastUpdated[pname] = new Date();
}
console.log('[done] added to cache', pname, file);
guard.release(resource);
});
res.pipe(outputStream);
});
});
};
module.exports = Cache;
<file_sep>/config.js
var path = require('path');
module.exports = {
// directory to store cached packages (full path)
cacheDirectory: path.normalize(__dirname+'/db/'),
// maximum age before an index is refreshed from npm
cacheAge: 60 * 60 * 1000,
// external url to npm-lazy, no trailing /
externalUrl: 'http://localhost:8080',
// bind port and host
port: 8080,
host: 'localhost',
// external registries in resolve order
searchPath: [
{
// subdirectory in cacheDirectory for caching/storage
dir: 'local'
// no url = this is the local repository
},
{
// subdirectory in cacheDirectory for caching
dir: 'remote',
// url to registry
url: 'http://registry.npmjs.org/'
}
]
};
<file_sep>/lib/package.js
var fs = require('fs'),
url = require('url'),
path = require('path'),
semver = require('semver');
// configuration
var Cache, // Cache instance
externalUrl; // external URL of the registry
function Package() { }
Package.configure = function(config) {
Cache = config.cache;
externalUrl = config.externalUrl;
};
Package.exists = function(name) {
return Cache.has(name, 'index.json');
};
Package.get = function(name, version, callback) {
// version is optional
if(arguments.length == 2) {
callback = version;
return Package._getIndex(name, callback);
} else {
return Package._getVersion(name, version, callback);
}
};
Package._getIndex = function(name, callback) {
Cache.get(name, 'index.json', function(err, doc) {
return callback(err,
Package._rewriteLocation(
JSON.parse(doc.toString())
));
});
};
Package._getVersion = function(name, version, callback) {
var filename = name +'/index.json';
// according to the NPM source, the version specific JSON is
// directly from the index document (e.g. just take doc.versions[ver])
Cache.get(name, 'index.json', function(err, doc) {
if(err) throw err;
doc = JSON.parse(doc.toString());
// from NPM: if not a valid version, then treat as a tag.
if (!(version in doc.versions) && (version in doc['dist-tags'])) {
version = doc['dist-tags'][version]
}
if(doc.versions[version]) {
return callback(undefined, Package._rewriteLocation(doc.versions[version]));
}
throw new Error('[done] Could not find version', filename, version);
return callback(undefined, {});
});
};
Package._rewriteLocation = function(meta) {
if(!meta) {
return meta;
}
if(meta.versions) {
// if a full index, apply to all versions
Object.keys(meta.versions).forEach(function(version) {
meta.versions[version] = Package._rewriteLocation(meta.versions[version]);
});
}
if (meta.dist && meta.dist.tarball) {
var parts = url.parse(meta.dist.tarball);
meta.dist.tarball = externalUrl+parts.pathname;
}
return meta;
};
Package.checkFile = function(filename, cb) {
// from npm:
var crypto = require('crypto');
var h = crypto.createHash("sha1"),
s = fs.createReadStream(filename),
errState = null;
s.on("error", function (er) {
if (errState) return;
return cb(errState = er)
}).on("data", function (chunk) {
if (errState) return;
h.update(chunk);
}).on("end", function () {
if (errState) return
var actual = h.digest("hex").toLowerCase().trim();
cb(null, actual);
});
};
module.exports = Package;
<file_sep>/lib/api.js
var url = require('url'),
Router = require('mixu_minimal').Router,
Package = require('./package.js'),
Push = require('./push.js');
var api = new Router();
// full API, based on rewrites.js
// GET / => ../../../registry
// This should return the database info, like plain couchDB
// GET /-/jsonp/:jsonp => _list/short/listAll
// Call lists.js short(listAll)
// GET PUT POST DELETE HEAD _session
// User management
//
// POST /_session
// Log in; application/x-www-form-urlencoded encoding
// params: name and passowrd
// response { ok: true, name: foo, roles: [] }
//
// It looks like the expected cookie is called AuthSession=
//
// GET /_session
// Log in with a standard basic authorization header
//
// DELETE /_session
// Log out; unsets the session cookie
// GET /-/all/since => _list/index/modified
// Search - calls list.index(modified) -> returns index
api.get(new RegExp('^/-/all(.*)$'), list.index);
// GET /-/rss => _list/rss/modified
// RSS version of the modified index
// GET /-/all => _list/index/listAll
// GET /-/all/-/jsonp/:jsonp => _list/index/listAll
// list all, alternative version supports JSONP
// GET /-/short => _list/short/listAll
// array of the names of all packages
// GET /-/scripts => _list/scripts/scripts
// GET /-/by-field => _list/byField/byField
// GET /-/fields => _list/sortCount/fieldsInUse
// GET /-/needbuild => _list/needBuild/needBuild
// GET /-/prebuilt => _list/preBuilt/needBuild
// GET /-/nonlocal => _list/short/nonlocal
// GET /-/users => ../../../_users/_design/_auth/_list/index/listAll
// List of all users { "username": { name: "fullname", email: "email", "_conflicts": "junk" }
// PUT /-/user/:user => ../../../_users/:user
// Inserts user into the _users document, a builtin for CouchDB
function () {
'PUT'
, '/-/user/org.couchdb.user:'+encodeURIComponent(username)
{ name : username
, salt : salt
, password_sha : sha(password + salt)
, email : email
, _id : 'org.couchdb.user:'+username
, type : "user"
, roles : []
, date: new Date().toISOString()
}
// Return 409 if the user exists
}
// PUT /-/user/:user/-rev/:rev => ../../../_users/:user
// when updating, couchdb needs the latest rev
function () {
'PUT'
, '/-/user/org.couchdb.user:'+encodeURIComponent(username)
+ "/-rev/" + userobj._rev
, userobj
}
// GET /-/user/:user => ../../../_users/:user
function () {
'/-/user/org.couchdb.user:'+encodeURIComponent(username)
}
// GET /-/user-by-email/:email => ../../../_users/_design/_auth/_list/email/listAll
// fetch user by email ["username"]
// GET /-/top => _view/npmTop
// not working?
// GET /-/by-user/:user => _list/byUser/byUser
// GET /-/starred-by-user/:user => _list/byUser/starredByUser
// GET /-/starred-by-package/:user => _list/byUser/starredByPackage
// GET /:pkg => /_show/package/:pkg
api.get(new RegExp('^/([^/]+)$'), show.package);
// GET /:pkg/-/jsonp => /_show/package/:pkg
// GET /:pkg/:version/:jsonp => _show/package/:pkg (GET /package/version)
api.get(new RegExp('^/(.+)/(.+)$'), function(req, res, match) {
Package.get(match[1], match[2], function(err, data) {
if(err) throw err;
res.end(JSON.stringify(data));
});
});
// GET /:pkg/:version/-/jsonp/:jsonp => _show/package/:pkg
// GET "/:pkg/-/:att", to: "../../:pkg/:att (GET /package/-/package-version.tgz)
api.get(new RegExp('^/(.+)/-/(.+)$'), function(req, res, match) {
Package.getTar(match[1], match[2], res);
});
// PUT "/:pkg/-/:att/:rev", to: "../../:pkg/:att
// PUT "/:pkg/-/:att/-rev/:rev", to: "../../:pkg/:att", method: "PUT" }
// DELETE "/:pkg/-/:att/:rev", to: "../../:pkg/:att
// DELETE "/:pkg/-/:att/-rev/:rev", to: "../../:pkg/:att
// PUT "/:pkg", to: "/_update/package/:pkg (PUT /packagename { wrangled package.json })
// create the package
api.put(new RegExp('^/([^/]+)$'), api.parse(create.package));
// Return 409 if the package exists
// PUT "/:pkg/-rev/:rev", to: "/_update/package/:pkg
// update the package (-rev should match latest?)
// PUT "/:pkg/:version", to: "_update/package/:pkg
// PUT "/:pkg/:version/-rev/:rev", to: "_update/package/:pkg (PUT /requireincontext/-/requireincontext-0.0.2.tgz/-rev/5-988ff7c27a21e527ceeb50cbedc8d1b0)
// send a binary package
api.put(new RegExp('^/([^/]+)/-/([^/]+)/-rev/([^/]+)$'), create.binary);
// PUT "/:pkg/:version/-tag/:tag", to: "_update/package/:pkg (PUT /requireincontext/0.0.2/-tag/latest)
// add a new version to the package
api.put(new RegExp('^/([^/]+)/([^/]+)/-tag/([^/]+)$'), api.parse(package.addversion));
// PUT "/:pkg/:version/-tag/:tag/-rev/:rev", to: "_update/package/:pkg
// PUT "/:pkg/:version/-pre/:pre", to: "_update/package/:pkg
// PUT "/:pkg/:version/-pre/:pre/-rev/:rev", to: "_update/package/:pkg
// DELETE "/:pkg/-rev/:rev", to: "../../:pkg"
// Unpublish a package (all versions)
function ender(res, success) {
return function(err) {
if(err) {
res.statusCode = 403;
return res.end(JSON.stringify({ forbidden: err }));
}
console.log(success);
res.end(JSON.stringify({ ok: success }));
};
}
// Create workflow:
// PUT /packagename { wrangled package.json } --> This is intended to create a new package
// GET /packagename
// check that the version we are pushing is newer than before
// PUT /requireincontext/0.0.2/-tag/latest --> This contains a full new version
// {"name":"requireincontext","description":"Wrapper to require() js files in a custom context","version":"0.0.2","author":{"name":"<NAME>","email":"<EMAIL>"},"keywords":["require"],"repository":{"type":"git","url":"git://github.com/mixu/require2incontext.git"},"main":"index.js","_npmUser":{"name":"mixu","email":"<EMAIL>"},"_id":"requireincontext@0.0.2","dependencies":{},"devDependencies":{},"optionalDependencies":{},"engines":{"node":"*"},"_engineSupported":true,"_npmVersion":"1.1.18","_nodeVersion":"v0.6.7","_defaultsLoaded":true,"dist":{"shasum":"742d3bce1cb0bea1ce8fca90b867281c42627f82","tarball":"http://localhost:8080/requireincontext/-/requireincontext-0.0.2.tgz"},"readme":""}
// GET /requireincontext
// check something?
// PUT /requireincontext/-/requireincontext-0.0.2.tgz/-rev/5-988ff7c27a21e527ceeb50cbedc8d1b0
module.exports = api;
<file_sep>/test/integration.test.js
var fs = require('fs'),
http = require('http'),
path = require('path'),
assert = require('assert'),
npm = require('npm'),
api = require('../lib/app.js').Api;
var config = {
// directory to store cached packages (full path)
cacheDirectory: path.normalize(__dirname+'/../db/'),
// maximum age before an index is refreshed from npm
cacheAge: 60 * 60 * 1000,
// external url to npm-lazy, no trailing /
externalUrl: 'http://localhost:9090',
// bind port and host
port: 9090,
host: 'localhost',
// external registries in resolve order
searchPath: [
{
// subdirectory in cacheDirectory for caching/storage
dir: 'local'
// no url = this is the local repository
},
{
// subdirectory in cacheDirectory for caching
dir: 'remote',
// url to registry
url: 'http://registry.npmjs.org/'
}
]
};
config.externalUrl = 'http://localhost:9090';
require('../lib/app.js').configure(config);
exports['given a server'] = {
before: function(done) {
this.server = http.createServer(function(req, res) {
api.route(req, res);
});
this.server.listen(9090, 'localhost', function() {
done();
});
},
// npm install foo
'can install a package from the cache': function(done) {
this.timeout(100000);
npm.load({ registry: 'http://localhost:9090/'}, function (err) {
if (err) { throw new Error(err); }
npm.commands.install(["requireincontext"], function (err, data) {
if (err) { throw new Error(err); }
done();
})
});
},
// npm push foo
'can push a package to the cache': function(done) {
this.timeout(10000);
npm.load({ registry: 'http://localhost:9090/'}, function (err) {
if (err) { throw new Error(err); }
npm.commands.publish(['./fixture/'], function (err, data) {
if (err) { throw new Error(err); }
done();
})
});
}
};
// if this module is the script being run, then run the tests:
if (module == require.main) {
var mocha = require('child_process').spawn('mocha', [ '--colors', '--ui', 'exports', '--reporter', 'spec', __filename ]);
mocha.stdout.pipe(process.stdout);
mocha.stderr.pipe(process.stderr);
}
<file_sep>/lib/lifecycle.js
var util = require('util'),
EventEmitter = require('events').EventEmitter;
function Lifecycle() {
this.blocked = {};
}
util.inherits(Lifecycle, EventEmitter);
Lifecycle.prototype.block = function(resource) {
console.log('Blocking', resource);
this.blocked[resource] = true;
};
Lifecycle.prototype.release = function(resource) {
console.log('Releasing', resource);
if(this.isBlocking(resource)) {
delete this.blocked[resource];
console.log('Released: '+resource+' - run callbacks');
this.emit('resource');
}
};
Lifecycle.prototype.isBlocking = function(resource) {
return this.blocked.hasOwnProperty(resource);
};
Lifecycle.prototype.onRelease = function(resource, callback) {
console.log('Blocked: '+resource+' - setting callback for release');
this.once('resource', callback);
};
module.exports = Lifecycle;
<file_sep>/Makefile
TESTS += test/cache.test.js
# TESTS += test/integration.test.js
TESTS += test/lifecycle.test.js
TESTS += test/package.test.js
test:
@./node_modules/.bin/mocha \
--ui exports \
--reporter spec \
--slow 2000ms \
--bail \
$(TESTS)
.PHONY: test
<file_sep>/test/push.test.js
var fs = require('fs'),
util = require('util'),
http = require('http'),
path = require('path'),
assert = require('assert'),
npm = require('npm'),
rimraf = require('rimraf'),
Router = require('mixu_minimal').Router,
Client = require('mixu_minimal').Client,
api = require('../lib/api.js'),
Package = require('../lib/package.js'),
Push = require('../lib/push.js');
exports['given a push endpoint'] = {
before: function(done) {
var Cache = require('../lib/cache.js');
Cache.configure({ cacheDirectory: __dirname+'/db/'});
Package.configure({
cache: Cache,
externalUrl: 'http://localhost:9090'
});
Push.configure({
cache: Cache,
cacheDirectory: __dirname+'/db/'
});
this.server = http.createServer(function(req, res) {
api.route(req, res);
});
this.server.listen(9090, 'localhost', function() {
rimraf(__dirname+'/db/testfoo', function() {
done();
})
});
},
// npm push foo, where the package does not exist
'can push a new package to the cache': function(done) {
this.timeout(10000);
npm.load({ registry: 'http://localhost:9090/'}, function (err) {
if (err) { throw new Error(err); }
npm.commands.publish(['./fixture/0.0.1'], function (err, data) {
if (err) { throw new Error(err); }
done();
})
});
},
// npm view testfoo
'can npm view': function(done) {
npm.load({ registry: 'http://localhost:9090/'}, function (err) {
if (err) { throw new Error(err); }
npm.commands.view(['testfoo'], function (err, data) {
if (err) { throw new Error(err); }
assert.ok(data['0.0.1']);
data = data['0.0.1'];
console.log(util.inspect(data, false, 5, true));
assert.equal(data.name, 'testfoo');
assert.equal(data.version, '0.0.1');
assert.equal(data['dist-tags'].latest, '0.0.1');
done();
})
});
},
// npm install testfoo
// npm push foo, where the package exists and is a new version
'can push a updated version of a package to the cache': function(done) {
this.timeout(10000);
npm.load({ registry: 'http://localhost:9090/'}, function (err) {
if (err) { throw new Error(err); }
npm.commands.publish(['./fixture/0.0.2'], function (err, data) {
if (err) { throw new Error(err); }
Client
.get('http://localhost:9090/testfoo')
.end(Client.parse(function(err, data) {
data = JSON.parse(data);
assert.equal(data.name, 'testfoo');
assert.equal(data['dist-tags'].latest, '0.0.2');
done();
}));
})
});
},
// npm search testfoo
'can npm search': function(done) {
this.timeout(10000);
npm.load({ registry: 'http://localhost:9090/'}, function (err) {
if (err) { throw new Error(err); }
npm.commands.search(['testfoo'], function (err, data) {
if (err) { throw new Error(err); }
console.log(data);
done();
})
});
},
};
// if this module is the script being run, then run the tests:
if (module == require.main) {
var mocha = require('child_process').spawn('mocha', [ '--colors', '--ui', 'exports', '--reporter', 'spec', __filename ]);
mocha.stdout.pipe(process.stdout);
mocha.stderr.pipe(process.stderr);
}
<file_sep>/lib/push.js
var fs = require('fs'),
semver = require('semver'),
Package = require('./package.js');
// configuration
var Cache, // Cache instance
basePath; // path to cache directory
exports.configure = function(config) {
Cache = config.cache;
basePath = config.cacheDirectory;
};
// create a new package
exports.create = function(name, json, callback) {
var doc = json;
// ported from NPM
if(!doc._id) doc._id = doc.name;
if(doc.url) {
console.log('The URLs as dependencies feature is not supported by npm-push.');
res.end();
}
if (!doc.versions) doc.versions = {};
if (!doc['dist-tags']) doc['dist-tags'] = {};
// add a junk _rev for npm
doc['_rev'] = 'junk-'+new Date().getTime();
// write to file
return Cache.add(name, 'index.json', JSON.stringify(doc), callback);
};
// add a new version to a package
exports.addVersion = function(name, version, json, callback) {
// must be valid
if(!semver.valid(version)) {
// this is where the tag update code would go
return callback('invalid version: '+ version);
}
Cache.get(name, 'index.json', function(err, doc) {
doc = JSON.parse(doc.toString());
var isValidVersion = semver.valid(version),
isExistingVersion = !!((version in doc.versions) || (semver.clean(version) in doc.versions)),
isValidName = exports.validName(json.name),
isSameName = !!(json.version == semver.clean(version));
if(!isValidVersion) {
return callback('invalid version: '+JSON.stringify(version));
}
if(isExistingVersion) {
return callback('cannot modify existing version');
}
if(!isValidName) {
return callback('Invalid name: '+JSON.stringify(json.name));
}
if(!isSameName) {
return callback('version in doc doesn\'t match version in request: '
+ JSON.stringify(json.version)
+ " !== " + JSON.stringify(version));
}
// fill in defaults
json._id = json.name + "@" + json.version;
if (json.description) doc.description = json.description;
if (json.author) doc.author = json.author;
if (json.repository) doc.repository = json.repository;
json.maintainers = doc.maintainers;
// set the tag and time
var tag = (json.publishConfig && json.publishConfig.tag) || json.tag || "latest";
doc["dist-tags"][tag] = json.version;
doc.versions[version] = json;
doc.time = doc.time || {};
doc.time[version] = (new Date()).toISOString();
doc['_rev'] = 'junk-'+new Date().getTime();
// save the document
return Cache.add(name, 'index.json', JSON.stringify(doc), callback);
});
};
// update the metadata on the latest package version
exports.updateLatest = function(name, version, json, callback) {
// update the latest package document revision
var changed = false;
Cache.getIndex(name, function(err, doc) {
if (doc._rev && doc._rev !== json._rev) {
return callback('must supply latest _rev to update existing package');
}
if (json.url && (json.versions || json["dist-tags"])) {
return callback('Do not supply versions or dist-tags for packages hosted elsewhere. Just a URL is sufficient.');
}
for (var i in json) {
if (typeof json[i] === "string" || i === "maintainers") {
doc[i] = json[i];
}
}
if (json.versions) {
doc.versions = json.versions;
}
if (json["dist-tags"]) {
doc["dist-tags"] = json["dist-tags"];
}
if (json.users) {
if (!doc.users) {
doc.users = {};
}
// doc.users[req.userCtx.name] = json.users[req.userCtx.name]
}
// add a junk _rev for npm
doc['_rev'] = 'junk-'+new Date().getTime();
return Cache.addIndex(name, doc, callback);
});
};
// store a tar file
exports.storeFile = function(name, req, res, filename, revision, callback) {
var localName = basePath + name + '/'+ filename;
req.on('end', callback);
req.pipe(fs.createWriteStream(localName));
};
exports.getTar = function(name, filename, res) {
Cache.respondTar(name, filename, res);
};
// from NPM
exports.validName = function validName (name) {
if (!name) return false
var n = name.replace(/^\s|\s$/, "")
if (!n || n.charAt(0) === "."
|| n.match(/[\/\(\)&\?#\|<>@:%\s\\]/)
|| n.toLowerCase() === "node_modules"
|| n.toLowerCase() === "favicon.ico") {
return false
}
return n
};
<file_sep>/test/cache.test.js
var fs = require('fs'),
path = require('path'),
http = require('http'),
assert = require('assert'),
Cache = require('../lib/cache.js');
exports['given a cache'] = {
before: function(done) {
if(path.existsSync(__dirname+'/db/foobar/index.json')) {
fs.unlinkSync(__dirname+'/db/foobar/index.json');
}
Cache.configure({ cacheDirectory: __dirname+'/db/' });
done();
},
'can check for a nonexistent package': function(done) {
assert.equal(Cache.has('foobar', 'index.json'), false);
done();
},
'can add a package': function(done) {
Cache.add('foobar', 'index.json', JSON.stringify({ msg: "hello world"}), function(err) {
done();
});
},
'can check for an existing package': function(done) {
assert.equal(Cache.has('foobar', 'index.json'), true);
done();
},
'can get an existing package': function(done) {
Cache.get('foobar', 'index.json', function(err, data) {
assert.deepEqual({ msg: 'hello world'}, JSON.parse(data.toString()));
done();
});
},
'can get a remote package': function(done) {
this.timeout(20000); // npm is slow today
if(path.existsSync(__dirname+'/db/requireincontext/index.json')) {
fs.unlinkSync(__dirname+'/db/requireincontext/index.json');
}
Cache.get('requireincontext', 'index.json', function(err, data) {
data = JSON.parse(data);
// not really sure how I would mock this
assert.equal('requireincontext', data.name);
done();
});
}
};
// if this module is the script being run, then run the tests:
if (module == require.main) {
var mocha = require('child_process').spawn('mocha', [ '--colors', '--ui', 'exports', '--reporter', 'spec', __filename ]);
mocha.stdout.pipe(process.stdout);
mocha.stderr.pipe(process.stderr);
}
<file_sep>/readme.md
# npm-push: a private npm server
I wanted a private server that is easy to deploy - e.g. one that uses regular files for storage (no CouchDB).
I wanted something that can cache npm packages locally, and that can accept pushes from npm locally.
## Configuration
npm config set registry http://localhost:8080
or
npm --registry http://localhost:8080/ install foo
or in package.json:
"publishConfig":{
"registry": "http://localhost:8080/"
}
## Supported commands
Commands that work - remote:
npm install
npm publish
npm view / npm info
Install and view are cached.
Publish does not go out to the main server.
Todo - remote:
npm adduser
npm deprecate <pkg>[@<version>] <message>
npm outdated [<pkg> [<pkg> ...]]
npm owner add <username> <pkg>
npm owner rm <username> <pkg>
npm owner ls <pkg>
npm search
npm star <package> [pkg, pkg, ...]
npm unstar <package> [pkg, pkg, ...]
npm tag <project>@<version> [<tag>]
npm unpublish <project>[@<version>]
npm update
Commands that work - local:
npm bin / npm prefix / npm root
npm bugs / npm docs
npm cache ...
npm completion
npm config ... / npm get / npm set
npm edit / npm explore
npm faq / npm help / npm help-search
npm init
npm link
npm ls
npm pack
npm rebuild
npm rm / npm uninstall / npm prune
npm run-script/ npm start / npm restart / npm stop / npm test
npm submodule
npm shrinkwrap
npm version
npm whoami
<file_sep>/test/package.test.js
var fs = require('fs'),
util = require('util'),
assert = require('assert'),
Package = require('../lib/package.js');
exports['given a package'] = {
before: function(done) {
var Cache = require('../lib/cache.js');
Cache.configure({ cacheDirectory: __dirname+'/db/'});
Package.configure({
cache: Cache,
externalUrl: 'http://localhost:8080'
});
done();
},
'can fetch a package index': function(done) {
this.timeout(10000);
Package.get('foo', function(err, json) {
var expected = JSON.parse(
fs.readFileSync(__dirname+'/db/foo/index.json')
.toString().replace('http://registry.npmjs.org/foo', 'http://localhost:8080/foo')
);
assert.deepEqual(json, expected);
done();
});
},
'can fetch a specific version in the index': function(done) {
Package.get('foo', '1.0.0', function(err, json) {
var expected = JSON.parse(
fs.readFileSync(__dirname+'/db/foo/index.json')
.toString().replace('http://registry.npmjs.org/foo', 'http://localhost:8080/foo')
).versions["1.0.0"];
assert.deepEqual(json, expected);
done();
});
},
'can check file sha': function(done) {
Package.checkFile(__dirname+'/fixtures/requireincontext/requireincontext-0.0.2.tgz', function(err, actual) {
assert.notEqual('4a77c6f7ccbd43e095d9fc6c943e53707e042f41', actual);
assert.equal('3bb7b8a676e95a33a0f28f081cf860176b8f67c7', actual);
done();
});
}
};
// if this module is the script being run, then run the tests:
if (module == require.main) {
var mocha = require('child_process').spawn('mocha', [ '--colors', '--ui', 'exports', '--reporter', 'spec', __filename ]);
mocha.stdout.pipe(process.stdout);
mocha.stderr.pipe(process.stderr);
}
<file_sep>/server.js
var http = require('http'),
api = require('./lib/api.js'),
config = require('./config.js');
var server = http.createServer();
server.on('request', function(req, res) {
if(!api.route(req, res)) {
console.log('No route found', req.url);
res.end();
}
}).listen(config.port, config.host);
|
1d89694ebd5ebe91744e634c1c63f45697978218
|
[
"JavaScript",
"Makefile",
"Markdown"
] | 13
|
JavaScript
|
mixu/npm_push
|
822c7f7225bf57a5a6ff2a09b2ba930d40426d7c
|
82d120cb9774b326b59ddff4554109a8520627a3
|
refs/heads/master
|
<repo_name>daver1419/app_lib_multitracker_android<file_sep>/app/src/main/java/com/artear/multitrackerandroid/App.kt
package com.artear.multitrackerandroid
import android.app.Application
import com.artear.multitracker.MultiTracker
import com.artear.multitrackerandroid.trackers.AnalyticsTracker
import com.artear.multitrackerandroid.trackers.OtherCustomTracker
import timber.log.Timber
class App : Application() {
override fun onCreate() {
super.onCreate()
Timber.plant(Timber.DebugTree())
//In your app register all trackers
MultiTracker.instance.register(AnalyticsTracker(baseContext))
MultiTracker.instance.register(OtherCustomTracker(baseContext))
}
}
<file_sep>/app/src/main/java/com/artear/multitrackerandroid/trackers/type/view/MyView.kt
package com.artear.multitrackerandroid.trackers.type.view
import com.artear.multitracker.contract.send.TrackerView
class MyView(private val name: String) : TrackerView {
override fun toString(): String {
return "< MyView - name = $name >"
}
}
<file_sep>/multitracker/src/main/java/com/artear/multitracker/contract/tracker/Tracker.kt
/*
* Copyright 2018 <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.artear.multitracker.contract.tracker
import com.artear.multitracker.contract.send.TrackerSend
/**
* A basic interface which can send a [TrackerSend] object and receive
* the lifecycle events of a traditional component. Also define a key to identify itself.
*
*
* For example: [MultiTracker][com.artear.multitracker.MultiTracker] or
* [ContextTracker][com.artear.multitracker.ContextTracker].
*/
interface Tracker {
fun send(params: TrackerSend)
fun onResume()
fun onPause()
fun onDestroy()
fun keyName(): String
}
<file_sep>/app/src/main/java/com/artear/multitrackerandroid/TrackerActivity.kt
package com.artear.multitrackerandroid
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.artear.multitracker.MultiTracker
import com.artear.multitrackerandroid.trackers.AnalyticsTracker
import com.artear.multitrackerandroid.trackers.OtherCustomTracker
import com.artear.multitrackerandroid.trackers.type.event.MyEvent
import com.artear.multitrackerandroid.trackers.type.exception.MyException
import com.artear.multitrackerandroid.trackers.type.view.MyView
import kotlinx.android.synthetic.main.activity_tracker.*
class TrackerActivity : AppCompatActivity() {
private val testView = MyView("Main View")
private val testEventOne = MyEvent("Event One")
private val testEventTwo = MyEvent("Event Two")
private val testException = MyException(MyException.ErrorCode.INTERNAL_ERROR, "Error :(")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_tracker)
sendViewButton.setOnClickListener {
//Only send to an specific tracker
MultiTracker.instance.send(testView, arrayOf(AnalyticsTracker::class.java.name))
}
sendEventButton.setOnClickListener {
val justSomeTrackers = arrayOf(AnalyticsTracker::class.java.name,
OtherCustomTracker::class.java.name)
MultiTracker.instance.send(testEventOne, justSomeTrackers)
MultiTracker.instance.send(testEventTwo, justSomeTrackers)
}
sendExceptionButton.setOnClickListener {
//Send to all tracker registered
MultiTracker.instance.send(testException)
}
}
}
<file_sep>/multitracker/src/main/java/com/artear/multitracker/MultiTracker.kt
/*
* Copyright 2018 <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.artear.multitracker
import com.artear.multitracker.MultiTracker.Companion.instance
import com.artear.multitracker.contract.send.TrackerSend
import com.artear.multitracker.contract.tracker.Tracker
import com.artear.tools.android.log.logD
import java.util.concurrent.Executors
/**
* A simple class for track and propagate to all trackers registered.
* To send a [TrackerSend] each tracker registered must implements [Tracker].
*
* MultiTracker is a singleton, its creation must be through [instance] .
*/
class MultiTracker private constructor() : Tracker {
companion object {
val instance = MultiTracker()
}
private val trackers = hashMapOf<String, Tracker>()
private val executor = Executors.newSingleThreadExecutor()!!
/**
* It is used to register a tracker and send to it a [TrackerSend] in the future.
*
* @param tracker The tracker to deliver the send message.
*/
fun register(tracker: Tracker) {
if (trackers.containsKey(tracker.keyName())) {
logD { "- MultiTracker - Tracker type currently exists: ${tracker.keyName()}" }
}
trackers[tracker.keyName()] = tracker
}
/**
* Use this method for send only to some specific trackers. For send to all trackers use
* [send][com.artear.multitracker.contract.tracker.Tracker.send]
*
* @param param The object to be sent.
* @param trackerKeys The keys that represent to which tracker will be delivered.
*
*/
fun send(param: TrackerSend, trackerKeys: Array<String>) {
trackerKeys.forEach {
if (trackers.containsKey(it)) {
executor.submit { trackers[it]?.send(param) }
} else {
logD { "- MultiTracker - Tracker unknown keyName: $it " }
}
}
}
/**
* Use this for send to all trackers registered.
*
* @param params The object to be sent.
*/
override fun send(params: TrackerSend) {
send(params, trackers.keys.toTypedArray())
}
override fun onResume() {
trackers.values.forEach { executor.submit { it.onResume() } }
}
override fun onPause() {
trackers.values.forEach { executor.submit { it.onPause() } }
}
override fun onDestroy() {
trackers.values.forEach { executor.submit { it.onDestroy() } }
trackers.clear()
}
override fun keyName(): String {
return javaClass.name
}
}<file_sep>/app/src/main/java/com/artear/multitrackerandroid/trackers/AnalyticsTracker.kt
package com.artear.multitrackerandroid.trackers
import android.content.Context
import com.artear.multitracker.ContextTracker
import com.artear.multitracker.contract.send.TrackerSend
import com.artear.tools.android.log.logD
class AnalyticsTracker(context: Context) : ContextTracker(context) {
override fun send(params: TrackerSend) {
logD { "- AnalyticsTracker - Send params to some place. Param = $params" }
}
override fun onResume() {
}
override fun onPause() {
}
override fun onDestroy() {
}
}
<file_sep>/multitracker/build.gradle
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath "com.jfrog.bintray.gradle:gradle-bintray-plugin:$bintrayVersion"
classpath "com.github.dcendents:android-maven-gradle-plugin:$dcendentsVersion"
classpath "org.jetbrains.dokka:dokka-android-gradle-plugin:$dokkaVersion"
}
}
plugins {
id 'com.android.library'
id 'kotlin-android'
id 'kotlin-android-extensions'
id 'kotlin-kapt'
id 'com.github.ben-manes.versions' version '0.21.0'
}
ext {
bintrayRepo = 'Android'
bintrayName = 'com.artear.multitracker'
publishedGroupId = 'com.artear.multitracker'
libraryName = 'MultiTracker'
artifact = 'multitracker'
libraryDescription = 'Elegant library to send events to different agents'
siteUrl = 'https://github.com/Artear/App_Library_ANDROID_MultiTracker'
gitUrl = 'https://github.com/Artear/App_Library_ANDROID_MultiTracker.git'
developerId = 'artear'
developerName = '<NAME>'
licenseName = 'The Apache Software License, Version 2.0'
licenseUrl = 'http://www.apache.org/licenses/LICENSE-2.0.txt'
allLicenses = ["Apache-2.0"]
}
static int getVersionCode(branch) {
def versionCodeCommand = "git rev-list --count " + branch
return versionCodeCommand.execute().text.trim().toInteger()
}
static def getBranchName() {
return "git rev-parse --abbrev-ref HEAD".execute().text.trim()
}
android {
compileSdkVersion 28
buildToolsVersion "28.0.3"
def branch = getBranchName()
def vCode = 0 + getVersionCode(branch)
defaultConfig {
minSdkVersion 17
targetSdkVersion 28
versionCode vCode
versionName libraryVersion
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
//Test
testImplementation "junit:junit:$junitVersion"
androidTestImplementation "androidx.test:runner:$testRunnerVersion"
androidTestImplementation "androidx.test.espresso:espresso-core:$espressoCoreVersion"
//Kotlin
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlinVersion"
//Support
implementation "androidx.annotation:annotation:$annotationsVersion"
//Artear
implementation "com.artear.tools:tools:$toolsVersion"
}
dependencyUpdates.resolutionStrategy {
componentSelection { rules ->
rules.all { ComponentSelection selection ->
boolean rejected = ['alpha', 'beta', 'rc', 'cr', 'm', 'preview', 'b', 'ea'].any { qualifier ->
selection.candidate.version ==~ /(?i).*[.-]${qualifier}[.\d-+]*/
}
if (rejected) {
selection.reject('Release candidate')
}
}
}
}
group = publishedGroupId
version = libraryVersion
apply from: 'publication.gradle'
apply from: 'bintray.gradle'
<file_sep>/versions.gradle
buildscript {
ext {
// -------- Library Version ---------
libraryVersion = '0.1.4'
// ------------ Kotlin --------------
kotlin_version = '1.3.31'
kotlinVersion = kotlin_version
// ------------ Gradle --------------
gradle_build_version = '3.3.2'
// ------------ Bintray -------------
bintrayVersion = '1.8.4'
// ------------ Dokka ---------------
dokkaVersion = '0.9.18'
// ---------- dcendents -------------
dcendentsVersion = '2.1'
// ------------- Test ---------------
junitVersion = '4.12'
testRunnerVersion = '1.1.1'
espressoCoreVersion = '3.1.1'
// ----------- Framework ------------
// AndroidX
appCompatVersion = '1.0.2'
// Annotations
annotationsVersion = '1.0.2'
// ------------- Artear -------------
// Tools
toolsVersion = '0.0.19'
}
}<file_sep>/app/build.gradle
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
static int getVersionCode(branch) {
def versionCodeCommand = "git rev-list --count " + branch
return versionCodeCommand.execute().text.trim().toInteger()
}
static def getBranchName() {
return "git rev-parse --abbrev-ref HEAD".execute().text.trim()
}
android {
compileSdkVersion 28
buildToolsVersion "28.0.3"
def branch = getBranchName()
def vCode = 0 + getVersionCode(branch)
defaultConfig {
applicationId "com.artear.multitrackerandroid"
minSdkVersion 17
targetSdkVersion 28
versionCode vCode
versionName libraryVersion
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation project(path: ':multitracker')
implementation fileTree(dir: 'libs', include: ['*.jar'])
//Test
testImplementation "junit:junit:$junitVersion"
androidTestImplementation "androidx.test:runner:$testRunnerVersion"
androidTestImplementation "androidx.test.espresso:espresso-core:$espressoCoreVersion"
//Kotlin
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlinVersion"
//AndroidX
implementation "androidx.appcompat:appcompat:$appCompatVersion"
//Artear
implementation "com.artear.tools:tools:$toolsVersion"
}
<file_sep>/app/src/main/java/com/artear/multitrackerandroid/trackers/type/event/MyEvent.kt
package com.artear.multitrackerandroid.trackers.type.event
import com.artear.multitracker.contract.send.TrackerEvent
class MyEvent(private val name: String) : TrackerEvent {
override fun toString(): String {
return "< MyEvent - name = $name >"
}
}
<file_sep>/settings.gradle
include ':app', ':multitracker'
<file_sep>/app/src/main/java/com/artear/multitrackerandroid/trackers/OtherCustomTracker.kt
package com.artear.multitrackerandroid.trackers
import android.content.Context
import com.artear.multitracker.ContextTracker
import com.artear.multitracker.contract.send.TrackerSend
import com.artear.tools.android.log.logD
class OtherCustomTracker(context: Context) : ContextTracker(context) {
override fun send(params: TrackerSend) {
logD { "- OtherCustomTracker - Send params to custom server. Param = $params" }
}
override fun onResume() {
}
override fun onPause() {
}
override fun onDestroy() {
}
}
<file_sep>/multitracker/src/main/java/com/artear/multitracker/ContextTracker.kt
/*
* Copyright 2018 <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.artear.multitracker
import android.content.Context
import com.artear.multitracker.contract.tracker.Tracker
/**
* ContextTracker is a tracker which needs a [Context] for the implementation.
*
*
* Most common of libraries to track and receive events needs the context to initialize.
*/
abstract class ContextTracker(val context: Context) : Tracker {
/**
* By default the key used is the class name. You can override this
* and use the key would you prefers
*/
override fun keyName(): String {
return javaClass.name
}
}
<file_sep>/app/src/main/java/com/artear/multitrackerandroid/trackers/type/exception/MyException.kt
package com.artear.multitrackerandroid.trackers.type.exception
import com.artear.multitracker.contract.send.TrackerException
class MyException(private val code: ErrorCode, private val messenger: String) : TrackerException {
enum class ErrorCode {
INVALID_CHARACTER,
INTERNAL_ERROR
}
override fun toString(): String {
return "< MyException - code = $code, messenger = $messenger >"
}
}
|
9e535dc06b4e192bd5decff20db2deff354a1d60
|
[
"Kotlin",
"Gradle"
] | 14
|
Kotlin
|
daver1419/app_lib_multitracker_android
|
6014f3e86935b78e08b23ef457b9d4d8c14b7dda
|
10c32f590c5f3b98e94d288bfc12e61138101142
|
refs/heads/master
|
<file_sep>package com.clearevo.quran_thai;
import com.clearevo.quran_thai.R;
import java.io.*;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextSwitcher;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewSwitcher;
import android.graphics.Typeface;
import android.util.TypedValue;
import android.util.Log;
import android.content.Intent;
//TODO: add search, toast about how to use GOTO option in settings to jump to chapter, verse
//image resize cmd example: convert -resize 96x96 qth.png ../drawable-xhdpi/ic_launcher.png
public class QuranTHAIActivity extends Activity implements ViewSwitcher.ViewFactory,
View.OnClickListener, OnTouchListener {
public static final String MENU_GOTO_STR = "ข้ามไปซูเราะห์อื่น...";
final int DIALOG_GOTO_ID = 0;
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
switch(id) {
case DIALOG_GOTO_ID:
{
// get prompts.xml view
LayoutInflater li = LayoutInflater.from(this);
View promptsView = li.inflate(R.layout.goto_dialog, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
// set prompts.xml to alertdialog builder
alertDialogBuilder.setView(promptsView);
final EditText userInput0 = (EditText) promptsView.findViewById(R.id.goto_ch);
final EditText userInput1 = (EditText) promptsView.findViewById(R.id.goto_v);
// set dialog message
alertDialogBuilder.setCancelable(true);
DialogInterface.OnClickListener on_ok = new DialogInterface.OnClickListener() {
int c=0,v=1;
@Override
public void onClick(DialogInterface dialog, int which)
{
// get user input and set it to result
// edit text
try
{
c = Integer.parseInt(userInput0.getText().toString());
try{
v = Integer.parseInt(userInput1.getText().toString());
}catch(Exception e){}
display_verses(c,v,true);
}catch(Exception e){
alert("กรุณาใส่ตัวเลขซูเราะห์");
return;
}
//dialog.cancel();
}
};
alertDialogBuilder.setPositiveButton("ไป", on_ok);
DialogInterface.OnClickListener on_cancel = new DialogInterface.OnClickListener() {
int c,v;
@Override
public void onClick(DialogInterface dialog, int which)
{
//dialog.cancel();
}
};
alertDialogBuilder.setNegativeButton("ยกเลิก",on_cancel);
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
break;
}
return dialog;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(MENU_GOTO_STR);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
if(item.getTitle().equals(MENU_GOTO_STR))
{
showDialog(DIALOG_GOTO_ID);
return true;
}
return super.onOptionsItemSelected(item);
}
private TextSwitcher mSwitcher;
private int mCounter = 0;
VerseLoader g_vl_ar;//arabic
VerseLoader g_vl_th;//thai
TextView g_view;
Typeface face_ar;
Typeface face_th;
ScrollView sv;
LinearLayout ll;
Button ppb, npb; //prev page button, next page button
//prev chapter, verse index
int g_prevc = 1;
int g_prevv = 1;
static int NVERSEPERPAGE = 12;
@Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
outState.putInt("g_prevc",g_prevc);
outState.putInt("g_prevv",g_prevv);
save_read_pos();
super.onSaveInstanceState(outState);
}
public void save_read_pos()
{
try
{
String FILENAME = "read_pos.dat";
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
DataOutputStream dos = new DataOutputStream(fos);
dos.writeInt(g_prevc);
dos.writeInt(g_prevv);
Log.d("qth_act","wrote 4 c:v "+g_prevc+":"+g_prevv);
dos.close();
fos.close();
}
catch(Exception e)
{
Log.d("qth_act","write excep +"+e.toString());
}
}
public void get_read_pos()
{
try
{
String FILENAME = "read_pos.dat";
FileInputStream fos = openFileInput(FILENAME);
DataInputStream dos = new DataInputStream(fos);
g_prevc = dos.readInt();
g_prevv = dos.readInt();
Log.d("qth_act","r 5 c:v"+g_prevc+":"+g_prevv);
dos.close();
fos.close();
}
catch(Exception e)
{
Log.d("qth_act","read excep +"+e.toString());
}
}
public void init_sv()
{
sv = new ScrollView(this);
ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
sv.addView(ll);
//sv.setOnTouchListener(this);
//sv.seto
/*TextView tv = new TextView(this);
try
{
tv.setText(g_vl.GotoVerse(1,1));
ll.addView(tv);
}
catch(Exception e)
{
alert("goto init verse failed: "+ e.toString());
}*/
ppb = (Button) new Button(this);
ppb.setText("ก่อนหน้า...");
ppb.setOnClickListener(this);
npb = (Button) new Button(this);
npb.setText("ต่อไป...");
npb.setOnClickListener(this);
}
public void display_verses(int c, int v, boolean forward) //starting with c,v
{
//check if valid first
if(!g_vl_th.does_verse_exist(c,v))
{
alert("ไม่พบ ซูเราะห์:อายะห์ "+c+":"+v+" ในฐานข้อมูล");
return;
}
////////////////////
ll.removeAllViews();
g_prevc = c;
g_prevv = v;
for(int i=0;i<NVERSEPERPAGE;i++)
{
TextView tv_ar;
if (android.os.Build.VERSION.SDK_INT < 11) {
tv_ar = null;
} else {
tv_ar = new TextView(this);
tv_ar.setTypeface(face_ar);
tv_ar.setTextSize(TypedValue.COMPLEX_UNIT_SP,28);
}
//tv_ar.setLineSpacing (0, (float) 1.5 );
//float tsx = tv_ar.getTextScaleX();
//tsx *= 2.0;
//tv_ar.setTextScaleX(tsx);
TextView tv_th = new TextView(this);
tv_th.setTextSize(TypedValue.COMPLEX_UNIT_SP,20);
tv_th.setTypeface(face_th);
try
{
String s = null;
if(i==0)
s = g_vl_th.GotoVerse(c, v);
else
{
if(forward)
s= g_vl_th.GotoNextVerse();
else
s= g_vl_th.GotoPreviousVerse();
}
if(s == null)
{
break;
}
s += "\n__________";
tv_th.setText(s);
//add arabic
//thai arab universities alumni association's translation excludes bismillah except surah 1
int tc, tv;
tc = g_vl_th.chapter;
tv = g_vl_th.verse;
/*if(tc == 1 || tc == 9)
;
else
tv += 1;
*/
if(tv_ar != null) {
s = g_vl_ar.GotoVerse(tc, tv);
if (s != null)
tv_ar.setText(s);
}
if(forward)
{
if(tv_ar != null)
ll.addView(tv_ar);
ll.addView(tv_th);
}
else
{
ll.addView(tv_th,0);
if(tv_ar != null)
ll.addView(tv_ar,0);
}
}
catch(Exception e)
{
alert("get verse failed: "+ e.toString());
}
}
if(!forward) //set as if we loaded forward from c,v behind
{
int tc, tv;
tc = g_vl_th.chapter;
tv = g_vl_th.verse;
g_vl_th.chapter = g_prevc;
g_vl_th.verse = g_prevv;
g_prevc = tc;
g_prevv = tv;
}
if(g_prevc == 1 && g_prevv == 1)
;//dont add prev_button
else
ll.addView(ppb,0);//add prev button
if(g_vl_th.chapter == g_vl_th.NCHAPTERS && g_vl_th.verse == g_vl_th.GetNumberOfVerses(g_vl_th.NCHAPTERS))
;//dont add next
else
ll.addView(npb);//add next button
if(forward)
{
sv.scrollTo(0, 0);
}
else
{
//sv.scrollTo(0, sv.getHeight()-1);
sv.post(new Runnable() {
@Override
public void run() {
sv.fullScroll(ScrollView.FOCUS_DOWN);
}
});
}
}
public void change_page(boolean next)
{
if(next)
{
display_verses(g_vl_th.chapter,g_vl_th.verse,true);
}
else
{
display_verses(g_prevc,g_prevv,false);
}
}
public void alert(String s)
{
Context context = getApplicationContext();
CharSequence text = s;
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
public void alert_long(String s)
{
Context context = getApplicationContext();
CharSequence text = s;
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
@Override
public void onDestroy ()
{
super.onDestroy();
save_read_pos();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(savedInstanceState == null)
get_read_pos();
//////////////////////NEW CODE - LONG VERTICAL LIST
//http://www.dreamincode.net/forums/topic/130521-android-part-iii-dynamic-layouts/
try
{
g_vl_th = new VerseLoader(this,"data_th");
g_vl_ar = new VerseLoader(this,"data_ar");
g_vl_ar.skip_verse_num = true;
}
catch(Exception e)
{
alert("create verse_loader failed: "+e.toString());
}
init_sv();
if(savedInstanceState != null)
{
g_prevc = savedInstanceState.getInt("g_prevc", 1);
g_prevv = savedInstanceState.getInt("g_prevv", 1);
}
else
{
//do nothing - already loaded from get_read_pos(); above
}
if(face_ar == null)
face_ar = Typeface.createFromAsset(getAssets(), "fonts/DroidSansArabic.ttf");
if(face_th == null)
face_th = Typeface.createFromAsset(getAssets(), "fonts/Waree.ttf");
try {
//////if we got intetnt to open chapter to overwrite the chapter and verse
Intent intent = getIntent();
short read_chap;
read_chap = intent.getShortExtra("schap",(short) 0);
Log.d("qth_act","start_chap key in intent val "+read_chap);
if(read_chap != 0)
{
g_prevc = (int) read_chap;
g_prevv = 1;
}
} catch (Exception e) {}
display_verses(g_prevc,g_prevv,true);
this.setContentView(sv);
if (android.os.Build.VERSION.SDK_INT < 11)
alert_long("โทรศัพท์นี้ไม่รองรับการแสดงอักษรอาหรับแบบติดกิน (ต้องการ Android 3.0 หรือใหม่กว่า)");
}
public void onClick(View v) {
if(g_vl_th != null)
{
if(v == npb)
{
change_page(true);
}
else if( v == ppb)
{
change_page(false);
}
}
}
public View makeView() {
TextView t = new TextView(this);
t.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL);
t.setTextSize(40);
//t.setTypeface(face);
t.setOnTouchListener(this);
g_view = t;
return t;
}
@Override
public boolean onTouch(View v, MotionEvent event) {
//not used anymore...
if(sv != null && sv == v)
{
}
return false;
}
}<file_sep><?xml version="1.0"?>
<!-- http://www.comscigate.com/ant/A_beginners_guide_to_Ant.htm - build file for lesson 1 -->
<project name="qth_parser" default="build" basedir=".">
<target name="build">
<javac srcdir="." />
</target>
</project>
<file_sep>qth_parser - Generic scripture data indexer for load in Android, j2me
==========
Generic scripture data indexer (for huge text in the UTF-8 text formatted with chapter:verse) - designed to make easy-load-to-mem possible for both j2me and android - this program cuts, does indexing and make key files to load the data.
Reading, loading, skipping in the the whole multi-megabyte file is often impossible/fails on mobile phones with low memory, so the purpost of this project is to make it possible to jump and read any chapter:verse from the huge original text file. Sample data is from a Thai Quran translation.
NOTE: The quality/standard of the code is quite low as this was written when I had less experience in programming, but it continued to work so there was no need to rewrite it.
Howto
----
Generally, we take a huge text file containing lines of "verses" in the format like the sample "th.txt" that qth_parser sucessfully parses and generates the "data" folder with all the files, then we put that "data" folder into the reader application - [QuranTHAI sample reader project](https://github.com/ykasidit/QuranTHAI) - into its "assets" folder. Then we use/customize that reader application to read (mainly in VerseLoader.java) and display that "data".
To build manually with apache ant in this base folder and run:
ant
To run with commandline param telling the input file:
java qth_parser th.txt
Input text file format
----------------------
(empty line)
(chapter_num):(verse_num)(single_space)(verse_contents)
...
The sample th.txt and ar.txt were generated from original files from www.qurandatabase.org - used Gnumeric to edit them and save into plain text_configurable and in its wizard/form - use "unix line feed", custom > (empty) separator, quoting > never, encoding: utf-8.
Credits to other projects
------------------------
Credit to http://www.qurandatabase.org/ for providing both the Arabic text and Thai translations used here in an easy-to-program format.
<file_sep>QuranTHAI - A Scripture reader Android app
===============================
QuranTHAI is a **generic scripture reader Android app** (for huge text in the UTF-8 text formatted with chapter:verse). Sample data is from a Thai Quran translation.
All data is stored in specially structured assets/data folder - designed to store and make easy-load-to-mem possible for both j2me and android - there are data index and key files too - all generated by the **qth_parser** program in the folder with its name.
howto
----
Generally, we take a huge text file containing lines of "verses" in the format that qth_parser sucessfully parses and generates the "data" folder with all the files, then we put that "data" folder into this "assets" folder. Then we use/customize this application to read (mainly in VerseLoader.java) and display that "data".
Credits to other projects
=========================
Data source
-----------
Credit to http://www.qurandatabase.org/ for providing both the Arabic text and Thai translations used here in an easy-to-program format.
Arabic font used
----------------
Thanks to "ahmedre" for providing "DroidSansArabic.ttf" which proves to be a clear/working arabic font that doesnt skip or get squeezed as the various others tried on Android...
URL: https://github.com/ahmedre/quran_android/tree/master/app/assets
Thai font used
--------------
Credit to the developers who made the "Waree" font from the TLWG project.
URL: http://linux.thai.net/projects/thaifonts-scalable
|
0ca288b75ccd99a2b402cddc258cda65b152a30b
|
[
"Markdown",
"Java",
"Ant Build System"
] | 4
|
Java
|
ykasidit/QuranTHAI
|
a28f90b7f46c2870bf6eae5bfe82b680e0256266
|
0352c63e5d27d66fbb3bbd22f096ee839019ec7c
|
refs/heads/master
|
<file_sep># Boku No Hero Academia
## Sinopsis
[Boku No Hero Academia](https://es.wikipedia.org/wiki/My_Hero_Academia) es una serie de manga escrita e ilustrada por <NAME>. Se basa en un one-shot realizado por el mismo autor y publicado en el quinto volumen del manga Ōmagadoki Dōbutsuen bajo el nombre de My Hero.23 El 11 de enero de 2015, fue lanzado un VOMIC basado en el manga. [Página oficial del manga/anime](https://heroaca.com/)<file_sep># Hamefura
## Sinopsis
[Hemefura](https://es.wikipedia.org/wiki/Otome_Game_no_Hametsu_Flag_Shika_Naiiii_Akuyaku_Reij%C5%8D_ni_Tensei_Shiteshimatta...)La única hija de duque Claes, Catarina, era orgullosa y egoísta porque fue malcriada por sus padres. Sin embargo, a la edad de ocho años, su padre la llevó al castillo real donde ella golpea su cabeza contra una piedra. Después de esto, recupera los recuerdos de su vida anterior como una niña otaku que perdió la vida en un accidente de tráfico. Este mundo le parece familiar, por lo que se da cuenta de que es el del juego otome, Fortune Lover, que jugó antes de su accidente y que en realidad reencarnó como la rival de la heroína y antagonista del juego, también recuerda que todo lo que le esperaba a Catarina al final del juego era el camino a la destrucción que termina en su exilio lejos del reino o su ejecución. Por lo tanto, Catarina dedicará todos sus esfuerzos a evitar un final destructivo para pasar una vejez pacífica. [Opening del anime](https://www.youtube.com/watch?v=00zguIZOXlA)<file_sep>const path = require('path');
const {
beAbsolutePath, transIntoAbsolute, isDirectory, typeOfExtension, isFile,
readingFiles,
readingDirectories,
getArrayOfFilesAndDirectories,
getMDFiles,
getMDLinks,
validateOption,
} = require('../src/index.js');
const cwd = process.cwd();
describe('Testing para saber si beAbsolutePath es función', () => {
it('debería ser una función', () => {
expect(typeof beAbsolutePath).toBe('function');
});
});
describe('Testing para saber si la ruta es absoluta', () => {
it('debería dar true si es ruta absoluta', () => {
// eslint-disable-next-line no-console
// console.log(beAbsolutePath(path.join(cwd, '\\src')));
expect(beAbsolutePath(path.join(cwd, '\\src'))).toBe(true);
});
it('debería dar false si es ruta relativa', () => {
expect(beAbsolutePath('../pruebas/PRUEBA1.md')).toBe(false);
});
});
describe('Testing para convertir ruta relativa a ruta absoluta', () => {
it('transIntoAbsolute debería ser una función', () => {
expect(typeof transIntoAbsolute).toBe('function');
});
it('debería convertir a ruta absoluta', () => {
// console.log(transIntoAbsolute('..\PRUEBA2.md'));
expect(transIntoAbsolute('../pruebas/PRUEBA1.md')).toBe('C:\\Users\\Isabella\\Documents\\Laboratoria-p\\pruebas\\PRUEBA1.md');
});
});
describe('Testing para saber si la ruta es directorio', () => {
it('isDirectory debería ser una función', () => {
expect(typeof isDirectory).toBe('function');
});
it('isDirectory debería dar true si es directorio', () => {
expect(isDirectory('C:\\Users\\Isabella\\Documents\\Laboratoria-p\\LIM012-FE-MD-LINKS\\pruebas')).toBe(true);
});
it('isDirectory debería dar false si es archivo', () => {
expect(isDirectory('C:\\Users\\Isabella\\Documents\\Laboratoria-p\\LIM012-FE-MD-LINKS\\pruebas\\PRUEBA1.md')).toBe(false);
});
});
describe('Testing para saber si es archivo', () => {
it('isFile debería ser una función', () => {
expect(typeof isFile).toBe('function');
});
it('isFile debería dar true si es un archivo', () => {
expect(isFile('C:\\Users\\Isabella\\Documents\\Laboratoria-p\\LIM012-FE-MD-LINKS\\pruebas\\PRUEBA1.md')).toBe(true);
});
});
describe('Testing para saber cual es la extensión del archivo es', () => {
it('typeOfExtension debería ser un función', () => {
expect(typeof typeOfExtension).toBe('function');
});
it('typeOfExtension debe identificar la extensión de esta ruta: .md', () => {
expect(typeOfExtension('C:\\Users\\Isabella\\Documents\\Laboratoria-p\\LIM012-FE-MD-LINKS\\pruebas\\PRUEBA1.md')).toBe('.md');
});
});
describe('Testing para saber si readingFiles lee archivos', () => {
it('readingFiles debería ser una función', () => {
expect(typeof readingFiles).toBe('function');
});
});
describe('Testing para saber si readingDirectories lee directorios', () => {
it('readingDirectories debería ser una función', () => {
expect(typeof readingDirectories).toBe('function');
});
});
describe('Testing para saber si getArrayOfFilesAndDirectories da los archivos y directorios de una ruta', () => {
it('getArrayOfFilesAndDirectories debería ser una función', () => {
expect(typeof getArrayOfFilesAndDirectories).toBe('function');
});
});
describe('Testing para saber si getMDFiles da los archivos md de una ruta', () => {
it('getMDFiles debería ser una función', () => {
expect(typeof getMDFiles).toBe('function');
});
});
describe('Testisng para saber si getMDLinks obtiene los links de una ruta', () => {
it('getMDLinks debería ser una función', () => {
expect(typeof getMDLinks).toBe('function');
});
});
describe('Testing para saber si validateOption valida en estado de los links de los archivos md de una ruta', () => {
expect(typeof validateOption).toBe('function');
});
<file_sep># Markdown Links 📄🔗

## About the project
Welcome to my first library! This the Markdown Links Library which will help you to extract
the links of all the markdown links of a path. It also give the information:
- Validate Links(OK, FAIL)
- Stats Links(total, unique, broken)
SPOILER ALERT!!

## Flow Chart
- To create this library first we need to understand how we can built everything from the start, that's why we used:
- Flow Chart.
- Git hub projects.
### API Flow Chart

### CLI Flow Chart


## How to install mdLinks?
- Install this library with this command: `npm install IsabelaSanchez/LIM012-fe-md-links `
### API `mdLinks(path, opts)`
#### Example of how to use it:
```js
const mdLinks = require("md-links");
mdLinks("./some/example.md")
.then(links => {
// => [{ href, text, file }]
})
.catch(console.error);
mdLinks("./some/example.md", { validate: true })
.then(links => {
// => [{ href, text, file, status, ok }]
})
.catch(console.error);
mdLinks("./some/dir")
.then(links => {
// => [{ href, text, file }]
})
.catch(console.error);
```
### CLI (Command Line Interface - Interfaz de Línea de Comando)
```js
Remember that to use this library you need to insert:
👉 md-links <path-to-file>
👉 md-links <path-to-file> [valid arguments]
*****************Valid Arguments*****************
⭐md-links <path-to-file> --validate --stats
⭐md-links <path-to-file> --v --s
⭐md-links <path-to-file> --V --S
⭐md-links <path-to-file> --validate
⭐md-links <path-to-file> --stats
*************************************************
```
---
### Data Lovers learning goals
- [⭐] Entender la diferencia entre expression y statements.
- [⭐] Entender el uso de bucles (for | forEach).
- [⭐] Manipular arrays (filter | map | sort | reduce).
- [😅] Entender como funciona flexbox en CSS. *Este objetivo se queda para Red Social
- [⭐] Entender la diferencia entre tipos de datos atómicos y estructurados.
- [⭐] Utilizar linter para seguir buenas prácticas (ESLINT)
### Javascript
- [⭐] Uso de callbacks
- [😅] Consumo de Promesas
- [⭐] Creacion de Promesas
- [⭐] Modulos de Js
- [⭐] Recursión
### Node
- [⭐] Sistema de archivos
- [⭐] package.json
- [⭐] crear modules
- [⭐] Instalar y usar modules
- [⭐] npm scripts
- [⭐] CLI (Command Line Interface - Interfaz de Línea de Comando)
### Testing
- [⭐] Testeo de tus funciones
- [😅] Testeo asíncrono
- [ ] Uso de librerias de Mock
- [ ] Mocks manuales
- [ ] Testeo para multiples Sistemas Operativos
### Git y Github
- [⭐] Organización en Github
### Buenas prácticas de desarrollo
- [⭐] Modularización
- [⭐] Nomenclatura / Semántica
- [ ] Linting
***
## The End :shipit:
So this was mdLinks! I suffer a lot during this project but learn JS for real!

- Thank you to everyone who help and give the opportunity to learn and ask during this process. I know I would be a great Front End Developer!!
- **See you on Red Social!!

## Pistas / Tips
### FAQs
#### ¿Cómo hago para que mi módulo sea _instalable_ desde GitHub?
Para que el módulo sea instalable desde GitHub solo tiene que:
- Estar en un repo público de GitHub
- Contener un `package.json` válido
Con el comando `npm install githubname/reponame` podemos instalar directamente
desde GitHub. Ver [docs oficiales de `npm install` acá](https://docs.npmjs.com/cli/install).
Por ejemplo, el [`course-parser`](https://github.com/Laboratoria/course-parser)
que usamos para la currícula no está publicado en el registro público de NPM,
así que lo instalamos directamente desde GitHub con el comando `npm install
Laboratoria/course-parser`.
### Sugerencias de implementación
La implementación de este proyecto tiene varias partes: leer del sistema de
archivos, recibir argumentos a través de la línea de comando, analizar texto,
hacer consultas HTTP, ... y todas estas cosas pueden enfocarse de muchas formas,
tanto usando librerías como implementando en VanillaJS.
Por poner un ejemplo, el _parseado_ (análisis) del markdown para extraer los
links podría plantearse de las siguientes maneras (todas válidas):
- Usando un _módulo_ como [markdown-it](https://github.com/markdown-it/markdown-it),
que nos devuelve un arreglo de _tokens_ que podemos recorrer para identificar
los links.
- Siguiendo otro camino completamente, podríamos usar
[expresiones regulares (`RegExp`)](https://developer.mozilla.org/es/docs/Web/JavaScript/Guide/Regular_Expressions).
- También podríamos usar una combinación de varios _módulos_ (podría ser válido
transformar el markdown a HTML usando algo como [marked](https://github.com/markedjs/marked)
y de ahí extraer los link con una librería de DOM como [JSDOM](https://github.com/jsdom/jsdom)
o [Cheerio](https://github.com/cheeriojs/cheerio) entre otras).
- Usando un _custom renderer_ de [marked](https://github.com/markedjs/marked)
(`new marked.Renderer()`).
No dudes en consultar a tus compañeras, coaches y/o el [foro de la comunidad](http://community.laboratoria.la/c/js)
si tienes dudas existenciales con respecto a estas decisiones. No existe una
"única" manera correcta :wink:
### Tutoriales / NodeSchool workshoppers
- [learnyounode](https://github.com/workshopper/learnyounode)
- [how-to-npm](https://github.com/workshopper/how-to-npm)
- [promise-it-wont-hurt](https://github.com/stevekane/promise-it-wont-hurt)
### Otros recursos
- [Acerca de Node.js - Documentación oficial](https://nodejs.org/es/about/)
- [Node.js file system - Documentación oficial](https://nodejs.org/api/fs.html)
- [Node.js http.get - Documentación oficial](https://nodejs.org/api/http.html#http_http_get_options_callback)
- [Node.js - Wikipedia](https://es.wikipedia.org/wiki/Node.js)
- [What exactly is Node.js? - freeCodeCamp](https://medium.freecodecamp.org/what-exactly-is-node-js-ae36e97449f5)
- [¿Qué es Node.js y para qué sirve? - drauta.com](https://www.drauta.com/que-es-nodejs-y-para-que-sirve)
- [¿Qué es Nodejs? Javascript en el Servidor - Fazt en YouTube](https://www.youtube.com/watch?v=WgSc1nv_4Gw)
- [¿Simplemente qué es Node.js? - IBM Developer Works, 2011](https://www.ibm.com/developerworks/ssa/opensource/library/os-nodejs/index.html)
- [Node.js y npm](https://www.genbeta.com/desarrollo/node-js-y-npm)
- [Módulos, librerías, paquetes, frameworks... ¿cuál es la diferencia?](http://community.laboratoria.la/t/modulos-librerias-paquetes-frameworks-cual-es-la-diferencia/175)
- [Asíncronía en js](https://carlosazaustre.com/manejando-la-asincronia-en-javascript/)
- [NPM](https://docs.npmjs.com/getting-started/what-is-npm)
- [Publicar packpage](https://docs.npmjs.com/getting-started/publishing-npm-packages)
- [Crear módulos en Node.js](https://docs.npmjs.com/getting-started/publishing-npm-packages)
- [Leer un archivo](https://nodejs.org/api/fs.html#fs_fs_readfile_path_options_callback)
- [Leer un directorio](https://nodejs.org/api/fs.html#fs_fs_readdir_path_options_callback)
- [Path](https://nodejs.org/api/path.html)
- [Linea de comando CLI](https://medium.com/netscape/a-guide-to-create-a-nodejs-command-line-package-c2166ad0452e)
- [Promise](https://javascript.info/promise-basics)
- [Comprendiendo Promesas en Js](https://hackernoon.com/understanding-promises-in-javascript-13d99df067c1)
- [Pill de recursión - video](https://www.youtube.com/watch?v=lPPgY3HLlhQ&t=916s)
- [Pill de recursión - repositorio](https://github.com/merunga/pildora-recursion)
<file_sep>#!/usr/bin/env node
/* eslint-disable no-console */
const { mdLinks } = require('./mdLinks');
const statsOption = (arrayOfMDLinks) => {
const totalLinks = arrayOfMDLinks.length;
const uniqueLinks = new Set(arrayOfMDLinks.map((element) => element.href)).size;
if (totalLinks === 0) {
return 'There is 0 Links in this path! Try another one!';
}
const statsTemplate = `
Final Stats:
TOTAL: ${totalLinks}
UNIQUE: ${uniqueLinks}
`;
return statsTemplate;
};
const statsValidate = (arrayOfMDLinks) => {
const totalLinks = arrayOfMDLinks.length;
const uniqueLinks = new Set(arrayOfMDLinks.map((element) => element.href)).size;
const brokenLinks = new Set(arrayOfMDLinks.filter((href) => (href.status >= 400))).size;
const statsValidateTemplate = `
Final Stats Validate
TOTAL: ${totalLinks}
UNIQUE: ${uniqueLinks}
BROKEN: ${brokenLinks}
`;
return statsValidateTemplate;
};
const help = `
Remember that to use this library you need to insert:
1) md-links <path-to-file>
2) md-links <path-to-file> [valid arguments]
*****************Valid Arguments*****************
⭐md-links <path-to-file> --validate --stats
⭐md-links <path-to-file> -v -s
⭐md-links <path-to-file> --validate
⭐md-links <path-to-file> --stats
*************************************************
`;
const route = process.argv[2]; // argumento 2
const validate = process.argv.indexOf('--validate');
const shortValidate = process.argv.indexOf('-v');// argumento 3
const stats = process.argv.indexOf('--stats');
const shortStats = process.argv.indexOf('-s'); // argumento 4
const helpCom = process.argv.indexOf('--help');
const cliFunction = (route) => {
if (helpCom >= 0 || route === undefined) {
console.log(help);
}
if (route) {
if ((stats >= 0 || shortStats >= 0) && (validate >= 0 || shortValidate >= 0)) {
mdLinks(route, { validate: true })
.then((links) => console.log(statsValidate(links)))
.catch((error) => console.log(error));
}
if (validate >= 0 || shortValidate >= 0) {
mdLinks(route, { validate: true })
.then((links) => console.log(links))
.catch((error) => console.log(help));
}
if (stats >= 0 || shortStats >= 0) {
mdLinks(route, { validate: false })
.then((links) => console.log(statsOption(links)))
.catch((error) => console.error(error));
} else {
mdLinks(route, { validate: false })
.then((links) => console.log(links))
.catch((error) => console.error('Error'));
}
}
};
cliFunction(route);
<file_sep># One Piece
## Sinopsis
[One Piece](https://es.wikipedia.org/wiki/One_Piece) En 2016 era el décimo anime más largo de la historia y el que más ganancias ha reportado a su autor ostentando el récord Guinness como el cómic más vendido de la historia. [Página oficial del manga/anime](http://corp.toei-anim.co.jp/en/film/pickup.php?id=2)
|
9c07bfb8c8b705b6bc9fab236230c7564fee72cc
|
[
"Markdown",
"JavaScript"
] | 6
|
Markdown
|
IsabelaSanchez/LIM012-fe-md-links
|
d34288489553584a89766d5c9b8b6cc9c7b62bb1
|
a7070cb736738c4001451d55b92895733309586a
|
refs/heads/main
|
<repo_name>danicasun/KemisUpdate-main<file_sep>/finalApp/ViewController.swift
//
// ViewController.swift
// finalApp
//
// Created by Scholar on 8/2/21.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var historyButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// historyButton.layer.cornerRadius = 14
}
}
<file_sep>/finalApp/actionViewController.swift
//
// actionViewController.swift
// finalApp
//
// Created by Scholar on 8/4/21.
//
import UIKit
class actionViewController: UIViewController {
@IBOutlet weak var button1: UIButton!
@IBOutlet weak var button2: UIButton!
@IBOutlet weak var button3: UIButton!
@IBOutlet weak var button4: UIButton!
@IBOutlet weak var button5: UIButton!
@IBOutlet weak var button6: UIButton!
@IBOutlet weak var button7: UIButton!
@IBOutlet weak var button8: UIButton!
@IBOutlet weak var button9: UIButton!
@IBOutlet weak var button10: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func task1(_ sender: UIButton) {
button1.isHidden = true
}
@IBAction func task2(_ sender: UIButton) {
button2.isHidden = true
}
@IBAction func task3(_ sender: UIButton) {
button3.isHidden = true
}
@IBAction func task4(_ sender: UIButton) {
button4.isHidden = true
}
@IBAction func task5(_ sender: UIButton) {
button5.isHidden = true
}
@IBAction func task6(_ sender: UIButton) {
button6.isHidden = true
}
@IBAction func task7(_ sender: UIButton) {
button7.isHidden = true
}
@IBAction func task8(_ sender: UIButton) {
button8.isHidden = true
}
@IBAction func task9(_ sender: UIButton) {
button9.isHidden = true
}
@IBAction func task10(_ sender: UIButton) {
button10.isHidden = true
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
|
e4a490a1b1f645ef0af5cd474eb174fc37d148a8
|
[
"Swift"
] | 2
|
Swift
|
danicasun/KemisUpdate-main
|
a2c4b5d2ddee942937c72e65a6dea56927e520b3
|
4d18c9efe525859fcbc3d7c5f59398d73e00a6e3
|
refs/heads/master
|
<repo_name>TRL242/chess_stats_using_api<file_sep>/main.py
from chessdotcom import get_leaderboards, get_player_stats, get_player_game_archives
import pprint
import requests
printer = pprint.PrettyPrinter()
USERNAME = 'PolinaKarelina'
ISO = 'BS'
def print_leaderboards():
data = requests.get('https://api.chess.com/pub/leaderboards').json()
categories = data.keys()
for category in categories:
print('Category:', category)
for idx, entry in enumerate(data[category]):
print(f'Rank: {idx + 1} | Username: {entry["username"]} | Rating: {entry["score"]}')
print_leaderboards()
def country_info(iso):
data = requests.get(f'https://api.chess.com/pub/country/{iso}').json()
print(data)
country_info(ISO)
def print_players_by_country(iso):
data = requests.get(f'https://api.chess.com/pub/country/{iso}/players').json()
players = data.items()
print(players)
print_players_by_country(ISO)
def get_player_rating(username):
data = requests.get(f'https://api.chess.com/pub/player/{username}/stats').json()
categories = ['chess_blitz', 'chess_rapid', 'chess_bullet']
for category in categories:
print('Category:', category)
print(f'Current: {data[category]["last"]["rating"]}')
print(f'Best: {data[category]["best"]["rating"]}')
print(f'Best: {data[category]["record"]}')
get_player_rating(USERNAME)
def get_most_recent_game(username):
data = requests.get(f'https://api.chess.com/pub/player/{username}/games/archives').json()
url = data['archives'][-1]
games = requests.get(url).json()
game = games['games'][-1]
printer.pprint(game)
get_most_recent_game(USERNAME)
|
589f2e42068dd24c31cc82d319ba757c610fbd8d
|
[
"Python"
] | 1
|
Python
|
TRL242/chess_stats_using_api
|
e4349508ef97365a73e9fdf66bfcd48ff02b0191
|
4ac538941a5d2be12ec3230ba44bcf15a22b19c0
|
refs/heads/main
|
<repo_name>shrade1206/mvn-repo<file_sep>/src/test/java/com/fendihotpot/malapot/dao/SetMealDAOHibernateTests.java
package com.fendihotpot.malapot.dao;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.hibernate.Session;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.Rollback;
import org.springframework.transaction.annotation.Transactional;
import com.fendihotpot.malapot.domain.I9sBean;
import com.fendihotpot.malapot.domain.SetMealBean;
import com.fendihotpot.malapot.i9sDao.SetMealDAO;
import com.fendihotpot.malapot.service.SetMealService;
@SpringBootTest
public class SetMealDAOHibernateTests {
@Autowired
private SetMealDAO setMealDAO;
@Autowired
private SetMealService setMealService;
// @Test
// @Transactional
// public void testSelectMeal() {
// List<SetMealBean> select = setMealService.select(null);
// for(SetMealBean bean:select) {
// System.out.println("bean"+bean);
// }
// }
// //DAO 新增食材
// @Test
// @Transactional
// public void testInsertItem() {
// SetMealBean setMealBean = new SetMealBean();
// Set<I9sBean> i9sBeans = new HashSet<I9sBean>();
// I9sBean bean1 = new I9sBean();
// bean1.setI9sId(3);
// I9sBean bean2 = new I9sBean();
// bean2.setI9sId(4);
//
// i9sBeans.add(bean1);
// i9sBeans.add(bean2);
// setMealBean.setName("TestPot6");
// setMealBean.setPrice(1500);
// setMealBean.setType(2);
//
// SetMealBean insert = setMealDAO.insert(setMealBean, i9sBeans);
// Set<I9sBean> i9sBeans2 = insert.getI9sBeans();
// for(I9sBean bean:i9sBeans2) {
// System.out.println("bean="+bean);
// }
// System.out.println("insert="+insert);
// }
// //Service 新增套餐
// @Test
// @Transactional
// @Rollback(false)
// public void testServiceInsertMeal() {
// SetMealBean meal = new SetMealBean();
// meal.setName("HugePot");
// meal.setPrice(1000);
// meal.setType(2);
// SetMealBean insertMeal = setMealService.insertMeal(meal);
// System.out.println("insertMeal="+insertMeal);
// }
// //DAO 新增套餐
// @Test
// @Transactional
// public void testInsertMeal() {
// SetMealBean meal = new SetMealBean();
// meal.setName("海陸總匯鍋");
// meal.setPrice(790);
// meal.setType(2);
// SetMealBean insertMeal = setMealDAO.insertMeal(meal);
// System.out.println("insertMeal="+insertMeal);
// }
// //Service 查詢
// @Test
// @Transactional
// public void testServiceSelect() {
// SetMealBean meal = new SetMealBean();
// meal.setId(2);
// List<List<Object>> meals = setMealService.select(meal);
// System.out.println("meals="+meals);
//
// List<List<Object>> mealss = setMealService.select(null);
// System.out.println("mealss"+mealss);
//
// }
// //DAO單查
// @Test
// @Transactional
// public void testsSelectOnly() {
// List<Object> meals = setMealDAO.select(2);
// SetMealBean meal = (SetMealBean)meals.get(0);
// Set<I9sBean> beans = (Set<I9sBean>)meals.get(1);
// for(I9sBean bean:beans) {
// System.out.println("bean="+bean);
// }
// System.out.println("meal="+meal);
// }
//
// //DAO全查
// @Test
// @Transactional
// public void testSelectAll() {
// List<List<Object>> meals = setMealDAO.selectAll();
// for(List<Object> lists:meals) {
// System.out.println("Meal="+lists.get(0));
// Set<I9sBean> i9sBens = (Set<I9sBean>)lists.get(1);
// for(Object i9sBean:i9sBens) {
// System.out.println("Item="+i9sBean);
// }
// }
// }
}
<file_sep>/src/test/java/com/fendihotpot/malapot/MalapotApplicationTests.java
package com.fendihotpot.malapot;
import javax.persistence.PersistenceContext;
import org.hibernate.Session;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.transaction.annotation.Transactional;
@SpringBootTest
class MalapotApplicationTests {
@PersistenceContext
private Session session;
@Test
void contextLoads() {
}
@Test
@Transactional
void sessionTest() {
Object[] product = (Object[])session.createNativeQuery("select * from product where id=1").uniqueResult();
System.out.println("product="+product[0]+":"+product[1]);
}
}
<file_sep>/src/main/java/com/fendihotpot/malapot/i9sDao/I9sDAO.java
package com.fendihotpot.malapot.i9sDao;
import java.util.List;
import com.fendihotpot.malapot.domain.I9sBean;
public interface I9sDAO {
public abstract I9sBean select(Integer i9sId);
public abstract List<I9sBean> select(Integer i9sId,Integer currentPage,Integer pageSize);
public abstract List<I9sBean> selectAll(Integer currentPage,Integer pageSize);
public abstract I9sBean insert(I9sBean bean);
public abstract I9sBean update(I9sBean bean);
public abstract boolean delete(Integer i9sId);
public abstract Integer totalRows();
}<file_sep>/src/main/resources/static/js/login.js
<script type="text/javascript"
src="${pageContext.servletContext.contextPath }/js/login.js"></script>
$(function() {
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
let firebaseConfig = {
apiKey: "<KEY>",
authDomain: "fendishabu-c6e6d.firebaseapp.com",
databaseURL: "https://fendishabu-c6e6d-default-rtdb.firebaseio.com",
projectId: "fendishabu-c6e6d",
storageBucket: "fendishabu-c6e6d.appspot.com",
messagingSenderId: "215823760498",
appId: "1:215823760498:web:e44e3ea9c96182a1b316eb",
measurementId: "G-4L3K47YRJ0"
};
// Initialize Firebase
let a = firebase.initializeApp(firebaseConfig);
console.log("Initialized");
console.log(a);
firebase.analytics();
//SignIn
let btnIn = document.getElementById("btnSignIn");
btnIn.onclick = function() {
let emailIn = $("#emailIn").val();
let passwordIn = $("#passwordIn").val();
firebase.auth()
.signInWithEmailAndPassword(emailIn, passwordIn)
.then(result => {
console.log(result);
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// 使用者已登入,可以取得資料
var email = user.email;
var uid = user.uid;
console.log(email, uid);
Cookies.set("uid", uid);
console.log(email + " " + uid);
window.location.href = "/shabushabu/pages/login.controller";
} else {
// 使用者未登入
}
});
})
.catch(error => {
console.log(error.message);
});
}
//SignUp
let btn = document.getElementById('btnSignUp');
btn.onclick = function() {
let email = $('#email').val();
let password = $('#password').val();
let moblie = $("#mobile").val(); //displayName
const rex= /^09\d{8}$/;
if(!rex.test($("#mobile").val())){
$("#mobile").val().siblings("span").text("請輸入正確格式").css("color","red");
}else{
$("#mobile").val().siblings("span").text("v").css("color","green");
}
firebase
.auth()
.createuserWithEmailAndPassword(email, password,)
.then(result => {
console.log("註冊");
console.log(result);
let user = firebase.auth().currentuser;
//EmailAuth
user
.sendEmailVerification()
.then(function() {
// 驗證信發送完成
window.alert('驗證信已發送到您的信箱,請點選連結驗證。')
}).catch(error => {
// 驗證信發送失敗
console.log(error.message);
});
}).catch(function(error) {
console.log(error.message)
});
}
//SignOut
let btnOut = document.getElementById("btnSignOut")
btnOut.onclick = function() {
firebase.auth().signOut()
.then(function() {
alert('您已登出');
let user = firebase.auth().currentuser;
Cookies.remove("uid");
console.log(user);
// 登出後強制重整一次頁面
window.location.reload();
}).catch(function(error) {
console.log(error.message)
});
}
//Delete
let btnDelete = document.getElementById('btnDelete');
btnDelete.onclick = function() {
let user = firebase.auth().currentuser;
user.delete().then(function() {
alert('帳號已刪除')
})
}
//Google
let provider = new firebase.auth.GoogleAuthProvider();
let btnGooglePopup = document.getElementById('#googleSignUpPopup');
$("#googleSignUpPopup").on("click", function() {
firebase.auth().signInWithPopup(provider).then(function(result) {
// 可以獲得 Google 提供 token,token可透過 Google API 獲得其他數據。
let token = result.credential.accessToken;
let user = result.user;
let userIn = firebase.auth().currentuser;
if (userIn) {
// user is signed in.
let email = user.email;
let uid = user.uid;
Cookies.set("uid", uid);
alert('登入成功')
} else {
// No user is signed in.
}
})
})
//Facebook
let providerF = new firebase.auth.FacebookAuthProvider();
let btnFacebookPopup = document.getElementById('facebookSignUpPopup');
btnFacebookPopup.onclick = function() {
firebase.auth().signInWithPopup(providerF).then(function(result) {
let token = result.credential.accessToken;
let user = result.user;
let userIn = firebase.auth().currentuser;
if (userIn) {
// user is signed in.
alert('登入成功')
} else {
// No user is signed in.
}
})
}
//忘記密碼
const btnuserForgotSure = document.getElementById('sure-forgot');
btnuserForgotSure.addEventListener('click', e => {
const emailAddress = document.getElementById('new-forgot').value;
const auth = firebase.auth();
firebase.auth().languageCode = 'zh-TW'; // 發信模版改中文
auth.sendPasswordResetEmail(emailAddress).then(() => {
window.alert('已發送信件至信箱,請按照信件說明重設密碼');
window.location.reload();
}).catch(error => {
changeErrMessage(error.message)
});
})
//修改密碼
let btnChangePassword = document.getElementById("sure-password");
btnChangePassword.addEventListener('click', e => {
function reAuth(checkPassword) {
return new Promise(function(resolve, reject) {
let user = firebase.auth().currentuser;
let password = document.getElementById(checkPassword).value;
let credential = firebase.auth.EmailAuthProvider.credential(user.email, password);
user.reauthenticateWithCredential(credential).then(function() {
resolve(user)
}).catch(function(error) {
reject(error.message);
});
})
}
// 取得新密碼
let newPassword = document.getElementById('new-password').value;
// 更新密碼
reAuth('old-password')
.then(function(user) {
user.updatePassword(new<PASSWORD>).then(function() {
window.alert('密碼更新完成,請重新登入');
// 修改密碼完成後,強制登出並重整一次頁面
firebase.auth().signOut().then(function() {
window.location.reload();
});
}).catch(function(error) {
console.log(error.message)
});
}).catch(function(error) {
console.log(error.message)
});
})
})<file_sep>/src/main/java/com/fendihotpot/malapot/domain/TypeBean.java
package com.fendihotpot.malapot.domain;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.OrderBy;
import javax.persistence.Table;
@Entity
@Table(name="TYPE")
public class TypeBean {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="ID")
private Integer id;
@Column(name="NAME")
private String name;
@OneToMany
@JoinColumn(name="TYPE_ID", referencedColumnName="ID")
@OrderBy(value="i9sId asc")
private Set<I9sBean> i9sBeans;
@OneToMany
@JoinColumn(name="TYPE_ID", referencedColumnName="ID")
@OrderBy(value="id asc")
private Set<SetMealBean> setMealBeans;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<I9sBean> getI9sBeans() {
return i9sBeans;
}
public void setI9sBeans(Set<I9sBean> i9sBeans) {
this.i9sBeans = i9sBeans;
}
@Override
public String toString() {
return "TypeBean [id=" + id + ", name=" + name + "]";
}
public Set<SetMealBean> getSetMealBeans() {
return setMealBeans;
}
public void setSetMealBeans(Set<SetMealBean> setMealBeans) {
this.setMealBeans = setMealBeans;
}
}
<file_sep>/src/main/java/com/fendihotpot/malapot/domain/ReservationBean.java
package com.fendihotpot.malapot.domain;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "RESERVATION")
public class ReservationBean {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID")
private Integer rId;
@Column(name = "UID")
private String uid;
@Column(name = "PEOPLE")
private Integer people;
@Column(name = "DATE")
private String date;
@Column(name = "TIME")
private String time;
@Column(name = "BRENCH")
private String brench;
@Column(name = "RNAME")
private String rName;
@Column(name = "EMAIL")
private String email;
@Column(name = "MOBLIE")
private String mobile;
@Override
public String toString() {
return "ReservationBean [rId=" + rId + ", uid=" + uid + ", people=" + people + ", date=" + date + ", time="
+ time + ", brench=" + brench + ", rName=" + rName + ", email=" + email + ", mobile=" + mobile + "]";
}
/**
* @return the rId
*/
public Integer getrId() {
return rId;
}
/**
* @param rId the rId to set
*/
public void setrId(Integer rId) {
this.rId = rId;
}
/**
* @return the uid
*/
public String getUid() {
return uid;
}
/**
* @param uid the uid to set
*/
public void setUid(String uid) {
this.uid = uid;
}
/**
* @return the people
*/
public Integer getPeople() {
return people;
}
/**
* @param people the people to set
*/
public void setPeople(Integer people) {
this.people = people;
}
/**
* @return the date
*/
public String getDate() {
return date;
}
/**
* @param date the date to set
*/
public void setDate(String date) {
this.date = date;
}
/**
* @return the time
*/
public String getTime() {
return time;
}
/**
* @param time the time to set
*/
public void setTime(String time) {
this.time = time;
}
/**
* @return the brench
*/
public String getBrench() {
return brench;
}
/**
* @param brench the brench to set
*/
public void setBrench(String brench) {
this.brench = brench;
}
/**
* @return the rName
*/
public String getrName() {
return rName;
}
/**
* @param rName the rName to set
*/
public void setrName(String rName) {
this.rName = rName;
}
/**
* @return the email
*/
public String getEmail() {
return email;
}
/**
* @param email the email to set
*/
public void setEmail(String email) {
this.email = email;
}
/**
* @return the mobile
*/
public String getMobile() {
return mobile;
}
/**
* @param mobile the mobile to set
*/
public void setMobile(String mobile) {
this.mobile = mobile;
}
}
<file_sep>/src/test/java/com/fendihotpot/malapot/dao/I9sTests.java
package com.fendihotpot.malapot.dao;
import java.util.List;
import java.util.Optional;
import javax.persistence.PersistenceContext;
import org.hibernate.Session;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
import com.fendihotpot.malapot.domain.I9sBean;
@RunWith(SpringRunner.class)
@SpringBootTest
public class I9sTests {
@PersistenceContext
private Session session;
@Test
@Transactional
public void test() {
List<?> result = session.createNativeQuery("select * from ingredients").list();
for (Object obj : result) {
Object[] array = (Object[]) obj;
System.out.println(array[0] + ":" + array[1] + ":" + array[2]+ ":" + array[3] + ":" + array[4]);
}
}
}
<file_sep>/src/main/java/com/fendihotpot/malapot/reservationDAO/ReservationDAOHibernate.java
package com.fendihotpot.malapot.reservationDAO;
import java.util.List;
import javax.persistence.PersistenceContext;
import org.hibernate.Session;
import org.springframework.stereotype.Repository;
import com.fendihotpot.malapot.domain.ReservationBean;
@Repository
public class ReservationDAOHibernate implements ReservationDAO {
@PersistenceContext
private Session session;
public Session getSession() {
return session;
}
// 查詢會員資料
@Override
public ReservationBean select(String uid) {
if (uid != null) {
String hql = "FROM ReservationBean WHERE uid=:uid ORDER BY id DESC";
System.out.println("ttt="+this.getSession().createQuery(hql, ReservationBean.class).setParameter("uid", uid).setMaxResults(1)
.uniqueResult());
return this.getSession().createQuery(hql, ReservationBean.class).setParameter("uid", uid).setMaxResults(1)
.uniqueResult();
}
return null;
}
// 依分店查詢
@Override
public List<ReservationBean> selectOne(String brench, Integer currentPage, Integer pageSize) {
if (brench != null) {
String hql = "FROM ReservationBean WHERE brench=:brench ORDER BY id DESC";
List<ReservationBean> beans = session.createQuery(hql, ReservationBean.class)
.setParameter("brench", brench)
.setFirstResult((currentPage - 1) * pageSize)
.setMaxResults(pageSize)
.list();
return beans;
}
return null;
}
// 查詢所有訂單
@Override
public List<ReservationBean> selectAll(Integer currentPage, Integer pageSize) {
List<ReservationBean> beans = session
.createQuery("from ReservationBean ORDER BY ID DESC", ReservationBean.class)
.setFirstResult((currentPage - 1) * pageSize)
.setMaxResults(pageSize)
.list();
return beans;
}
// 新增訂單
@Override
public ReservationBean insert(ReservationBean bean) {
if (bean != null) {
this.getSession().save(bean);
return bean;
}
return null;
}
// 刪除訂單
@Override
public boolean delete(Integer rId) {
if (rId != null && !rId.equals(0)) {
ReservationBean bean = this.getSession().get(ReservationBean.class, rId);
if (bean != null) {
this.getSession().delete(bean);
return true;
}
}
return false;
}
// 查詢總比數
@Override
public Integer totalRows() {
String hql = "SELECT COUNT(r.id) FROM ReservationBean as r";
return session.createQuery(hql, Long.class).uniqueResult().intValue();
}
@Override
public Integer totalRowsByBranch(String brench) {
String hql = "SELECT COUNT(r.id) FROM ReservationBean as r WHERE r.brench=:brench";
return session.createQuery(hql, Long.class)
.setParameter("brench", brench)
.uniqueResult()
.intValue();
}
}
<file_sep>/src/main/java/com/fendihotpot/malapot/i9sDao/TypeDAO.java
package com.fendihotpot.malapot.i9sDao;
import java.util.List;
import java.util.Set;
public interface TypeDAO {
// public abstract TypeBean select(Integer id);
public abstract List<Set<?>> selectAll();
}
<file_sep>/src/main/java/com/fendihotpot/malapot/controller/PathController.java
package com.fendihotpot.malapot.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class PathController {
@RequestMapping(
path = "/",
method = RequestMethod.GET
)
public String index() {
return "/index";
}
@RequestMapping(path= "/takeout")
public String takeout() {
return "/pages/takeout";
}
@RequestMapping(path= "/order")
public String order() {
return "/pages/order";
}
@RequestMapping(path= "/fmenu")
public String fmenu() {
return "/pages/fmenu";
}
@RequestMapping(path= "/location")
public String location() {
return "/pages/location";
}
@RequestMapping(path= "/backend/mealadd")
public String mealadd() {
return "/backend/mealadd";
}
@RequestMapping(path= "/backend/i9s/{currentPage}")
public String i9s() {
return "/backend/i9s";
}
@RequestMapping(path= "/backend/i9sInsert")
public String i9sInsert() {
return "/backend/i9sInsert";
}
@RequestMapping(path= "/backend/i9sUpdate")
public String i9sUpdate() {
return "/backend/i9sUpdate";
}
@RequestMapping(path= "/backend/type01")
public String type01() {
return "/backend/type01";
}
@RequestMapping(path= "/cms")
public String cms() {
return "/cms";
}
@RequestMapping(path= {"/pages/menu"})
public String menu() {
return "/pages/menu";
}
@RequestMapping(path = {"/contact"})
public String contact() {
return "/pages/contact";
}
@RequestMapping(path = {"/reservation"})
public String reservation() {
return "/pages/reservation";
}
@RequestMapping(path = {"/login"})
public String login() {
return "/pages/login";
}
@RequestMapping(path= "/backend/sales")
public String sales() {
return "/backend/salesfigure";
}
@RequestMapping(path="/backend/table")
public String table() {
return "/backend/table";
}
}
<file_sep>/src/test/java/com/fendihotpot/malapot/dao/TypeTests.java
package com.fendihotpot.malapot.dao;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import javax.persistence.PersistenceContext;
import org.hibernate.Session;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.transaction.annotation.Transactional;
import com.fendihotpot.malapot.domain.I9sBean;
import com.fendihotpot.malapot.domain.SetMealBean;
import com.fendihotpot.malapot.domain.TypeBean;
import com.fendihotpot.malapot.i9sDao.TypeDAO;
import com.fendihotpot.malapot.service.TypeService;
@SpringBootTest
public class TypeTests {
@PersistenceContext
private Session session;
@Autowired
private TypeDAO typeDAO;
@Test
@Transactional
public void testTypeDAO() {
List<Set<?>> selectAll = typeDAO.selectAll();
for(Set<?> set:selectAll) {
System.out.println("set="+set);
}
}
// @Test
// @Transactional
// public void testType() {
// TypeBean typeBeans = session.get(TypeBean.class, 2);
//
// Set<I9sBean> i9sBeans = typeBeans.getI9sBeans();
// for(I9sBean bean:i9sBeans) {
// System.out.println("bean="+bean);
// }
//
// Set<SetMealBean> setMealBeans = typeBeans.getSetMealBeans();
// for(SetMealBean bean: setMealBeans) {
// System.out.println("bean="+bean);
// }
// }
}
<file_sep>/src/main/java/com/fendihotpot/malapot/orderDao/OrderListDAO.java
package com.fendihotpot.malapot.orderDao;
import java.util.List;
import java.util.Map;
import com.fendihotpot.malapot.domain.OrderListBean;
public interface OrderListDAO {
// 新增訂單
public abstract Integer insert(OrderListBean orderList);
// 查詢單筆訂單
public abstract OrderListBean select(Integer orderId);
// 查看用戶歷史訂單
public abstract List<OrderListBean> select(String userId, Integer currentPage, Integer pageSize);
// 查看所有訂單 => 後台管理 一頁10筆
public abstract List<OrderListBean> select(Integer currentPage, Integer pageSize);
// 查看分店所有訂單 => 後台管理 一頁10筆
public abstract List<OrderListBean> selectByBranch(String branch, Integer currentPage, Integer pageSize);
// 查詢訂單總比數
public abstract Integer totalRows();
// 查詢分店訂單總比數
public abstract Integer totalRowsByBranch(String branch);
// 刪除訂單,連同訂單品項一起刪除
public abstract boolean delect(Integer orderId);
// 查詢今年與去年 每月份的業績
public abstract Map<String, List<Map<String, Object>>> selectSales();
// 查詢各分店 今年與去年 每月份的業績
public abstract Map<String, List<Map<String, Object>>> selectSalesByBranch(String branch);
// 查詢各分店 今年的業績
public abstract List<Object[]> salesForBranches();
}
<file_sep>/src/main/java/com/fendihotpot/malapot/orderDao/OrderItemDAOHibernate.java
package com.fendihotpot.malapot.orderDao;
import javax.persistence.PersistenceContext;
import org.hibernate.Session;
import org.springframework.stereotype.Repository;
import com.fendihotpot.malapot.domain.OrderItemBean;
@Repository
public class OrderItemDAOHibernate implements OrderItemDAO{
@PersistenceContext
private Session session;
@Override
public boolean insert(OrderItemBean orderItem) {
if (orderItem!=null && orderItem.getOrderId()!=null) {
Integer pk = (Integer) session.save(orderItem);
if (pk!=null && !pk.equals(0)) {
return true;
}
}
return false;
}
@Override
public boolean update(OrderItemBean orderItem) {
if (orderItem!=null && orderItem.getOrderQty()!=null) {
try {
session.update(orderItem);
return true;
} catch (Exception e) {
e.printStackTrace();
System.out.println(e.toString());
}
}
return false;
}
@Override
public OrderItemBean select(Integer orderItemId) {
if (orderItemId!=null && !orderItemId.equals(0)) {
return session.get(OrderItemBean.class, orderItemId);
}
return null;
}
@Override
public boolean delete(Integer orderItemId) {
if (orderItemId!=null && !orderItemId.equals(0)) {
OrderItemBean orderItem = session.get(OrderItemBean.class, orderItemId);
session.delete(orderItem);
return true;
}
return false;
}
}
<file_sep>/src/main/java/com/fendihotpot/malapot/orderDao/OrderListDAOHibernate.java
package com.fendihotpot.malapot.orderDao;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.persistence.PersistenceContext;
import org.hibernate.Session;
import org.springframework.stereotype.Repository;
import com.fendihotpot.malapot.domain.OrderListBean;
@Repository
public class OrderListDAOHibernate implements OrderListDAO {
@PersistenceContext
private Session session;
@Override
public Integer insert(OrderListBean orderList) {
if (orderList!=null && orderList.getUserMobile()!=null) {
return (Integer) session.save(orderList);
}
return 0;
}
@Override
public OrderListBean select(Integer orderId) {
if (orderId!=null && !orderId.equals(0)) {
return session.get(OrderListBean.class, orderId);
}
return null;
}
@Override
public List<OrderListBean> select(String userId, Integer currentPage, Integer pageSize) {
if (userId!=null && userId.length()>0) {
String hql = "FROM OrderListBean WHERE userId=:userId ORDER BY order_date DESC";
List<OrderListBean> orderList = session.createQuery(hql, OrderListBean.class)
.setParameter("userId", userId)
.setFirstResult((currentPage - 1) * pageSize)
.setMaxResults(pageSize)
.list();
return orderList;
}
return null;
}
@Override
public List<OrderListBean> selectByBranch(String branch, Integer currentPage, Integer pageSize) {
String hql = "FROM OrderListBean WHERE takeoutStore=:branch ORDER BY order_date DESC";
List<OrderListBean> orderList = session.createQuery(hql, OrderListBean.class)
.setParameter("branch", branch)
.setFirstResult((currentPage - 1) * pageSize)
.setMaxResults(pageSize)
.list();
return orderList;
}
@Override
public List<OrderListBean> select(Integer currentPage, Integer pageSize) {
String hql = "FROM OrderListBean ORDER BY order_date DESC";
List<OrderListBean> orderList = session.createQuery(hql, OrderListBean.class)
.setFirstResult((currentPage - 1) * pageSize)
.setMaxResults(pageSize)
.list();
return orderList;
}
@Override
public boolean delect(Integer orderId) {
if (orderId!=null && !orderId.equals(0)) {
OrderListBean orderList = session.get(OrderListBean.class, orderId);
session.delete(orderList);
return true;
}
return false;
}
@Override
public Map<String, List<Map<String, Object>>> selectSales() {
Map<String, List<Map<String, Object>>> sales = new HashMap<>();
String hql = "SELECT DATE_FORMAT( o.orderDate, '%Y-%m'), ROUND( SUM(o.totalAmount), 0) FROM OrderListBean o WHERE DATE_FORMAT( o.orderDate, '%Y' )=:year GROUP BY DATE_FORMAT( o.orderDate, '%Y-%m')";
// 取出年份
SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
Integer thisYear = Integer.parseInt(sdf.format(new Date()));
Integer lastYear = thisYear - 1;
// 今年各月份業績
List<Object[]> salesNow = session.createQuery(hql, Object[].class)
.setParameter("year", thisYear.toString())
.list();
Map<String, Object> salesOfNow = null;
List<Map<String, Object>> salesThisYear = new ArrayList<>();
sales.put("thisYear", salesThisYear);
for (Object[] object : salesNow) {
salesOfNow = new HashMap<>();
salesOfNow.put("month", (String) object[0]);
salesOfNow.put("sales", (Long) object[1]);
salesThisYear.add(salesOfNow);
}
// 去年各月份業績
List<Object[]> salesPast = session.createQuery(hql, Object[].class)
.setParameter("year", lastYear.toString())
.list();
Map<String, Object> salesOfPast = null;
List<Map<String, Object>> salesLastYear = new ArrayList<>();
sales.put("lastYear", salesLastYear);
for (Object[] object : salesPast) {
salesOfPast = new HashMap<>();
salesOfPast.put("month", (String) object[0]);
salesOfPast.put("sales", (Long) object[1]);
salesLastYear.add(salesOfPast);
}
return sales;
}
@Override
public Map<String, List<Map<String, Object>>> selectSalesByBranch(String branch) {
Map<String, List<Map<String, Object>>> sales = new HashMap<>();
String hql = "SELECT DATE_FORMAT( o.orderDate, '%Y-%m'), ROUND( SUM(o.totalAmount), 0) FROM OrderListBean o WHERE DATE_FORMAT( o.orderDate, '%Y' )=:year AND o.takeoutStore=:branch GROUP BY DATE_FORMAT( o.orderDate, '%Y-%m')";
// 取出年份
SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
Integer thisYear = Integer.parseInt(sdf.format(new Date()));
Integer lastYear = thisYear - 1;
// 今年各月份業績
List<Object[]> salesNow = session.createQuery(hql, Object[].class)
.setParameter("year", thisYear.toString())
.setParameter("branch", branch)
.list();
Map<String, Object> salesOfNow = null;
List<Map<String, Object>> salesThisYear = new ArrayList<>();
sales.put("thisYear", salesThisYear);
for (Object[] object : salesNow) {
salesOfNow = new HashMap<>();
salesOfNow.put("month", (String) object[0]);
salesOfNow.put("sales", (Long) object[1]);
salesThisYear.add(salesOfNow);
}
// 去年各月份業績
List<Object[]> salesPast = session.createQuery(hql, Object[].class)
.setParameter("year", lastYear.toString())
.setParameter("branch", branch)
.list();
Map<String, Object> salesOfPast = null;
List<Map<String, Object>> salesLastYear = new ArrayList<>();
sales.put("lastYear", salesLastYear);
for (Object[] object : salesPast) {
salesOfPast = new HashMap<>();
salesOfPast.put("month", (String) object[0]);
salesOfPast.put("sales", (Long) object[1]);
salesLastYear.add(salesOfPast);
}
return sales;
}
@Override
public Integer totalRows() {
String hql = "SELECT COUNT(o.id) FROM OrderListBean AS o";
return session.createQuery(hql, Long.class).uniqueResult().intValue();
}
@Override
public Integer totalRowsByBranch(String branch) {
String hql = "SELECT COUNT(o.id) FROM OrderListBean AS o WHERE o.takeoutStore=:branch";
return session.createQuery(hql, Long.class)
.setParameter("branch", branch)
.uniqueResult()
.intValue();
}
@Override
public List<Object[]> salesForBranches() {
// 今年
SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
Integer thisYear = Integer.parseInt(sdf.format(new Date()));
String hql = "SELECT o.takeoutStore, ROUND( SUM(o.totalAmount), 0) FROM OrderListBean AS o WHERE DATE_FORMAT( o.orderDate, '%Y' )=:year GROUP BY o.takeoutStore";
return session.createQuery(hql, Object[].class)
.setParameter("year", thisYear.toString())
.list();
}
}<file_sep>/src/main/java/com/fendihotpot/malapot/i9sDao/SetMealDAO.java
package com.fendihotpot.malapot.i9sDao;
import java.util.List;
import java.util.Set;
import com.fendihotpot.malapot.domain.I9sBean;
import com.fendihotpot.malapot.domain.SetMealBean;
public interface SetMealDAO {
public abstract SetMealBean select(Integer id);
public abstract List<SetMealBean> selectAll();
public abstract SetMealBean insertMeal(SetMealBean bean);
public abstract Set<I9sBean> insertMealI9s(SetMealBean bean,I9sBean i9sbean);
public abstract SetMealBean updateMeal(SetMealBean bean);
public abstract Set<I9sBean> deleteMealI9s(SetMealBean bean,I9sBean i9sBean);
public abstract boolean deleteMeal(Integer setId);
}
<file_sep>/src/main/resources/static/js/scripts.js
window.addEventListener('DOMContentLoaded', event => {
// Navbar shrink function
var navbarShrink = function () {
const navbarCollapsible = document.body.querySelector('#mainNav');
if (!navbarCollapsible) {
return;
}
if (window.scrollY === 0) {
navbarCollapsible.classList.remove('navbar-shrink')
} else {
navbarCollapsible.classList.add('navbar-shrink')
}
};
// Shrink the navbar
navbarShrink();
// Shrink the navbar when page is scrolled
document.addEventListener('scroll', navbarShrink);
// Activate Bootstrap scrollspy on the main nav element
const mainNav = document.body.querySelector('#mainNav');
if (mainNav) {
new bootstrap.ScrollSpy(document.body, {
target: '#mainNav',
offset: 72,
});
};
});
<file_sep>/src/main/java/com/fendihotpot/malapot/orderDao/OrderItemDAO.java
package com.fendihotpot.malapot.orderDao;
import com.fendihotpot.malapot.domain.OrderItemBean;
public interface OrderItemDAO {
// 新增訂單品項
public abstract boolean insert(OrderItemBean orderItem);
// 修改訂單品項,主要應該是修改數量
public abstract boolean update(OrderItemBean orderItem);
// 查詢訂單詳細品項內容
public abstract OrderItemBean select(Integer orderItemId);
// 刪除訂單品項
public abstract boolean delete(Integer orderItemId);
}
<file_sep>/README.md
結訓專題,素材皆為練習,非營利用途
後端負責
src/main/java/com/fendihotpot/malapot
/config → SecurityConfig
/i9sDao → I9sService
/i9sDao → I9sDAO
/i9sDao → I9sDAOHibernate
/domain → I9sBean
/controller → I9sController
/controller → TypeController
前端負責
src/main/webapp/WEB-INF/views/backend/
i9s.jsp
i9sInsert.jsp
i9sUpdate.jsp
type01.jsp
|
6434766a0597661c62ca1b1e5115131f5a2e363b
|
[
"JavaScript",
"Java",
"Markdown"
] | 18
|
Java
|
shrade1206/mvn-repo
|
18e5aa8b326ee5a082f834d71b25e64a265f3ab7
|
d6341111a96957f800129f8934b95cf14ea152e2
|
refs/heads/main
|
<repo_name>jvillacinda11/googlebookssearch<file_sep>/models/Books.js
const { model, Schema } = require('mongoose')
const Books = new Schema({
title: String,
authors: [{
type: String
}],
description: String,
image: String,
link: String
})
module.exports = model('Books', Books)<file_sep>/client/src/pages/Search/index.js
import { useState, useEffect} from 'react'
import Render from '../../components/Render'
import axios from 'axios'
import { Container, Row } from "reactstrap"
// google books api key <KEY>
export default function Search() {
const [booksState, setBooksState] = useState({
title: '',
books: []
})
const handleInputChange = ({ target }) => {
setBooksState({ ...booksState, [target.name]: target.value })
}
const handleSearchBooks = event => {
event.preventDefault()
//change this to the books api
axios.get(`https://www.googleapis.com/books/v1/volumes?q=${booksState.title}&key=<KEY>`)
.then(({ data: { items: books } }) => {
console.log(books)
setBooksState({ ...booksState, books, title: '' })
})
.catch(err => console.error(err))
}
const view = () => {
alert('hi')
}
return(
<>
<h1>Search for books here</h1>
<form>
<p>
<label htmlFor='title'>title</label>
<input
type='text'
name='title'
value={booksState.title}
onChange={handleInputChange}
/>
</p>
<button onClick={handleSearchBooks}>Search Books</button>
</form>
<Container>
<Row>
{
booksState.books.length
? booksState.books.map((book, i) => <Render key={i} title={book.volumeInfo.title} authors={book.volumeInfo.authors} description={book.volumeInfo.description} image={book.volumeInfo.imageLinks.thumbnail} link={book.volumeInfo.infoLink}/>)
:null
}
</Row>
</Container>
</>
)
}<file_sep>/client/src/App.js
import React from 'react'
import {
BrowserRouter as Router,
Switch,
Route
} from 'react-router-dom'
import Search from './pages/Search'
import Saved from './pages/Saved'
import AppBar from './components/AppBar'
import 'bootstrap/dist/css/bootstrap.min.css';
function App() {
return (
<>
{/* <h1>App Page</h1> */}
<Router>
<AppBar />
{/* <div>
<Link to='/'>home</Link>
<Link to='/login'>login</Link>
<Link to='/profile'>profile</Link>
</div> */}
<Switch>
<Route exact path='/'>
<Saved />
</Route>
<Route path='/search'>
<Search />
</Route>
</Switch>
</Router>
</>
);
}
export default App;
<file_sep>/client/src/pages/Saved/index.js
import {useState, useEffect } from 'react'
import { Container, Row } from "reactstrap"
import RenderSaved from '../../components/RenderSaved.js/index.js'
import Post from '../../utils/Posts'
export default function Saved() {
const [postState, setPostState] = useState({
posts: []
})
useEffect(() => {
Post.getAll({})
.then(({ data: posts }) => {
setPostState({...postState, posts })
})
.catch(err => console.log(err))
}, [])
const view = () => {
console.log('pong')
}
const remove = () =>{
console.log('pong')
}
return(
<>
<h1>View your saved books here</h1>
<Container>
<Row>
{
postState.posts.length
? postState.posts.map((book, i) => <RenderSaved key={i} title={book.title} authors={book.authors} description={book.description} image={book.image} link= {book.link} id = {book._id} />)
: null
}
</Row>
</Container>
</>
)
}
<file_sep>/client/src/utils/Posts/Posts.js
import axios from 'axios'
// import { delete } from '../../../../routes/booksRoutes'
const Post ={
getAll: () => axios.get('/api/books'),
save: book => axios.post('/api/books', book)
}
export default Post<file_sep>/client/src/components/AppBar/AppBar.js
import {useState } from 'react'
import { Navbar, NavbarBrand, NavItem, NavLink, Nav, NavbarToggler, Collapse } from 'reactstrap'
import {Link} from 'react-router-dom'
const AppBar = () => {
const [isOpen, setIsOpen] = useState(false)
const toggle = () => setIsOpen(!isOpen)
return (
<Navbar color='light' light expand='md'>
{/* <img id="logo" src={Logo} alt="King Pepe" /> */}
<NavbarBrand>Google Books</NavbarBrand>
<NavbarToggler onClick={toggle} />
<Collapse isOpen={isOpen} navbar>
<Nav navbar>
<NavItem>
<Link to='/'>
<NavLink>Saved Books</NavLink>
</Link>
</NavItem>
<NavItem>
<Link to='/search'>
<NavLink>Search</NavLink>
</Link>
</NavItem>
</Nav>
</Collapse>
</Navbar>
)
}
export default AppBar<file_sep>/client/src/components/RenderSaved.js/RenderSaved.js
import React from 'react';
import {
Card, CardImg, CardText, CardBody,
CardTitle, CardSubtitle, Button,
Col
} from 'reactstrap';
import axios from 'axios';
const RenderSaved = ({title, authors, description, image, link, id}) => {
const view =()=> {
window.open(`${link}`, "_blank")
}
const remove = ()=> {
axios.delete(`/api/books/${id}`)
.then(() =>{
console.log('ok')
window.location.reload()
})
.catch(err => console.log(err))
}
return(
<>
<Col>
<Card>
<CardImg top width="100%" src={image} alt="Card image cap" />
<CardBody>
<CardTitle tag="h5">{title}</CardTitle>
<CardSubtitle tag="h6" className="mb-2 text-muted">Authors: {authors ? authors.map(author => `${author}, `) : 'Unknown'}</CardSubtitle>
<CardText>{description}</CardText>
<CardSubtitle>
<Button color='light' light expand='md' onClick={view} >
View
</Button>
<Button color='light' light expand='md' onClick={remove}>
Remove
</Button>
</CardSubtitle>
</CardBody>
</Card>
</Col>
</>
)
}
export default RenderSaved<file_sep>/client/src/utils/Posts/index.js
export {default} from './Posts.js'
|
d20c35a391cf86cab31caa3dd69cdc4c070bdc86
|
[
"JavaScript"
] | 8
|
JavaScript
|
jvillacinda11/googlebookssearch
|
bdc5533cf753d5c2d03c2c84262d1034e709cd56
|
6149e33dc41ef220c37f2dd352142c267bb8859b
|
refs/heads/master
|
<repo_name>twiggg/helpers<file_sep>/fornums/slices.go
package fornums
func RemoveFromSlice(slice *[]int32, i int32) bool {
n := len(*slice)
if !removableFromSlice(*slice, i) {
return false
}
s := *slice
s = append(s[:i], s[i+1:]...) //
*slice = s
if len(*slice) == n-1 {
return true
} else {
return false
}
}
func removableFromSlice(slice []int32, i int32) bool {
if i < 0 || i > int32(len(slice)-1) {
return false
}
return true
}
func FindInInt32Slice(slice []int32, toFind int32) (int, bool) {
for k, v := range slice {
if v == toFind {
return k, true
}
}
return -1, false
}
<file_sep>/timer.go
package main
import (
"fmt"
"time"
)
func main() {
fmt.Println("started the program")
defer fmt.Println("ended the program")
tim := NewTimer(250, 3000)
tim.Tic()
}
type timer struct {
tic uint
timeout uint
t0 uint
counts uint
}
func NewTimer(tic, timeout uint) *timer {
deftic := uint(500)
defboom := uint(3000)
return &timer{tic: max(tic, deftic), timeout: max(timeout, defboom)}
}
func max(a, b uint) uint {
if a >= b {
return a
}
return b
}
func (t *timer) Tic() {
boom := time.After(time.Duration(t.timeout) * time.Millisecond)
tick := time.Tick(time.Duration(t.tic) * time.Millisecond)
for {
select {
case <-boom:
fmt.Println("BOOM!")
fmt.Printf("%s", t.TimeString())
return
case <-tick:
fmt.Println("tick.")
t.counts++
//default:
//fmt.Println(" .")
//time.Sleep(50 * time.Millisecond)
}
}
}
func (t *timer) Time() float64{
return float64((t.counts*t.tic)/uint(1000))
}
func (t *timer) TimeString() string{
return fmt.Sprintf("%.1fs passed by\n",float64((t.counts*t.tic)/uint(1000)))
}
<file_sep>/helpers.go
package helpers
/*func (f *UserFields) remove(i int) {
if !f.removable(i) {
return
}
s := *f
s = append(s[:i], s[i+1:]...) //
*f = s
}
func (f UserFields) removable(i int) bool {
if i < 0 || i > (len(f)-1) {
return false
}
return true
}*/
func RemovedFromStringSlice(slice *[]string, i int) bool {
n := len(*slice)
if !removableFromStringSlice(*slice, i) {
return false
}
s := *slice
s = append(s[:i], s[i+1:]...) //
*slice = s
if len(*slice) == n-1 {
return true
} else {
return false
}
}
func RemovableFromStringSlice(slice []string, i int) bool {
if i < 0 || i > (len(slice)-1) {
return false
}
return true
}
<file_sep>/forstrings/forstrings.go
package forstrings
import (
"errors"
"fmt"
"html"
"math/rand"
"strconv"
"strings"
"time"
)
/*func (f *UserFields) remove(i int) {
if !f.removable(i) {
return
}
s := *f
s = append(s[:i], s[i+1:]...) //
*f = s
}
func (f UserFields) removable(i int) bool {
if i < 0 || i > (len(f)-1) {
return false
}
return true
}*/
func RemoveFromSlice(slice *[]string, i int) bool {
n := len(*slice)
if !RemovableFromSlice(*slice, i) {
return false
}
s := *slice
s = append(s[:i], s[i+1:]...) //
*slice = s
if len(*slice) == n-1 {
return true
} else {
return false
}
}
func RemovableFromSlice(slice []string, i int) bool {
if i < 0 || i > (len(slice)-1) {
return false
}
return true
}
func FindInSlice(slice []string, toFind string) (int, bool) {
for k, v := range slice {
if strings.ToLower(html.EscapeString(v)) == strings.ToLower(html.EscapeString(toFind)) {
return k, true
}
}
return -1, false
}
func RandomString(strlen int) string {
rand.Seed(time.Now().UTC().UnixNano())
const chars = "abcdefghijklmnopqrstuvwxyz0123456789"
result := make([]byte, strlen)
for i := 0; i < strlen; i++ {
result[i] = chars[rand.Intn(len(chars))]
}
return string(result)
}
func RandomIntString(strlen int) string {
rand.Seed(time.Now().UTC().UnixNano())
const chars = "0123456789"
result := make([]byte, strlen)
for i := 0; i < strlen; i++ {
result[i] = chars[rand.Intn(len(chars))]
}
return string(result)
}
func StringsToInt32s(list []string) ([]int32, []error) {
res := []int32{}
errs := []error{}
for k, v := range list {
v = strings.ToLower(html.EscapeString(strings.TrimSpace(v)))
r, err := strconv.ParseInt(v, 10, 32)
if err != nil {
if len(errs) == 0 {
msg0 := fmt.Sprintf("emitter: forstrings.StringsToInt32s")
errs = append(errs, errors.New(msg0))
}
msg := fmt.Sprintf("index: %d, error: %s", k, err.Error())
errs = append(errs, errors.New(msg))
} else {
res = append(res, int32(r))
}
}
return res, errs
}
func Concatenate(list []string) string {
res := ""
//l := len(list)
for k, v := range list {
if k != 0 {
res = fmt.Sprintf("%s, %s", res, v)
} else {
res = fmt.Sprintf("%s", v)
}
}
return res
}
func ConcatenateErrs(list []error) string {
res := ""
//l := len(list)
for k, v := range list {
if k != 0 {
res = fmt.Sprintf("%s, %s", res, v.Error())
} else {
res = fmt.Sprintf("%s", v.Error())
}
}
return res
}
<file_sep>/dates/date.go
package main
import (
"errors"
"fmt"
"strconv"
"strings"
"time"
)
func main() {
d,err:=ExtractFromString("16/30/03", "YY/DD/MM")
fmt.Println(*d,err)
fmt.Println(d.GenTime())
}
//custom types declaration
type date struct {
day int
month int
year int
}
type dateString map[string]string
type day string
type month string
type year string
var months =map[int]string{1:"Jan",2:"Feb",3:"Mar",4:"Apr",5:"May",6:"Jun",7:"Jul",8:"Aug",9:"Sep",10:"Oct",11:"Nov",12:"Dec"}
//methods
func (d date) GenTime() time.Time{
const shortForm = "02-Jan-2006"
phrase:=fmt.Sprintf("%d-%s-%d",d.day,months[d.month],d.year)
fmt.Println(phrase)
t, _ := time.Parse(shortForm, phrase)
//t, _ := time.Parse(shortForm, "13-Mar-2016")
//fmt.Println(t)
return t
}
func (ds dateString) isValid() (*date, error) {
d, dok := isDayOk(ds["day"])
m, mok := isMonthOk(ds["month"])
y, yok := isYearOk(ds["year"])
if dok == nil && mok == nil && yok == nil {
return &date{day: d, month: m, year: y}, nil
}
msg := ""
errs:=[]error{dok, mok, yok}
for i, m := range errs {
if m != nil {
if i > 0 {
msg = fmt.Sprintf("%s%s", msg, ",")
}
msg = fmt.Sprintf("%s%s", msg, m)
}
}
return nil, errors.New(msg)
}
//dispatch components of the date in the date map
func (dm dateString) dispatch(dpos, mpos, ypos int, list []string) error {
if dpos >= 0 && dpos < len(list) && mpos >= 0 && mpos < len(list) && ypos >= 0 && ypos < len(list) && dpos != mpos && dpos != ypos && mpos != ypos {
dm["day"] = list[dpos]
dm["month"] = list[mpos]
dm["year"] = list[ypos]
return nil
}
return errors.New("please make sure to provide positions with 0<indices<len(list) that are not overlapping.")
}
//extract the components of a date from a string
func ExtractFromString(date string, format string) (*date, error) {
//dmap:=make(map[string]int,3)
parts := strings.Split(date, "/")
dm := dateString{}
if len(parts) != 3 {
return nil, errors.New("a valid date is made of 3 components:day,month,year")
}
switch strings.ToUpper(format) {
case "DD/MM/YY":
err := dm.dispatch(0, 1, 2, parts)
if err != nil {
return nil, err
}
return dm.isValid()
case "JJ/MM/AA":
err := dm.dispatch(0, 1, 2, parts)
if err != nil {
return nil, err
}
return dm.isValid()
case "DD/MM/YYYY" :
err := dm.dispatch(0, 1, 2, parts)
if err != nil {
return nil, err
}
return dm.isValid()
case "JJ/MM/AAAA":
err := dm.dispatch(0, 1, 2, parts)
if err != nil {
return nil, err
}
return dm.isValid()
case "MM/DD/YY" :
err := dm.dispatch(1, 0, 2, parts)
if err != nil {
return nil, err
}
return dm.isValid()
case "MM/JJ/AA":
err := dm.dispatch(1, 0, 2, parts)
if err != nil {
return nil, err
}
return dm.isValid()
case "MM/DD/YYYY" :
err := dm.dispatch(1, 0, 2, parts)
if err != nil {
return nil, err
}
return dm.isValid()
case "MM/JJ/AAAA":
err := dm.dispatch(1, 0, 2, parts)
if err != nil {
return nil, err
}
return dm.isValid()
case "YY/DD/MM" :
err := dm.dispatch(1, 2, 0, parts)
if err != nil {
return nil, err
}
return dm.isValid()
case "AA/JJ/MM":
err := dm.dispatch(1, 2, 0, parts)
if err != nil {
return nil, err
}
return dm.isValid()
case "YYYY/DD/MM" :
err := dm.dispatch(1, 2, 0, parts)
if err != nil {
return nil, err
}
return dm.isValid()
case "AAAA/JJ/MM":
err := dm.dispatch(1, 2, 0, parts)
if err != nil {
return nil, err
}
return dm.isValid()
case "YY/MM/DD" :
err := dm.dispatch(2, 1, 0, parts)
if err != nil {
return nil, err
}
return dm.isValid()
case "AA/MM/JJ":
err := dm.dispatch(2, 1, 0, parts)
if err != nil {
return nil, err
}
return dm.isValid()
case "YYYY/MM/DD" :
err := dm.dispatch(2, 1, 0, parts)
if err != nil {
return nil, err
}
return dm.isValid()
case "AAAA/MM/JJ":
err := dm.dispatch(2, 1, 0, parts)
if err != nil {
return nil, err
}
return dm.isValid()
default:
return nil, errors.New("a valid date is made of 3 components:day,month,year")
}
}
//components validators
func isDayOk(d string) (int, error) {
val, err := strconv.Atoi(d)
if err != nil {
return -1, errors.New("could not parse day string in a day integer")
}
if val < 1 || val > 31 {
return -1, errors.New("please provide a valid 1<day<31")
}
return val, nil
}
func isMonthOk(m string) (int, error) {
val, err := strconv.Atoi(m)
if err != nil {
return -1, errors.New("could not parse month string in a month integer")
}
if val < 1 || val > 12 {
return -1, errors.New("please provide a valid 1<month<12")
}
return val, nil
}
func isYearOk(y string) (int, error) {
val, err := strconv.Atoi(y)
if err != nil {
return -1, errors.New("could not parse year string in a year integer")
}
switch len(y) {
case 2:
if val < 1 || val > (time.Now().Year()%100)+100 {
return -1, errors.New("please provide a valid 1<year<now+100 in YY format")
}
//fmt.Println("now:",time.Now().Year()%2000,"val:",val)
return val+2000, nil
case 4:
if val < 1 || val > time.Now().Year()+100 {
return -1, errors.New("please provide a valid 1<year<now+100 in YYYY format")
}
return val, nil
default:
return -1, errors.New("please provide a year in YY or YYYY format")
}
}
|
2f7ecc88b792515e890acef382fcd4c32cb06640
|
[
"Go"
] | 5
|
Go
|
twiggg/helpers
|
d3ae92e072efd4903f60a43cb16aa02f9f36fbb2
|
15d0e74fb1bafc95b46809d340654ced77df4fdc
|
refs/heads/master
|
<repo_name>ScrapThemAll/scrapjob<file_sep>/src/bots.test.js
import test from 'ava';
import bots from './bots';
test('without name', t => {
try {
bots();
} catch (err) {
t.is(err.name, 'Error');
t.is(err.message, 'You must provide a name');
}
});
test('bot not a string', t => {
try {
bots([]);
} catch (err) {
t.is(err.name, 'Error');
t.is(err.message, 'Bot must be a string');
}
});
test('bot does not exit', t => {
try {
bots('<NAME> and <NAME>');
} catch (err) {
t.is(err.message, 'Bot does not exist');
}
});
test('bot canalplus', async t => {
const botCanalplus = bots('canalplus');
t.true(typeof botCanalplus.scrap === 'function');
});
<file_sep>/package.json
{
"name": "scrapjob",
"version": "0.0.0",
"description": "Get job offers from your favorite company",
"main": "dist/bots.js",
"scripts": {
"commit": "git-cz",
"lint": "xo",
"report-coverage": "cat ./coverage/lcov.info | codecov",
"test": "nyc ava --verbose",
"prebuild": "rimraf dist",
"build": "babel --copy-files --out-dir dist --ignore *.test.js src",
"validate": "npm-run-all --parallel lint test build",
"release": "semantic-release pre && npm publish && semantic-release post"
},
"repository": {
"type": "git",
"url": "https://github.com/ScrapThemAll/scrapjob-bot.git"
},
"keywords": [
"bots",
"jobs",
"job board"
],
"files": [
"dist"
],
"author": "<NAME> <<EMAIL>>",
"license": "MIT",
"bugs": {
"url": "https://github.com/ScrapThemAll/scrapjob-bot/issues"
},
"homepage": "https://github.com/ScrapThemAll/scrapjob#readme",
"devDependencies": {
"ava": "0.16.0",
"babel-cli": "6.14.0",
"babel-plugin-transform-async-to-generator": "6.8.0",
"babel-polyfill": "6.13.0",
"babel-preset-es2015": "6.14.0",
"babel-register": "6.14.0",
"codecov": "1.0.1",
"commitizen": "2.8.6",
"cz-conventional-changelog": "1.2.0",
"ghooks": "1.3.2",
"npm-run-all": "3.1.0",
"nyc": "8.1.0",
"rimraf": "2.5.4",
"validate-commit-msg": "2.8.0",
"xo": "0.16.0",
"semantic-release": "^4.3.5"
},
"nyc": {
"reporter": [
"text",
"lcov"
],
"include": [
"src"
]
},
"babel": {
"presets": [
"es2015"
],
"plugins": [
"transform-async-to-generator"
]
},
"ava": {
"require": [
"./test/helpers/setup.js"
]
},
"config": {
"commitizen": {
"path": "cz-conventional-changelog"
},
"ghooks": {
"pre-commit": "npm run validate",
"commit-msg": "validate-commit-msg"
}
},
"dependencies": {
"cheerio": "0.22.0",
"got": "6.3.0"
}
}
<file_sep>/src/bots.js
function safeCheck(botName) {
if (!botName) {
throw new Error('You must provide a name');
}
if (typeof botName !== 'string') {
throw new Error('Bot must be a string');
}
}
function main(name) {
safeCheck(name);
try {
return require(`./sites/${name}/${name}`);
} catch (err) {
throw new Error('Bot does not exist');
}
}
export default main;
module.exports = main;
<file_sep>/README.md
# scrapjob
[](https://travis-ci.org/ScrapThemAll/scrapjob)
[](https://codecov.io/github/ScrapThemAll/scrapjob)
[](http://opensource.org/licenses/MIT)
## Install
```
$ npm install --save scrapjob
```
## Usage
```js
const bot = require('scrapjob');
const canalplus = bot('canalplus');
canalplus.scrap()
.then(jobs => {
console.log(jobs);
/*[
{
date: '08/09/2016',
poste: 'software engineer',
duree: '',
contrat: 'CDI',
context: 'blabla',
mission: '',
niveau: 'Bac+3',
experience: '1 an'
},
...
]*/
});
```
## API
### .scrap([options]): *Object[]*
Get jobs.
#### options
Type: `object`
##### nbPage
Type: `number`
Page number that will be scrap
## Available companies
Companies that are available in scrapjob:
- `canalplus`
|
099a23d168608949ba3faa534bf23d82477940ce
|
[
"JavaScript",
"JSON",
"Markdown"
] | 4
|
JavaScript
|
ScrapThemAll/scrapjob
|
f2f802ebb7aa6999d79cbb74f5ab2a4a2655ca2f
|
abcff53334b8207848a72b48ad1303f885218781
|
refs/heads/master
|
<file_sep>package course_management_system;
import java.util.Scanner;
public class login{
/*private static String CourseID;
private static int point = 0;*/
private double courseQTY;
private static final Course[] courseList = new Course[3];
private static final Scanner sc = new Scanner(System.in);
public static void main(String[] args){
String userSelection;
Course courseList[] = new Course[3];
courseList[0] = new Course("C100","web programming","Intro to programming","Design web pages","empty",100);
courseList[1] = new Course("C101","Database concept","DCNC","Learning SQL and ER diagram","L101",0);
courseList[2] = new Course("C102","Programming 1","Intro to programming","Java", "empty",0);
do{
System.out.println("Course Management System Menu");
System.out.println("-------------------");
System.out.println();
System.out.printf("%-28s%s\n", "Student", "A");
System.out.printf("%-28s%s\n", "Lecturer", "B");
System.out.printf("%-28s%s\n", "Admin", "C");
System.out.println();
System.out.print("Enter selection: ");
userSelection = sc.nextLine().toUpperCase();
System.out.println();
// process user's selection
switch (userSelection)
{
case "A":
student();
break;
case "B":
lecturer();
break;
case "C":
admin();
break;
case "X":
System.out.println("Exiting the program...");
break;
default:
System.out.println("Error - invalid selection!");
}
} while (!userSelection.equals("X"));
}
private static void student(){
int i;
String userName,passWord,coursename,prereqs,description,chooseCoursename;
System.out.println("Please enter your userName: ");
userName = sc.nextLine();
System.out.println("Please enter your passWord: ");
passWord = sc.nextLine();
if(userName.equals("student")&& passWord.equals("student123")){
//------------extend program coordinator
System.out.println("Welcome to student page\n");
System.out.println("\n");
}
else{
System.out.println("Your account is invaild, please re-enter again");
}
for(int i = 0; i < courseList.length; i++){
coursename = courseList[i].getCoursename();
prereqs = courseList[i].getPrereqs();
description = courseList[i].getDescription();
System.out.println("No."+ i +" coursename:" + " " + coursename
+ ", " + "prereqs:" + " " + prereqs
+ ", " + "description:" + " " + description);
}
//Enrollment
System.out.println("Which is your favor courses? Please select course: ");
chooseCoursename = sc.nextLine();
if(courseList[i].getCoursename().indexOf(chooseCoursename) >= 0){
System.out.println(courseList[i].getCourseID() + " - " + courseList[i].getCoursename());
}
if(){
}
System.out.println("\n");
}
private static void lecturer(){
String userName;
String passWord;
System.out.println("Please enter your userName: ");
userName = sc.nextLine();
System.out.println("Please enter your passWord: ");
passWord = sc.nextLine();
if(userName.equals("lecturer")&& passWord.equals("<PASSWORD>")){
//------------extend program coordinator
System.out.println("Welcome to lecturer page\n");
}
else{
System.out.println("Your account is invaild, please re-enter again");
}
}
private static void admin(){
String userName;
String passWord;
System.out.println("Please enter your userName: ");
userName = sc.nextLine();
System.out.println("Please enter your passWord: ");
passWord = sc.nextLine();
if(userName.equals("admin")&& passWord.equals("<PASSWORD>")){
//------------extend program coordinator
System.out.println("Welcome to admin page\n");
}
else{
System.out.println("Your account is invaild, please re-enter again");
}
}
/*private static int search(Course courseList[])
{
for(int i=0;i<courseList.length;i++)
{
if(CourseID.equals(courseList[i].getCourseID()))
{
return i;
}
}
return -1;
}*/
}
|
0120a11ef8dd45025f36fe18281ed7270b626d7d
|
[
"Java"
] | 1
|
Java
|
petergaobro/course_management__system
|
5f771c9e0f6c131866cc1a5ef2789c04092c78da
|
bf6c87e1f37a9efd0374a188219f2afe2f71b2b7
|
refs/heads/master
|
<repo_name>priyaaank/T<file_sep>/app/assets/javascripts/init.js
App = new Backbone.Marionette.Application();
App.Views = {};
App.Views.Layouts = {};
App.Models = {};
App.Collections = {};
App.Routers = {};
App.Helpers = {};
App.layouts = {};
App.addRegions({
content: '#content',
header: '#header',
footer: '#footer'
});
App.bind("initialize:after", function() {
App.header.show(App.layouts.header);
App.footer.show(App.layouts.footer);
App.content.show(App.layouts.invitation);
});
App.vent.on("authentication:login", function() {
App.content.show(App.layouts.home);
});
<file_sep>/spec/models/invite_spec.rb
require 'spec_helper'
describe Invite do
context "email" do
it { should respond_to :email }
it { should validate_format_of(:email).with("<EMAIL>") }
it { should validate_format_of(:email).with("<EMAIL>") }
it { should validate_format_of(:email).not_with("john<EMAIL>").with_message("email address is not valid") }
it { should validate_format_of(:email).not_with("<EMAIL>").with_message("email address is not valid") }
it { should validate_format_of(:email).not_with("").with_message("email address is not valid") }
it { should validate_format_of(:email).not_with(nil) }
end
end
<file_sep>/spec/fabricators/review_fabricator.rb
Fabricator(:review) do
text "Eiffel tower is one of the most breathtaking sites anywhere in the world"
rating_value 5
review_date { DateTime.now }
reviewer { Fabricate(:user) }
place
end
<file_sep>/spec/fabricators/stat_group_fabricator.rb
Fabricator(:likable, :from => :stat_group) do
likes 2000
dislikes 1
end
<file_sep>/spec/controllers/invite_controller_spec.rb
require 'spec_helper'
describe InviteController do
context "GET /invite/new" do
context "for a logged out user" do
it "should render the beta invitation page" do
get :new
response.should render_template("invite/new")
end
it "should return a success response" do
get :new
response.status.should eq 200
end
end
end
context "POST /invite" do
context "for a logged out user" do
let(:params_to_send) { params_to_send = {:invite => { :email => "<EMAIL>" }} }
it "returns a success reponse" do
post :create, params_to_send
response.status.should eq 200
end
it "render nothing" do
post :create, params_to_send
response.body.should be_blank
end
it "create an invite" do
post :create, params_to_send
response.status.should eq 200
Invite.where(:email => "<EMAIL>").first.should be_present
end
end
end
end
<file_sep>/spec/controllers/home_controller_spec.rb
require 'spec_helper'
describe HomeController do
context "GET to index" do
context "for a logged out user" do
it "should force a to authenticate" do
get :index
response.should redirect_to("http://test.host/users/sign_in")
end
end
context "for a logged in user" do
before do
user = User.create!(:email => "<EMAIL>", :password => "<PASSWORD>", :confirmed_at => Date.today)
sign_in user
end
it "should render index page" do
get :index
response.should render_template('home/index')
end
it "should be success" do
get :index
response.should be_success
end
it "should not redirect to sign in page" do
get :index
response.should_not redirect_to("http://test.host/users/sign_in")
end
end
end
end
<file_sep>/app/assets/javascripts/views/layouts/footer.js
App.Views.Layouts.Footer = Backbone.Marionette.Layout.extend({
template: 'layouts/footer',
regions: {},
views: {},
onShow: function() {}
});
App.addInitializer(function() {
App.layouts.footer = new App.Views.Layouts.Footer();
});
<file_sep>/app/models/category.rb
class Category
include Mongoid::Document
field :name, :type => String
field :identifier, :type => String
belongs_to :place
before_save :downcase_underscorize_and_assign_identifier
private
def downcase_underscorize_and_assign_identifier
self.identifier = (identifier||name).gsub(/\s+/,'').underscore
end
end
<file_sep>/app/assets/javascripts/views/loginAndRegistration/login.js
App.Views.LoginAndRegistration = App.Views.LoginAndRegistration || {};
App.Views.LoginAndRegistration.Login = Backbone.Marionette.ItemView.extend({
template: 'registrationAndLogin/login',
events: {
'submit form' : 'login'
},
initialize: function() {
this.model = new App.Models.UserSession();
this.modelBinder = new Backbone.ModelBinder();
},
onRender: function() {
this.modelBinder.bind(this.model, this.el);
},
login: function(e) {
e.preventDefault();
var el = $(this.el);
this.model.save(this.model.attributes, {
success: function(userSession, response) {
console.log(userSession);
},
error: function(userSession, response) {
var serverResponse = $.parseJSON(response.responseText);
console.log(serverResponse);
}
});
}
});
<file_sep>/app/models/photo.rb
class Photo
include Mongoid::Document
field :url, :type => String
field :caption, :type => String
field :type, :type => String
embedded_in :place
end
<file_sep>/app/assets/javascripts/views/layouts/home.js
App.Views.Layouts.Home = Backbone.Marionette.Layout.extend({
template: 'layouts/home',
regions : {
loginWidget: '#login-widget'
},
views:{},
onShow: function() {
this.views.login = App.Views.LoginAndRegistration.Login;
this.loginWidget.show(new this.views.login);
}
});
App.addInitializer(function() {
App.layouts.home = new App.Views.Layouts.Home();
});
<file_sep>/app/models/review.rb
class Review
include Mongoid::Document
field :text, :type => String
field :rating_value, :type => Integer
field :review_date, :type => DateTime
belongs_to :reviewer, :class_name => "User"
belongs_to :place
end
<file_sep>/spec/fabricators/contact_info_fabricator.rb
Fabricator(:eiffel_tower_address, :from => :contact_info) do
address_line_1 "Eiffel Tower"
address_line_2 "Avenue Gustave Eiffel"
city "Paris"
country "France"
zipcode "75007"
contactable(:fabricator => :place)
end
Fabricator(:hilton_hotel_address, :from => :contact_info) do
address_line_1 "London Hilton on Park Lane Hotel"
address_line_2 "22 Park Lane"
city "London"
country "United Kingdom"
zipcode "W1K1BE"
contactable(:fabricator => :place)
end
Fabricator(:france_address, :from => :contact_info) do
address_line_1 "France"
address_line_2 "Europe"
city "France"
country "France"
zipcode "NA"
contactable(:fabricator => :place)
end
<file_sep>/spec/api/places/apiv1_spec.rb
require 'spec_helper'
module Places
describe APIV1 do
context "GET /api/place/:id" do
let(:non_existent_place_id) { Moped::BSON::ObjectId.new }
before do
@eiffel_tower = Fabricate(:place)
end
it "should return a 200 status code in reponse" do
get "/api/place/#{@eiffel_tower.id}"
response.status.should eq 200
end
it "should return the name of the place in response body" do
get "/api/place/#{@eiffel_tower.id}"
json_response = response.body
json_response.should be_json_eql({"name" => @eiffel_tower.name, "id" => @eiffel_tower.id}.to_json).
excluding("categories", "photos","location","stats", "contact_info")
end
it "should return a 404 status code in response when place is not found" do
get "/api/place/#{non_existent_place_id}"
response.status.should eq 404
end
it "should return an error json when place is not found" do
get "/api/place/#{non_existent_place_id}"
response.body.should eq({:error => {:message => "We did not find what you were looking for", :code => 404}}.to_json)
end
context "for place with photos" do
it "should include photos and their details for the place in response" do
get "/api/place/#{@eiffel_tower.id}"
json_response = response.body
json_response.should have_json_size(1).at_path("photos")
json_response.should have_json_type(String).at_path("photos/0/id")
json_response.should have_json_type(String).at_path("photos/0/url")
json_response.should have_json_type(String).at_path("photos/0/caption")
json_response.should have_json_type(String).at_path("photos/0/type")
end
end
context "for place with location" do
it "should include location details for the place in response" do
get "/api/place/#{@eiffel_tower.id}"
json_response = response.body
json_response.should have_json_type(Float).at_path("location/latitude")
json_response.should have_json_type(Float).at_path("location/longitude")
end
end
context "for place with stat group" do
it "should include the stats from stat group details of the place in response" do
get "/api/place/#{@eiffel_tower.id}"
json_response = response.body
json_response.should have_json_type(Integer).at_path("stats/likes")
json_response.should have_json_type(Integer).at_path("stats/dislikes")
end
end
context "for place with contact info" do
it "should include the contact info details in the response" do
get "/api/place/#{@eiffel_tower.id}"
json_response = response.body
json_response.should have_json_type(String).at_path("contact_info/address_line_1")
json_response.should have_json_type(String).at_path("contact_info/address_line_2")
json_response.should have_json_type(NilClass).at_path("contact_info/address_line_3")
json_response.should have_json_type(String).at_path("contact_info/city")
json_response.should have_json_type(String).at_path("contact_info/country")
json_response.should have_json_type(String).at_path("contact_info/zipcode")
json_response.should have_json_type(NilClass).at_path("contact_info/state")
end
end
context "for place with associated categories" do
it "should include the categories for the place in response" do
get "/api/place/#{@eiffel_tower.id}"
json_response = response.body
json_response.should have_json_size(1).at_path("categories/")
json_response.should have_json_type(String).at_path("categories/0/name")
end
end
end
end
end
<file_sep>/app/api/users/user_response_entity.rb
module Users
class UserResponseEntity < Grape::Entity
expose :first_name
expose :last_name
expose :email
end
end
<file_sep>/db/seeds.rb
#clear all past data
Mongoid.purge!
#Create categories
["Monument", "Hotel", "Nightlife", "Park", "Coffee Shop", "Restaurant"].each do |category|
Category.create!(:name => category)
end
#create Eiffel Tower as a place
monument_category = Category.where(:name => "Monument").first
eiffel_tower = Place.create!(:name => "Eiffel Tower", :alternate_names => ['La Tour Eiffel','a dame de fer', 'the iron lady'],
:categories => [monument_category], :location => Location.new(:latitude => 48.858165, :longitude => 2.295354),
:stat_group => StatGroup.new(:likes => 200, :dislikes => 100)
)
photo_of_eiffel_tower = Photo.new(:url => "http://example.com/photo/1",
:caption => "Eiffel Tower in its glory",
:type => "jpeg"
)
eiffel_tower.photos << photo_of_eiffel_tower
contact_info_for_eiffel_tower = ContactInfo.new(:address_line_1 => "Eiffel Tower",
:address_line_2 => "Avenue Gustave Eiffel",
:city => "Paris",
:country => "France",
:zipcode => "75007",
:contactable => eiffel_tower
)
eiffel_tower.contact_info = contact_info_for_eiffel_tower
eiffel_tower.save!
#create Hilton Hotel Prime as a hotel
monument_category = Category.where(:name => "Hotel").first
hilton_prime = Place.create!(:name => "<NAME>", :alternate_names => ["<NAME>"],
:categories => [monument_category], :location => Location.new(:latitude => 51.505612, :longitude => -0.149633),
:stat_group => StatGroup.new(:likes => 10, :dislikes => 200)
)
photo_of_hilton_prime = Photo.new(:url => "http://example.com/photo/200",
:caption => "Lobby of Hilton Prime",
:type => "png"
)
hilton_prime.photos << photo_of_hilton_prime
contact_info_for_hilton_prime = ContactInfo.new(:address_line_1 => "London Hilton on Park Lane Hotel",
:address_line_2 => "22 Park Lane",
:city => "London",
:country => "United Kingdom",
:zipcode => "W1K1BE",
:contactable => hilton_prime
)
hilton_prime.contact_info = contact_info_for_hilton_prime
hilton_prime.save!
<file_sep>/app/api/itineraries/apiv1.rb
module Itineraries
class APIV1 < Grape::API
resource :itinerary do
desc "Returns an itinerary for a given id"
get "/:id" do
itinerary = Itinerary.find(params[:id])
present itinerary, :with => Itineraries::ItineraryResponseEntity
end
end
end
end
<file_sep>/Gemfile
source 'http://rubygems.org'
ruby "1.9.3"
gem 'rails', '~> 3.2.0'
gem 'devise'
gem 'jquery-rails'
gem 'haml'
gem 'mongoid', "~> 3.0.5"
gem 'bson_ext'
gem 'thin'
gem 'carrierwave'
gem 'mongoid-ancestry'
gem 'rails-backbone'
gem 'grape'
gem 'mongoid_rails_migrations', '~> 1.0.0'
gem 'uglifier'
gem 'less-rails'
gem 'therubyracer'
gem 'twitter-bootstrap-rails'
group :development do
gem 'travis-lint'
end
group :assets do
gem 'handlebars_assets'
end
group :test do
gem 'turn', '~> 0.8.3', :require => false
gem 'rspec'
gem 'rspec-rails'
gem 'shoulda-matchers'
gem 'database_cleaner'
gem 'fabrication'
gem 'json_spec'
end
<file_sep>/lib/tasks/data_load.rake
namespace :geonames do
namespace :data do
logger = Logger.new(STDOUT)
desc "Load the data from a provided filename to a intermediate collection in mongodb from where data will be funneled to core collection"
task :load_from, [:file_name_with_path] => ['environment:load_mongoid_config'] do |task, args|
require "#{Rails.root}/lib/tasks_support/data_loader"
logger.info "Starting data load. This may take some time."
filename = args[:file_name_with_path]
command = DataLoader.new(filename).command_to_load
logger.info `#{command}`
logger.info "Date load complete"
end
desc "Migrate the data from intermediate collection to the core place collection. Data transformation is done as part of this process"
task :migrate_to_core do
require "#{Rails.root}/lib/tasks_support/data_migrator"
logger.info "Data migration has been started. It may take a while"
DataMigrator.new.migrate
logger.info "Data migration is done!"
end
end
end
<file_sep>/spec/api/tips/apiv1_spec.rb
require 'spec_helper'
module Tips
describe APIV1 do
context "GET /api/tip/:id" do
let(:non_existent_tip_id) { Moped::BSON::ObjectId.new }
before do
@tip_on_eiffel_tower = Fabricate(:tip)
end
it "should return a 200 status code in reponse for valid tip" do
get "/api/tip/#{@tip_on_eiffel_tower.id}"
response.status.should eq 200
end
it "should return the detail of the tip in response body" do
get "/api/tip/#{@tip_on_eiffel_tower.id}"
json_response = response.body
tip_details_as_json = %({"text" : "#{@tip_on_eiffel_tower.text}"})
json_response.should be_json_eql(tip_details_as_json)
end
it "should return a 404 status code in response when tip is not found" do
get "/api/tip/#{non_existent_tip_id}"
response.status.should eq 404
end
it "should return an error json when tip is not found" do
get "/api/tip/#{non_existent_tip_id}"
response.body.should eq({:error => {:message => "We did not find what you were looking for", :code => 404}}.to_json)
end
end
end
end
<file_sep>/app/models/stat_group.rb
class StatGroup
include Mongoid::Document
field :likes, :type => Integer
field :dislikes, :type => Integer
embedded_in :place
end
<file_sep>/app/api/tips/tip_response_entity.rb
module Tips
class TipResponseEntity < Grape::Entity
expose :text
end
end
<file_sep>/app/api/places/place_response_entity.rb
module Places
class PlaceResponseEntity < Grape::Entity
expose :name
expose :_id, :as => :id
expose :photos, :using => Places::PhotoResponseEntity
expose :location, :using => Places::LocationResponseEntity
expose :stat_group, :as => :stats, :using => Places::StatGroupResponseEntity
expose :contact_info, :using => Places::ContactInfoResponseEntity
expose :categories, :using => Places::CategoryResponseEntity
end
end
<file_sep>/app/controllers/invite_controller.rb
class InviteController < ApplicationController
skip_filter :authenticate_user!
def create
invitation_request = Invite.new(:email => params["invite"]["email"])
invitation_request.save! if invitation_request.valid?
render :text => "", :head => :ok
end
end
<file_sep>/lib/tasks/environment.rake
namespace :environment do
desc "Load mongoid config for a environment"
task :load_mongoid_config do
Mongoid.load!("./config/mongoid.yml", :development)
end
end
<file_sep>/spec/models/review_spec.rb
require 'spec_helper'
describe Review do
context "attributes" do
it { should respond_to :text }
it { should respond_to :reviewer }
it { should respond_to :rating_value }
it { should respond_to :review_date }
it { should respond_to :place }
end
end
<file_sep>/app/models/place.rb
class Place
include Mongoid::Document
include Mongoid::Timestamps
include Mongoid::Ancestry
has_ancestry :orphan_strategy => :restrict
field :name, :type => String
field :alternate_names, :type => Array
embeds_many :photos
embeds_one :location
embeds_one :stat_group
embeds_one :contact_info, :as => :contactable
has_many :tips
has_many :reviews
has_many :categories
has_one :user, :as => :owner
end
<file_sep>/app/api/places/contact_info_response_entity.rb
module Places
class ContactInfoResponseEntity < Grape::Entity
expose :address_line_1
expose :address_line_2
expose :address_line_3
expose :city
expose :country
expose :zipcode
expose :state
end
end
<file_sep>/app/models/stopover.rb
class Stopover
include Mongoid::Document
field :name, :type => String
field :point_of_interest_type, :type => String
field :point_of_interest_id, :type => Moped::BSON::ObjectId
field :description, :type => String
embedded_in :itinerary
def point_of_interest_details
point_of_interest_type.constantize.send(:find, point_of_interest_id)
end
def self.at(point_of_interest, name = nil, description = nil)
Stopover.new(:name => name,
:description => description,
:point_of_interest_type => point_of_interest.class.name,
:point_of_interest_id => point_of_interest.id)
end
end
<file_sep>/app/api/places/category_response_entity.rb
module Places
class CategoryResponseEntity < Grape::Entity
expose :name
end
end
<file_sep>/app/api/itineraries/stopover_response_entity.rb
module Itineraries
class StopoverResponseEntity < Grape::Entity
expose :name, :as => :stopover_name
expose :description
expose :point_of_interest_details, :as => :point_of_interest, :using => Places::PlaceResponseEntity
end
end
<file_sep>/spec/models/category_spec.rb
require 'spec_helper'
describe Category do
context "attributes" do
it { should respond_to :name }
it { should respond_to :identifier }
end
context "identifier" do
it "should be lowercased always" do
monument_category = Fabricate(:category, :name=>"Monument", :identifier => "Monument")
Category.find(monument_category.id).identifier.should eq "monument"
end
it "should be auto assigned as lowercased undescorized version of name" do
monument_category = Fabricate(:category, :name=>"Nightlife Place", :identifier => nil)
Category.find(monument_category.id).identifier.should eq "nightlife_place"
end
it "should merely downcase the identifier if present" do
monument_category = Fabricate(:category, :name=>"Nightlife Place", :identifier => "Nightlife_For_Win")
Category.find(monument_category.id).identifier.should eq "nightlife_for_win"
end
it "should remove any spaces from identifier" do
monument_category = Fabricate(:category, :identifier => "Nightlife For Win")
Category.find(monument_category.id).identifier.should eq "nightlife_for_win"
end
end
end
<file_sep>/spec/models/contact_info_spec.rb
require 'spec_helper'
describe ContactInfo do
context "attributes" do
it { should respond_to :address_line_1 }
it { should respond_to :address_line_2 }
it { should respond_to :address_line_3 }
it { should respond_to :city }
it { should respond_to :country }
it { should respond_to :state }
it { should respond_to :zipcode }
it { should respond_to :phone_numbers }
it { should respond_to :contactable }
end
end
<file_sep>/app/models/tip.rb
class Tip
include Mongoid::Document
field :text, :type => String
belongs_to :user
belongs_to :place
end
<file_sep>/spec/models/location_spec.rb
require 'spec_helper'
describe Location do
context "attributes" do
it { should respond_to :cordinates }
it { should respond_to :latitude }
it { should respond_to :longitude }
end
context "geographical cordinates" do
let(:location) { Fabricate.build(:location) }
it "should have latitude" do
location.latitude.should eq 48.858165
end
it "should have longitude" do
location.longitude.should eq 2.295354
end
end
end
<file_sep>/app/api/reviews/apiv1.rb
module Reviews
class APIV1 < Grape::API
resource :review do
desc "Returns a Review for a passed id"
get "/:id" do
review = Review.find(params[:id])
present review, :with => Reviews::ReviewResponseEntity
end
end
end
end
<file_sep>/spec/models/photo_spec.rb
require 'spec_helper'
describe Photo do
context "attributes" do
it { should respond_to :url }
it { should respond_to :type }
it { should respond_to :caption }
it { should respond_to :place }
end
end
<file_sep>/lib/tasks_support/data_migrator.rb
class DataMigrator
def migrate
end
end
<file_sep>/app/api/itineraries/itinerary_response_entity.rb
module Itineraries
class ItineraryResponseEntity < Grape::Entity
expose :name
expose :description
expose :stopovers, :using => Itineraries::StopoverResponseEntity
end
end
<file_sep>/app/models/phone_number.rb
class PhoneNumber
include Mongoid::Document
field :country_code, :type => String
field :area_code, :type => String
field :number, :type => String
def formatted_phone_number
formatted_country_code = country_code.present? ? ["+", country_code].join : ""
[formatted_country_code, area_code, number].compact.join(" ").strip
end
end
<file_sep>/lib/tasks_support/data_loader.rb
class DataLoader
def initialize(filename, filetype = "tsv")
@fields = ["geoid","name","asciiname","alternatenames","latitude","longitude",
"feature_class","feature_code","country_code","cc2","admin1","admin2",
"admin3","admin4","population","elevation","dem","timezone","modification_date"]
@db_name = Mongoid::Config.sessions["default"]["database"]
@collection_name = "raw_geodata"
@file_type = filetype
@filename = filename
end
def command_to_load
"mongoimport --db #{@db_name} --collection #{@collection_name} --type #{@file_type} --file #{@filename} --fields #{@fields.join(",")}"
end
end
<file_sep>/app/api/api.rb
class API < Grape::API
format :json
error_format :json
version 'v1', :using => :header
rescue_from Mongoid::Errors::DocumentNotFound do |error|
rack_response({"error" => {"message" => "We did not find what you were looking for", "code" => 404}}.to_json, 404)
end
#Places API
mount Places::APIV1
#Review API
mount Reviews::APIV1
#Tips API
mount Tips::APIV1
#User API
mount Users::APIV1
#Itenerary API
mount Itineraries::APIV1
end
<file_sep>/app/api/users/apiv1.rb
module Users
class APIV1 < Grape::API
resource :user do
desc "Returns a user for a given user id"
get '/:id' do
user = User.find(params[:id])
present user, :with => Users::UserResponseEntity
end
end
end
end
<file_sep>/app/api/reviews/review_response_entity.rb
module Reviews
class ReviewResponseEntity < Grape::Entity
expose :text
expose :review_date, :as => :review_datetime
expose :rating_value, :as => :rating
end
end
<file_sep>/spec/api/itineraries/apiv1_spec.rb
require 'spec_helper'
module Itineraries
describe APIV1 do
context "GET /api/itinerary/:id" do
let(:non_existent_itinerary_id) { Moped::BSON::ObjectId.new }
let(:eiffel_tower_stopover) { Fabricate.build(:eiffel_tower_stopover) }
let(:hilton_hotel_stopover) { Fabricate.build(:hilton_hotel_stopover) }
before do
@itinerary_to_paris = Fabricate(:itinerary, :stopovers => [eiffel_tower_stopover, hilton_hotel_stopover])
end
it "should return a 200 status code in reponse for valid itinerary" do
get "/api/itinerary/#{@itinerary_to_paris.id}"
response.status.should eq 200
end
it "should return the detail of the itinerary in response body" do
get "/api/itinerary/#{@itinerary_to_paris.id}"
json_response = response.body
itinerary_details_as_json = %({"name" : "Trip to Paris", "description" : "Winter trip with family to somewhere nice"})
json_response.should be_json_eql(itinerary_details_as_json).excluding("stopovers")
end
context "place as point of interest" do
it "should include photos and their details for the place in response" do
get "/api/itinerary/#{@itinerary_to_paris.id}"
json_response = response.body
json_response.should have_json_type(String).at_path("stopovers/0/point_of_interest/photos/0/url")
json_response.should have_json_type(String).at_path("stopovers/0/point_of_interest/photos/0/caption")
json_response.should have_json_type(String).at_path("stopovers/0/point_of_interest/photos/0/type")
end
it "should include location details for the point of interest in response" do
get "/api/itinerary/#{@itinerary_to_paris.id}"
json_response = response.body
json_response.should have_json_type(Float).at_path("stopovers/0/point_of_interest/location/latitude")
json_response.should have_json_type(Float).at_path("stopovers/0/point_of_interest/location/longitude")
end
it "should include the stats from stat group details of the place in response" do
get "/api/itinerary/#{@itinerary_to_paris.id}"
json_response = response.body
json_response.should have_json_type(Integer).at_path("stopovers/0/point_of_interest/stats/likes")
json_response.should have_json_type(Integer).at_path("stopovers/0/point_of_interest/stats/dislikes")
end
end
it "should return all the stopovers in the response body" do
get "/api/itinerary/#{@itinerary_to_paris.id}"
json_response = response.body
json_response.should have_json_size(2).at_path("stopovers")
end
it "should return complete stopover detail in the response body" do
get "/api/itinerary/#{@itinerary_to_paris.id}"
json_response = response.body
json_response.should have_json_size(2).at_path("stopovers")
end
it "should return a 404 status code in response when itinerary is not found" do
get "/api/itinerary/#{non_existent_itinerary_id}"
response.status.should eq 404
end
it "should return an error json when itinerary is not found" do
get "/api/itinerary/#{non_existent_itinerary_id}"
response.body.should eq({:error => {:message => "We did not find what you were looking for", :code => 404}}.to_json)
end
end
end
end
<file_sep>/spec/fabricators/tip_fabricator.rb
Fabricator(:tip) do
text "The ground view of Eiffel tower is best from the north corner of the lawns"
user
place
end
<file_sep>/spec/models/stopover_spec.rb
require 'spec_helper'
describe Stopover do
context "attributes" do
subject { Fabricate.build(:stopover) }
it { should respond_to :point_of_interest_type }
it { should respond_to :name }
it { should respond_to :description }
it { should respond_to :point_of_interest_id }
it { should respond_to :point_of_interest_details }
end
context "association with place as point of interest" do
before do
@eiffel_tower = Fabricate(:place)
@stopover = Stopover.at(@eiffel_tower,"Eiffel Tower","Lunch at Eiffel Tower")
itinerary = Fabricate(:itinerary, :stopovers => [@stopover])
end
it "should initialize the point of interest type to that of the point of interest passed" do
@stopover.point_of_interest_type.should eq "Place"
end
it "should initialize the point of interest id with the id of point of interest passed" do
@stopover.point_of_interest_id.should eq @eiffel_tower.id
end
it "should return a place as a point of interest details when requested" do
@stopover.point_of_interest_details.should eq @eiffel_tower
end
it "should return 'Place' as the point of interest type" do
@stopover.point_of_interest_type.should eq "Place"
end
it "should return name assigned to the node" do
@stopover.name.should eq "Eiffel Tower"
end
it "should return the description assigned to the node" do
@stopover.description.should eq "Lunch at Eiffel Tower"
end
end
end
<file_sep>/app/assets/javascripts/views/layouts/betaInvitation.js
App.Views.Layouts.Beta = App.Views.Layouts.Beta || {};
App.Views.Layouts.Beta.Invitation = Backbone.Marionette.Layout.extend({
template: 'layouts/betaInvitation',
regions: {
content: '#invite'
},
views:{},
onShow: function() {
this.views.invitation = App.Views.Beta.Invitation;
this.content.show(new this.views.invitation);
}
});
App.addInitializer(function() {
App.layouts.invitation = new App.Views.Layouts.Beta.Invitation();
});
<file_sep>/spec/models/place_spec.rb
require 'spec_helper'
describe Place do
context "attributes" do
it { should respond_to :categories }
it { should respond_to :photos }
it { should respond_to :tips }
it { should respond_to :reviews }
it { should respond_to :location }
it { should respond_to :alternate_names }
it { should respond_to :contact_info }
it { should respond_to :user }
it { should respond_to :stat_group }
it { should respond_to :updated_at }
it { should respond_to :created_at }
it { should respond_to :name }
end
context "owner" do
end
context "hierarchy" do
let(:france) { Fabricate(:france) }
it "should not allow place with sub-places to be deleted" do
eiffel_tower = Fabricate(:place, :parent => france)
lambda {france.destroy}.should raise_error(Mongoid::Ancestry::Error)
end
it "should allow place to be deleted if no children exists" do
france.destroy.should be_true
end
end
end
<file_sep>/app/api/places/stat_group_response_entity.rb
module Places
class StatGroupResponseEntity < Grape::Entity
expose :likes
expose :dislikes
end
end
<file_sep>/db/migrate/20121006100858_create_base_categories.rb
class CreateBaseCategories < Mongoid::Migration
def self.up
["Monument", "Hotel", "Nightlife", "Park", "Coffee Shop", "Restaurant"].each do |category|
Category.create!(:name => category)
end
end
def self.down
Category.destory_all
end
end
<file_sep>/app/models/invite.rb
class Invite
include Mongoid::Document
field :email, :type => String
validates_format_of :email,
:with => /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i,
:message => "email address is not valid"
end
<file_sep>/spec/models/tip_spec.rb
require 'spec_helper'
describe Tip do
context "attributes" do
it { should respond_to :text }
it { should respond_to :place }
it { should respond_to :user }
end
end
<file_sep>/spec/models/user_spec.rb
require 'spec_helper'
describe User do
context "attributes" do
it { should respond_to :email }
it { should respond_to :unconfirmed_email }
it { should respond_to :encrypted_password }
it { should respond_to :reset_password_sent_at }
it { should respond_to :reset_password_token }
it { should respond_to :remember_created_at }
it { should respond_to :confirmation_sent_at }
it { should respond_to :confirmed_at }
it { should respond_to :confirmation_token }
it { should validate_presence_of(:email) }
it { should validate_presence_of(:encrypted_password) }
end
end
<file_sep>/app/models/user.rb
class User
include Mongoid::Document
devise :database_authenticatable, :registerable, :confirmable,
:recoverable, :rememberable, :validatable, :timeoutable
field :first_name, :type => String
field :last_name, :type => String
field :email, :type => String, :default => ""
field :unconfirmed_email, :type => String, :default => ""
field :encrypted_password, :type => String, :default => ""
field :reset_password_token, :type => String
field :reset_password_sent_at, :type => Time
field :remember_created_at, :type => Time
field :confirmation_token, :type => String
field :confirmed_at, :type => Time
field :confirmation_sent_at, :type => Time
validates_presence_of :email
validates_presence_of :encrypted_password
end
<file_sep>/spec/fabricators/location_fabricator.rb
Fabricator(:location) do
cordinates [48.858165,2.295354]
end
<file_sep>/spec/api/users/apiv1_spec.rb
require 'spec_helper'
module Users
describe APIV1 do
context "GET /api/user/:id" do
let(:non_existent_user_id) { Moped::BSON::ObjectId.new }
before do
@greg_house = Fabricate(:user, :email => "<EMAIL>")
end
it "should return a 200 status code in reponse for valid user" do
get "/api/user/#{@greg_house.id}"
response.status.should eq 200
end
it "should return the detail of the user in response body" do
get "/api/user/#{@greg_house.id}"
json_response = response.body
user_details_as_json = %({"first_name" : "#{@greg_house.first_name}", "last_name" : "#{@greg_house.last_name}", "email" : "#{@greg_house.email}"})
json_response.should be_json_eql(user_details_as_json)
end
it "should return a 404 status code in response when user is not found" do
get "/api/user/#{non_existent_user_id}"
response.status.should eq 404
end
it "should return an error json when user is not found" do
get "/api/user/#{non_existent_user_id}"
response.body.should eq({:error => {:message => "We did not find what you were looking for", :code => 404}}.to_json)
end
end
end
end
<file_sep>/app/models/itinerary.rb
class Itinerary
include Mongoid::Document
field :name, :type => String
field :description, :type => String
embeds_many :stopovers
end
<file_sep>/app/api/tips/apiv1.rb
module Tips
class APIV1 < Grape::API
resource :tip do
desc "Returns a tip for a given id"
get "/:id" do
tip = Tip.find(params[:id])
present tip, :with => Tips::TipResponseEntity
end
end
end
end
<file_sep>/spec/fabricators/category_fabricator.rb
Fabricator(:category, :from => :category) do
name "Category"
identifier "category"
end
Fabricator(:monuments, :from => :category) do
name "monuments"
end
Fabricator(:hotels, :from => :category) do
name "hotels"
end
<file_sep>/spec/fabricators/place_fabricator.rb
#encoding: UTF-8
Fabricator(:place) do
name "Eiffel Tower"
alternate_names ['La Tour Eiffel','a dame de fer', 'the iron lady']
categories { Array.wrap(Fabricate.build(:monuments)) }
location {Fabricate.build(:location) }
stat_group { Fabricate.build(:likable) }
photos { Array.wrap(Fabricate.build(:photo)) }
after_create { |place| place.contact_info = Fabricate.build(:eiffel_tower_address, :contactable => place); place.save!}
end
Fabricator(:hilton_hotel, :from => :place) do
name "<NAME>"
alternate_names ['Hotel la Hilton']
categories { Array.wrap(Fabricate.build(:hotels)) }
location { Fabricate.build(:location, :cordinates => [51.505612, -0.149633]) }
stat_group { Fabricate.build(:likable) }
photos { Array.wrap(Fabricate.build(:photo)) }
after_create { |place| place.contact_info = Fabricate.build(:hilton_hotel_address, :contactable => place); place.save!}
end
Fabricator(:france, :from => :place) do
name "France"
alternate_names ['République française','French Republic']
categories { Array.wrap(Fabricate.build(:monuments)) }
location { Fabricate.build(:location, :cordinates => [41.00, 6.0]) }
after_create { |place| place.contact_info = Fabricate.build(:france_address, :contactable => place); place.save!}
end
<file_sep>/app/assets/javascripts/models/invitation.js
App.Models.Beta = App.Models.Beta || {};
App.Models.Beta.Invitation = Backbone.Model.extend({
url: "/invite.json",
paramRoot: 'invite',
defaults: {
"email":""
}
});
<file_sep>/app/controllers/mocks_controller.rb
class MocksController < ApplicationController
skip_filter :authenticate_user!
def home
render :home
end
end
<file_sep>/spec/fabricators/itinerary_fabricator.rb
Fabricator(:itinerary) do
name "Trip to Paris"
description "Winter trip with family to somewhere nice"
stopovers { Array.wrap(Fabricate.build(:stopover)) }
end
<file_sep>/spec/models/stat_group_spec.rb
require 'spec_helper'
describe StatGroup do
context "types" do
it { should respond_to :likes }
it { should respond_to :dislikes }
end
end
<file_sep>/app/api/places/location_response_entity.rb
module Places
class LocationResponseEntity < Grape::Entity
expose :latitude
expose :longitude
end
end
<file_sep>/README.md
[](https://codeclimate.com/github/priyaaank/T)
[](http://travis-ci.org/priyaaank/T)
Some Random Pet Project
=========================
Just another repo. Will add more details as and when required.
<file_sep>/app/api/places/photo_response_entity.rb
module Places
class PhotoResponseEntity < Grape::Entity
expose :_id, :as => :id
expose :url
expose :caption
expose :type
end
end
<file_sep>/spec/models/phone_number_spec.rb
require 'spec_helper'
describe PhoneNumber do
context "attributes" do
it { should respond_to :country_code }
it { should respond_to :area_code }
it { should respond_to :number }
end
context "representation as text" do
let(:indian_phone_number) { PhoneNumber.new(:country_code => "91", :area_code => "020", :number => "2334567") }
let(:phone_for_unknown_country) { PhoneNumber.new(:area_code => "020", :number => "2334567") }
it "should be formatted in +<country_code> <area_code> <number> format" do
indian_phone_number.formatted_phone_number.should eq "+91 020 2334567"
end
it "should not append + sign if country code is not present" do
phone_for_unknown_country.formatted_phone_number.should eq "020 2334567"
end
end
end
<file_sep>/app/api/places/apiv1.rb
module Places
class APIV1 < Grape::API
resource :place do
desc "Returns a place for an id"
get '/:id' do
place = Place.find(params[:id])
present place, :with => Places::PlaceResponseEntity
end
end
end
end
<file_sep>/spec/fabricators/photo_fabricator.rb
Fabricator(:photo) do
url { sequence(:url) { |i| "http://example.com/photo/#{i}" } }
caption "The vivid picture of the place"
type "jpeg"
end
<file_sep>/spec/api/reviews/apiv1_spec.rb
require 'spec_helper'
module Reviews
describe APIV1 do
context "GET /api/review/:id" do
let(:non_existent_review_id) { Moped::BSON::ObjectId.new }
before do
@review_of_eiffel_tower = Fabricate(:review)
end
it "should return a 200 status code in reponse for valid review" do
get "/api/review/#{@review_of_eiffel_tower.id}"
response.status.should eq 200
end
it "should return the detail of the review in response body" do
get "/api/review/#{@review_of_eiffel_tower.id}"
json_response = response.body
review_details_as_json = %({"text" : "#{@review_of_eiffel_tower.text}",
"rating" : #{@review_of_eiffel_tower.rating_value},
"review_datetime" : "#{@review_of_eiffel_tower.review_date}"})
json_response.should be_json_eql(review_details_as_json)
end
it "should return a 404 status code in response when review is not found" do
get "/api/review/#{non_existent_review_id}"
response.status.should eq 404
end
it "should return an error json when review is not found" do
get "/api/review/#{non_existent_review_id}"
response.body.should eq({:error => {:message => "We did not find what you were looking for", :code => 404}}.to_json)
end
end
end
end
<file_sep>/spec/lib/tasks_support/data_load_spec.rb
require 'spec_helper'
require "#{Rails.root}/lib/tasks_support/data_loader"
describe DataLoader do
it "should print command to load data dump in raw format" do
filename = "/Users/example/some_sample_file.tsv"
command = DataLoader.new(filename).command_to_load
expected_command = "mongoimport --db t_test --collection raw_geodata --type tsv --file /Users/example/some_sample_file.tsv --fields geoid,name,asciiname,alternatenames,latitude,longitude,feature_class,feature_code,country_code,cc2,admin1,admin2,admin3,admin4,population,elevation,dem,timezone,modification_date"
command.should eq expected_command
end
end
<file_sep>/spec/fabricators/stopover_fabricator.rb
Fabricator(:stopover, :aliases => [:eiffel_tower_stopover]) do
initialize_with { place = Fabricate(:place); place.save!; Stopover.at(place) }
name "<NAME>"
description "Mid day stop for view and lunch"
end
Fabricator(:hilton_hotel_stopover, :from => :stopover) do
initialize_with { place = Fabricate(:hilton_hotel); place.save!; Stopover.at(place) }
name "<NAME>"
description "Super comfy and pocket shredding expensive hotel"
end
<file_sep>/spec/models/itinerary_spec.rb
require 'spec_helper'
describe Itinerary do
context "attributes" do
it { should respond_to :stopovers }
it { should respond_to :name }
it { should respond_to :description }
end
context "stopovers" do
let(:eiffel_tower_stopover) { Fabricate.build(:eiffel_tower_stopover) }
let(:hilton_hotel_stopover) { Fabricate.build(:hilton_hotel_stopover) }
before do
@trip_to_paris = Fabricate(:itinerary, :stopovers => [])
@trip_to_paris.stopovers << eiffel_tower_stopover
@trip_to_paris.stopovers << hilton_hotel_stopover
end
it "should assign and persist stopovers against itinerary" do
Itinerary.find(@trip_to_paris.id).stopovers.size.should eq 2
end
it "should maintain the order of insertion under an itinerary" do
stopovers = Itinerary.find(@trip_to_paris.id).stopovers
stopovers.first.should eq eiffel_tower_stopover
stopovers.last.should eq hilton_hotel_stopover
end
end
end
<file_sep>/spec/fabricators/user_fabricator.rb
Fabricator(:user) do
first_name "Gregory"
last_name "House"
email { sequence(:email) { |i| "<EMAIL>" } }
password "<PASSWORD>"
password_confirmation "<PASSWORD>"
after_create { |user| user.confirm! }
end
<file_sep>/spec/lib/tasks_support/data_migrator_spec.rb
require "#{Rails.root}/lib/tasks_support/data_migrator"
require 'spec_helper'
describe DataMigrator do
context "migration" do
context "when geoname record doesn't exist" do
it "should create a new record" do
end
end
context "when geoname record exists" do
it "should update the record" do
end
end
end
end
<file_sep>/app/models/location.rb
class Location
include Mongoid::Document
field :cordinates, :type => Array
embedded_in :place
def latitude
cordinates[0]
end
def longitude
cordinates[1]
end
end
<file_sep>/app/models/contact_info.rb
class ContactInfo
include Mongoid::Document
field :address_line_1, :type => String
field :address_line_2, :type => String
field :address_line_3, :type => String
field :city, :type => String
field :country, :type => String
field :zipcode, :type => String
field :state, :type => String
embeds_many :phone_numbers
embedded_in :contactable, :polymorphic => true
end
|
d44e8cd16f9a722eac936e435493f1c3b1eba896
|
[
"JavaScript",
"Ruby",
"Markdown"
] | 79
|
JavaScript
|
priyaaank/T
|
158db9205a8bf2bef94e648d16230a8574a8368f
|
b1aa4fd7885dc7f2aa3b661c5a5f2a9a99e9d70c
|
refs/heads/master
|
<file_sep>from django.http import HttpResponseRedirect
from django.utils.http import is_safe_url
from currencies.models import Currency
def set_currency(request):
currency_code = request.POST.get('currency', request.GET.get('currency'))
next = request.POST.get('next', request.GET.get('next'))
if next:
if not is_safe_url(url=next, host=request.get_host()):
next = '/'
else:
next = request.META.get('HTTP_REFERER', None) or '/'
response = HttpResponseRedirect(next)
if currency_code:
try:
Currency.objects.get(code__exact=currency_code)
except Currency.DoesNotExist:
# ignore
return response
if hasattr(request, 'session'):
request.session['currency'] = currency_code
else:
response.set_cookie('currency', currency_code)
return response
|
33e8f946d210ab7ce9ec709a9322aba6db6794d0
|
[
"Python"
] | 1
|
Python
|
cloudregistry/django-currencies
|
570790a8f3b5b0247ceb62448be53afb011fec79
|
58fd4e08df20aa72f76d963afd70f0c8005953f2
|
refs/heads/master
|
<file_sep>package me.stormbits.astromining.frame.mining;
import org.bukkit.Location;
public class AstroMiningBlock {
private Location location;
private MineableBlock mineableBlock;
private int damage;
private int task;
public AstroMiningBlock(Location location, MineableBlock mineableBlock, int task) {
this.location = location;
this.mineableBlock = mineableBlock;
this.task = task;
this.damage = 0;
}
public Location getLocation() {
return location;
}
public int getTask() {
return task;
}
public MineableBlock getMineableBlock() {
return mineableBlock;
}
public int getDamage() {
return damage;
}
public void setDamage(int damage) {
this.damage = damage;
}
}
<file_sep>import org.apache.tools.ant.filters.ReplaceTokens
plugins {
id 'java'
id "com.github.johnrengelman.shadow" version "5.2.0"
}
group = 'me.stormbits'
version = '1.0'
sourceCompatibility = '1.8'
targetCompatibility = '1.8'
repositories {
mavenLocal()
mavenCentral()
maven {
name = 'spigotmc-repo'
url = 'https://hub.spigotmc.org/nexus/content/repositories/snapshots/'
}
maven {
name = 'sonatype'
url = 'https://oss.sonatype.org/content/groups/public/'
}
}
dependencies {
compileOnly 'org.spigotmc:spigot:1.8.8-R0.1-SNAPSHOT'
compileOnly files('resources/AstroPlayers-1.0-all.jar')
compileOnly files('resources/AstroBoard-1.0-all.jar')
compileOnly files('resources/StormLib-1.0-all.jar')
}
processResources {
from(sourceSets.main.resources.srcDirs) {
filter ReplaceTokens, tokens: [version: version]
}
}
<file_sep>package me.stormbits.astromining.frame;
import me.stormbits.astromining.frame.mining.Tool;
import me.stormbits.stormlib.utils.NBTEditor;
import org.bukkit.inventory.ItemStack;
public class AstroPickaxe {
private ItemStack itemStack;
private Tool tool;
private int pickaxeLevel;
private int percentEnergy;
private int energy;
public AstroPickaxe(ItemStack itemStack) {
this.tool = Tool.getToolFromMaterial(itemStack);
this.pickaxeLevel = NBTEditor.getInt(itemStack, "level");
this.percentEnergy = NBTEditor.getInt(itemStack, "percentEnergy");
this.energy = NBTEditor.getInt(itemStack, "energy");
}
public void update() {
//TODO: UPDATE METHOD FOR LORE ETC.
}
}
<file_sep>package me.stormbits.astromining.commands;
/*
Created by Lars at 4/11/2021
*/
import me.stormbits.astromining.Main;
import me.stormbits.astromining.util.ItemBuilder;
import me.stormbits.stormlib.commands.StormCommand;
import me.stormbits.stormlib.utils.StringUtils;
import org.bukkit.Material;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
public class GivePickaxeCommand extends StormCommand {
private Main plugin;
public GivePickaxeCommand(Main plugin) {
this.plugin = plugin;
this.setLabel("givepickaxe");
this.setUsageMsg("/givepickaxe");
this.setConsoleCanUse(false);
this.setMinArgs(0);
this.setMaxArgs(0);
this.setHasPermission(false);
}
@Override
public void perform(CommandSender sender, String[] strings) {
Player player = (Player) sender;
ItemStack itemStack = new ItemBuilder(Material.WOOD_PICKAXE)
.setName("Wood Pickaxe &a1")
.setLore(" ", "&bEnergy", StringUtils.getProgressBar(0, 100, 40, '|', "&a", "&c") + " &r&l0%", "&7(&f0 &7/ " + plugin.getEnergyManager().getEnergyMap().get(1) + ")", " ", "&eRequires Level &r&l10").build();
player.getInventory().addItem(itemStack);
}
}
<file_sep>package me.stormbits.astromining.events;
import me.stormbits.astroboard.frame.AstroBoardType;
import me.stormbits.astromining.Main;
import me.stormbits.astromining.frame.mining.AstroMiningBlock;
import me.stormbits.astromining.frame.mining.MineableBlock;
import me.stormbits.astromining.frame.mining.Tool;
import me.stormbits.astroplayers.AstroPlayer;
import net.minecraft.server.v1_8_R3.EntityPlayer;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.craftbukkit.v1_8_R3.entity.CraftPlayer;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockDamageEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.scheduler.BukkitRunnable;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
public class BlockEvents implements Listener {
private Main instance;
public BlockEvents(Main instance) {
this.instance = instance;
}
@EventHandler
public void onBlockBreak(MineableBlockBreak event) {
Player player = event.getPlayer();
Block block = event.getBlock();
MineableBlock mineableBlock = MineableBlock.fromMaterial(block.getType());
if (mineableBlock == null) return;
new BukkitRunnable() {
AstroMiningBlock astroMiningBlock = null;
AstroPlayer astroPlayer = Main.getPlugin().getPlayerManager().getPlayer(player.getUniqueId());
int timeRan = 0;
@Override
public void run() {
if (instance.getMiningManager().getMining().containsKey(player.getUniqueId())) {
for (AstroMiningBlock astroBlock : instance.getMiningManager().getMining().get(player.getUniqueId())) {
if (astroBlock.getTask() == getTaskId()) astroMiningBlock = astroBlock;
if (block.getLocation().getBlockX() == astroBlock.getLocation().getBlockX() &&
block.getLocation().getBlockY() == astroBlock.getLocation().getBlockY() &&
block.getLocation().getBlockZ() == astroBlock.getLocation().getBlockZ() &&
astroBlock.getTask() != getTaskId()) {
this.cancel();
return;
}
}
}
if(astroMiningBlock == null) {
astroMiningBlock = new AstroMiningBlock(block.getLocation(), mineableBlock, getTaskId());
List<AstroMiningBlock> currentlyMining = new ArrayList<>();
if (instance.getMiningManager().getMining().containsKey(player.getUniqueId())) currentlyMining = instance.getMiningManager().getMining().get(player.getUniqueId());
currentlyMining.add(astroMiningBlock);
instance.getMiningManager().getMining().put(player.getUniqueId(), currentlyMining);
event.setDamageBlock(1);
astroMiningBlock.setDamage(1);
}
EntityPlayer entityPlayer = ((CraftPlayer)player).getHandle();
Block target = player.getTargetBlock((Set<Material>) null, 5);
Location tLoc = target.getLocation();
if(astroMiningBlock != null && astroMiningBlock.getDamage() == 9 && entityPlayer.ar) {
//TODO BREAK BLOCK
Bukkit.broadcastMessage("broken");
List<AstroMiningBlock> mining = instance.getMiningManager().getMining().get(player.getUniqueId());
if(mining != null) mining.remove(astroMiningBlock);
instance.getServer().getScheduler().runTaskLaterAsynchronously(instance, () -> {
if(instance.getMiningManager().getMining().containsKey(player.getUniqueId()))
if(!instance.getMiningManager().getMining().get(player.getUniqueId()).isEmpty())
instance.getMiningManager().getMining().remove(player.getUniqueId());
}, 100L);
event.breakBlock();
this.cancel();
me.stormbits.astroboard.Main.getPlugin().getBoardManager().applyScoreboard(player);
instance.getLevelManager().giveExp(astroPlayer, astroMiningBlock.getMineableBlock().getExp());
player.sendMessage(ChatColor.GREEN + "You have just received " + astroMiningBlock.getMineableBlock().getExp() + " EXP.");
return;
//TODO REST
} else if(astroMiningBlock != null && astroMiningBlock.getDamage() < 9 && entityPlayer.ar &&
tLoc.getBlockX() == astroMiningBlock.getLocation().getBlockX() &&
tLoc.getBlockY() == astroMiningBlock.getLocation().getBlockY() &&
tLoc.getBlockZ() == astroMiningBlock.getLocation().getBlockZ()) {
List<AstroMiningBlock> mining;
if(instance.getMiningManager().getMining().containsKey(player.getUniqueId()))
mining = instance.getMiningManager().getMining().get(player.getUniqueId());
else mining = new ArrayList<>();
mining.remove(astroMiningBlock);
event.setDamageBlock(astroMiningBlock.getDamage());
astroMiningBlock.setDamage(astroMiningBlock.getDamage() + 1);
mining.add(astroMiningBlock);
instance.getMiningManager().getMining().put(player.getUniqueId(), mining);
}
if(timeRan >= (astroMiningBlock.getMineableBlock().getSpeed() * 20)) {
Bukkit.broadcastMessage("cancelled");
List<AstroMiningBlock> mining = instance.getMiningManager().getMining().get(player.getUniqueId());
if(mining != null) mining.remove(astroMiningBlock);
instance.getServer().getScheduler().runTaskLaterAsynchronously(instance, () -> {
if(instance.getMiningManager().getMining().containsKey(player.getUniqueId()))
if(!instance.getMiningManager().getMining().get(player.getUniqueId()).isEmpty())
instance.getMiningManager().getMining().remove(player.getUniqueId());
}, 100L);
this.cancel();
return;
} else {
timeRan += astroMiningBlock.getMineableBlock().getSpeed();
}
}
}.runTaskTimer(instance, 0L, mineableBlock.getSpeed());
}
@EventHandler
public void onBlockDamage(BlockDamageEvent event) {
Player player = event.getPlayer();
AstroPlayer astroPlayer = Main.getPlugin().getPlayerManager().getPlayer(player.getUniqueId());
Block block = event.getBlock();
if (!player.hasPotionEffect(PotionEffectType.SLOW_DIGGING))
player.addPotionEffect(new PotionEffect(PotionEffectType.SLOW_DIGGING, Integer.MAX_VALUE, -1, false));
ItemStack itemStack = player.getInventory().getItemInHand();
for (MineableBlock mineableBlock : MineableBlock.values()) {
if (mineableBlock.getMaterial() == block.getType()) {
if (mineableBlock.getTool() == Tool.getToolFromMaterial(itemStack)) {
Bukkit.getPluginManager().callEvent(new MineableBlockBreak(player, astroPlayer, block));
//allow block breaking
//SHOW SCOREBOARD
}
}
}
}
}
<file_sep>rootProject.name = 'AstroMining'
|
665070216c46d627c610c90b0c7a9dd64eaf7d98
|
[
"Java",
"Gradle"
] | 6
|
Java
|
meStormBits/AstroMining
|
99f9246e7932fdbe85e15d080a39efdb79721aec
|
4cc6fed992524ab3a0e81788b0568991469b3208
|
refs/heads/master
|
<file_sep><?php namespace Gzero\EloquentTree\Model;
use DB;
use Gzero\EloquentTree\Model\Exception\MissingParentException;
use Gzero\EloquentTree\Model\Exception\SelfConnectionException;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model as Eloquent;
/**
* Class Tree
*
* This class represents abstract tree model for inheritance
*
* @author <NAME> <<EMAIL>>
* @package Gzero\EloquentTree\Model
*/
abstract class Tree extends Eloquent {
/**
* Database tree fields
*
* @var array
*/
protected static $treeColumns = [
'path' => 'path',
'parent' => 'parent_id',
'level' => 'level'
];
/**
* @inheritdoc
*/
public function __construct(array $attributes = [])
{
parent::__construct($attributes);
$this->addTreeEvents(); // Adding tree events
}
/**
* Set node as root node
*
* @return $this
*/
public function setAsRoot()
{
$this->handleNewNodes();
if (!$this->isRoot()) { // Only if it is not already root
if ($this->fireModelEvent('updatingParent') === false) {
return $this;
}
$oldDescendants = $this->getOldDescendants();
$this->{$this->getTreeColumn('path')} = $this->getKey() . '/';
$this->{$this->getTreeColumn('parent')} = null;
$this->setRelation('parent', null);
$this->{$this->getTreeColumn('level')} = 0;
$this->save();
$this->fireModelEvent('updatedParent', false);
$this->updateDescendants($this, $oldDescendants);
}
return $this;
}
/**
* Set node as child of $parent node
*
* @param Tree $parent
*
* @return $this
*/
public function setChildOf(Tree $parent)
{
$this->handleNewNodes();
if ($this->validateSetChildOf($parent)) {
if ($this->fireModelEvent('updatingParent') === false) {
return $this;
}
$oldDescendants = $this->getOldDescendants();
$this->{$this->getTreeColumn('path')} = $this->generateNewPath($parent);
$this->{$this->getTreeColumn('parent')} = $parent->getKey();
$this->{$this->getTreeColumn('level')} = $parent->{$this->getTreeColumn('level')} + 1;
$this->save();
$this->fireModelEvent('updatedParent', false);
$this->updateDescendants($this, $oldDescendants);
}
return $this;
}
/**
* Validate if parent change and prevent self connection
*
* @param Tree $parent New parent node
*
* @return bool
* @throws Exception\SelfConnectionException
*/
public function validateSetChildOf(Tree $parent)
{
if ($parent->getKey() == $this->getKey()) {
throw new SelfConnectionException();
}
if ($parent->{$this->getTreeColumn('path')} != $this->removeLastNodeFromPath()) { // Only if new parent
return true;
}
return false;
}
/**
* Set node as sibling of $sibling node
*
* @param Tree $sibling New sibling node
*
* @return $this
*/
public function setSiblingOf(Tree $sibling)
{
$this->handleNewNodes();
if ($this->validateSetSiblingOf($sibling)) {
if ($this->fireModelEvent('updatingParent') === false) {
return $this;
}
$oldDescendants = $this->getOldDescendants();
$this->{$this->getTreeColumn('path')} = $sibling->removeLastNodeFromPath() . $this->getKey() . '/';
$this->{$this->getTreeColumn('parent')} = $sibling->{$this->getTreeColumn('parent')};
$this->{$this->getTreeColumn('level')} = $sibling->{$this->getTreeColumn('level')};
$this->save();
$this->fireModelEvent('updatedParent', false);
$this->updateDescendants($this, $oldDescendants);
}
return $this;
}
/**
* Validate if parent change and prevent self connection
*
* @param Tree $sibling New sibling node
*
* @return bool
*/
public function validateSetSiblingOf(Tree $sibling)
{
if ($sibling->removeLastNodeFromPath() != $this->removeLastNodeFromPath()) { // Only if new parent and != self
return true;
}
return false;
}
/**
* Check if node is root
* This function check foreign key field
*
* @return bool
*/
public function isRoot()
{
return (empty($this->{$this->getTreeColumn('parent')})) ? true : false;
}
/**
* Check if node is sibling for passed node
*
* @param Tree $node
*
* @return bool
*/
public function isSibling(Tree $node)
{
return $this->{$this->getTreeColumn('parent')} === $node->{$this->getTreeColumn('parent')};
}
/**
* Get parent to specific node (if exist)
*
* @return static
*/
public function parent()
{
return $this->belongsTo(get_class($this), $this->getTreeColumn('parent'), $this->getKeyName());
}
/**
* Get children to specific node (if exist)
*
* @return static
*/
public function children()
{
return $this->hasMany(get_class($this), $this->getTreeColumn('parent'), $this->getKeyName());
}
/**
* Find all descendants for specific node with this node as root
*
* @return \Illuminate\Database\Eloquent\Builder
*/
public function findDescendants()
{
return static::where($this->getTreeColumn('path'), 'LIKE', $this->{$this->getTreeColumn('path')} . '%')
->orderBy($this->getTreeColumn('level'), 'ASC');
}
/**
* Find all ancestors for specific node with this node as leaf
*
* @return \Illuminate\Database\Eloquent\Builder
*/
public function findAncestors()
{
return static::whereIn($this->getKeyName(), $this->extractPath())
->orderBy($this->getTreeColumn('level'), 'ASC');
}
/**
* Find root for this node
*
* @return $this
*/
public function findRoot()
{
if ($this->isRoot()) {
return $this;
} else {
$extractedPath = $this->extractPath();
$root_id = array_shift($extractedPath);
return static::where($this->getKeyName(), '=', $root_id)->first();
}
}
/**
* Rebuilds trees from passed nodes
*
* @param Collection $nodes Nodes from which we are build tree
* @param bool $strict If we want to make sure that there are no orphan nodes
*
* @return static Root node
* @throws MissingParentException
*/
public function buildTree(Collection $nodes, $strict = true)
{
$refs = []; // Reference table to store records in the construction of the tree
$count = 0;
$roots = new Collection();
foreach ($nodes as &$node) {
/* @var Tree $node */
$node->initChildrenRelation(); // We need to init relation to avoid LAZY LOADING in future
$refs[$node->getKey()] = &$node; // Adding to ref table (we identify after the id)
if ($count === 0) {
$roots->add($node);
$count++;
} else {
if ($this->siblingOfRoot($node, $roots)) { // We use this condition as a factor in building subtrees
$roots->add($node);
} else { // This is not a root, so add them to the parent
$index = $node->{$this->getTreeColumn('parent')};
if (!empty($refs[$index])) { // We should already have parent for our node added to refs array
$refs[$index]->addChildToCollection($node);
} else {
if ($strict) { // We don't want to ignore orphan nodes
throw new MissingParentException();
}
}
}
}
}
if (!empty($roots)) {
if (count($roots) > 1) {
return $roots;
} else {
return $roots->first();
}
} else {
return false;
}
}
/**
* Displays a tree as html
* Rendering function accept {sub-tree} tag, represents next tree level
*
* EXAMPLE:
* $root->render(
* 'ul',
* function ($node) {
* return '<li>' . $node->title . '{sub-tree}</li>';
* },
* TRUE
* );
*
* @param string $tag HTML tag for level section
* @param callable $render Rendering function
* @param bool $displayRoot Is the root will be displayed
*
* @return string
*/
public function render($tag, Callable $render, $displayRoot = true)
{
$out = '';
if ($displayRoot) {
$out .= '<' . $tag . ' class="tree tree-level-' . $this->{$this->getTreeColumn('level')} . '">';
$root = $render($this);
$nextLevel = $this->renderRecursiveTree($this, $tag, $render);
$out .= preg_replace('/{sub-tree}/', $nextLevel, $root);
$out .= '</' . $tag . '>';
} else {
$out = $this->renderRecursiveTree($this, $tag, $render);
}
return $out;
}
/**
* Determine if we've already loaded the children
* Used to prevent lazy loading on children
*
* @return bool
*/
public function isChildrenLoaded()
{
return isset($this->relations['children']);
}
//---------------------------------------------------------------------------------------------------------------
// START STATIC
//---------------------------------------------------------------------------------------------------------------
/**
* Adds observer inheritance
*/
protected static function boot()
{
parent::boot();
static::observe(new Observer());
}
/**
* Gets all root nodes
*
* @return \Illuminate\Database\Eloquent\Builder
*/
public static function getRoots()
{
return static::whereNull(static::getTreeColumn('parent'));
}
/**
* Gets all leaf nodes
*
* @return \Illuminate\Database\Eloquent\Builder
*/
public static function getLeaves()
{
$parents = static::select('parent_id')->whereNotNull('parent_id')->distinct()->get()->pluck('parent_id')->all();
return static::wherenotin('id',$parents);
}
/**
* @param null $name
*
* @throws \Exception
*/
public static function getTreeColumn($name = null)
{
if (empty($name)) {
return static::$treeColumns;
} elseif (!empty(static::$treeColumns[$name])) {
return static::$treeColumns[$name];
}
throw new \Exception('Tree column: ' . $name . ' undefined');
}
/**
* Map array to tree structure in database
* You must set $fillable attribute to use this function
*
* Example array:
* array(
* 'title' => 'root',
* 'children' => array(
* array('title' => 'node1'),
* array('title' => 'node2')
* )
* );
*
* @param array $map Nodes recursive array
*/
public static function mapArray(Array $map)
{
foreach ($map as $item) {
$root = new static($item);
$root->setAsRoot();
if (isset($item['children'])) {
static::mapDescendantsArray($root, $item['children']);
}
}
}
/**
* Map array as descendants nodes in database to specific parent node
* You must set $fillable attribute to use this function
*
* @param Tree $parent Parent node
* @param array $map Nodes recursive array
*/
public static function mapDescendantsArray(Tree $parent, Array $map)
{
foreach ($map as $item) {
$node = new static($item);
$node->setChildOf($parent);
if (isset($item['children'])) {
static::mapDescendantsArray($node, $item['children']);
}
}
}
//---------------------------------------------------------------------------------------------------------------
// END STATIC
//---------------------------------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------------------------------
// START PROTECTED/PRIVATE
//---------------------------------------------------------------------------------------------------------------
/**
* Creating node if not exist
*/
protected function handleNewNodes()
{
if (!$this->exists) {
$this->save();
}
}
/**
* Adds tree specific events
*
* @return array
*/
protected function addTreeEvents()
{
$this->observables = array_merge(
[
'updatedParent',
'updatingParent',
'updatedDescendants'
],
$this->observables
);
}
/**
* Extract path to array
*
* @return array
*/
protected function extractPath()
{
$path = explode('/', $this->{$this->getTreeColumn('path')});
array_pop($path); // Remove last empty element
return $path;
}
/**
* Removing last node id from path and returns it
*
* @return mixed Node path
*/
protected function removeLastNodeFromPath()
{
return preg_replace('/\d\/$/', '', $this->{$this->getTreeColumn('path')});
}
/**
* Generating new path based on parent path
*
* @param Tree $parent Parent node
*
* @return string New path
*/
protected function generateNewPath(Tree $parent)
{
return $parent->{$this->getTreeColumn('path')} . $this->getKey() . '/';
}
/**
* Adds children for this node while building the tree structure in PHP
*
* @param Tree $child Child node
*/
protected function addChildToCollection(&$child)
{
$this->setRelation('children', $this->getRelation('children')->add($child));
}
/**
* Gets old descendants before modify parent
*
* @return Collection|static[]
*/
protected function getOldDescendants()
{
$collection = $this->findDescendants()->get();
$collection->shift(); // Removing current node from update
return $collection;
}
/**
* Recursive render descendants
*
* @param $node
* @param $tag
* @param callable $render
*
* @return string
*/
protected function renderRecursiveTree($node, $tag, Callable $render)
{
$out = '';
$out .= '<' . $tag . ' class="tree tree-level-' . ($node->{$node->getTreeColumn('level')} + 1) . '">';
foreach ($node->children as $child) {
if (!empty($child->children)) {
$level = $render($child);
$nextLevel = $this->renderRecursiveTree($child, $tag, $render);
$out .= preg_replace('/{sub-tree}/', $nextLevel, $level);
} else {
$out .= preg_replace('/{sub-tree}/', '', $render($child));
}
}
return $out . '</' . $tag . '>';
}
/**
* Updating descendants nodes
*
* @param Tree $node Updated node
* @param Collection $oldDescendants Old descendants collection (just before modify parent)
*/
protected function updateDescendants(Tree $node, $oldDescendants)
{
$refs = [];
$refs[$node->getKey()] = &$node; // Updated node
foreach ($oldDescendants as &$child) {
$refs[$child->getKey()] = $child;
$parent_id = $child->{$this->getTreeColumn('parent')};
if (!empty($refs[$parent_id])) {
if ($refs[$parent_id]->path != $refs[$child->getKey()]->removeLastNodeFromPath()) {
$refs[$child->getKey()]->level = $refs[$parent_id]->level + 1; // New level
$refs[$child->getKey()]->path = $refs[$parent_id]->path . $child->getKey() . '/'; // New path
DB::table($this->getTable())
->where($child->getKeyName(), '=', $child->getKey())
->update(
[
$this->getTreeColumn('level') => $refs[$child->getKey()]->level,
$this->getTreeColumn('path') => $refs[$child->getKey()]->path
]
);
}
}
}
$this->fireModelEvent('updatedDescendants', false);
}
/**
* Check if node is sibling for roots in collection
*
* @param Tree $node Tree node
* @param Collection $roots Collection of roots
*
* @return bool
*/
private function siblingOfRoot(Tree $node, Collection $roots)
{
return (bool) $roots->filter(
function ($item) use ($node) {
return $node->isSibling($item);
}
)->first();
}
/**
* Init children relation to avoid empty LAZY LOADING
*/
protected function initChildrenRelation()
{
$relations = $this->getRelations();
if (empty($relations['children'])) {
$this->setRelation('children', new Collection());
}
}
//---------------------------------------------------------------------------------------------------------------
// END PROTECTED/PRIVATE
//---------------------------------------------------------------------------------------------------------------
}
<file_sep><?php
class Tree extends \Gzero\EloquentTree\Model\Tree {
protected $fillable = ['title'];
/**
* ONLY FOR TESTS!
* Metod resets static::$booted
*/
public static function __resetBootedStaticProperty()
{
static::$booted = [];
}
}
<file_sep><?php namespace Gzero\EloquentTree\Model;
use DB;
/**
* Class Observer
*
* @author <NAME> <<EMAIL>>
* @package Gzero\EloquentTree\Model
*/
class Observer {
/**
* When saving node we must set path and level
*
* @param Tree $model
*/
public function saving(Tree $model)
{
if (!$model->exists and !in_array('path', array_keys($model->attributesToArray()), TRUE)) {
$model->{$model->getTreeColumn('path')} = '';
$model->{$model->getTreeColumn('parent')} = NULL;
$model->{$model->getTreeColumn('level')} = 0;
}
}
/**
* After mode was saved we're building node path
*
* @param Tree $model
*/
public function saved(Tree $model)
{
if ($model->{$model->getTreeColumn('path')} === '') { // If we just save() new node
$model->{$model->getTreeColumn('path')} = $model->getKey() . '/';
DB::connection($model->getConnectionName())->table($model->getTable())
->where($model->getKeyName(), '=', $model->getKey())
->update(
array(
$model->getTreeColumn('path') => $model->{$model->getTreeColumn('path')}
)
);
}
}
}
<file_sep><?php
namespace Gzero\EloquentTree\Model\Exception;
class MissingParentException extends \Exception {
}
<file_sep><?php
namespace Gzero\EloquentTree\Model\Exception;
class SelfConnectionException extends \Exception {
}
<file_sep>eloquent-tree [](https://packagist.org/packages/gzero/eloquent-tree) [](https://packagist.org/packages/gzero/eloquent-tree) [](https://travis-ci.org/AdrianSkierniewski/eloquent-tree)
=============
Eloquent Tree is a tree model for Laravel Eloquent ORM.
## Table of Contents
- [Features](#features)
- [Installation](#installation)
- [Migration](#migration)
- [Example usage](#example-usage)
- [Events](#events)
- [Support](#support)
##Features
* Creating root, children and sibling nodes
* Getting children
* Getting descendants
* Getting ancestor
* Moving sub-tree
* Building tree on PHP side
## Installation
**Version 1.0 is not compatible with 0.***
**Version 2.0 - Laravel 5 support**
**Version 2.1 - Laravel 5.1 support**
**Version 3.0 - Laravel 5.3 support**
Begin by installing this package through Composer. Edit your project's composer.json file to require gzero/eloquent-tree.
```json
"require": {
"laravel/framework": "5.3.*",
"gzero/eloquent-tree": "v3.0.*"
},
"minimum-stability" : "stable"
```
Next, update Composer from the Terminal:
```
composer update
```
That's all now you can extend \Gzero\EloquentTree\Model\Tree in your project
## Migration
Simply migration with all required columns that you could extend by adding new fields
```php
Schema::create(
'trees',
function (Blueprint $table) {
$table->increments('id');
$table->string('path', 255)->nullable();
$table->integer('parent_id')->unsigned()->nullable();
$table->integer('level')->default(0);
$table->timestamps();
$table->index(array('path', 'parent_id', 'level'));
$table->foreign('parent_id')->references('id')->on('contents')->onDelete('CASCADE');
}
);
```
## Example usage
- [Inserting and Updating new nodes](#inserting-and-updating-new-nodes)
- [Getting tree nodes](#getting-tree-nodes)
- [Finding Leaf nodes](#getting-leaf-nodes)
- [Map from array](#map-from-array)
- [Rendering tree](#rendering-tree)
### Inserting and updating new nodes
```php
$root = new Tree(); // New root
$root->setAsRoot();
$child = with(new Tree())->setChildOf($root); // New child
$sibling = new Tree();
$sibling->setSiblingOf($child); // New sibling
```
### Getting tree nodes
Leaf - returning root node
```php
$leaf->findRoot();
```
Children - returning flat collection of children. You can use Eloquent query builder.
```php
$collection = $root->children()->get();
$collection2 = $root->children()->where('url', '=', 'slug')->get();
```
Ancestors - returning flat collection of ancestors, first is root, last is current node. You can use Eloquent query builder.
Of course there are no guarantees that the structure of the tree would be complete if you do the query with additional where
```php
$collection = $node->findAncestors()->get();
$collection2 = $node->findAncestors()->where('url', '=', 'slug')->get();
```
Descendants - returning flat collection of descendants, first is current node, last is leafs. You can use Eloquent query builder.
Of course there are no guarantees that the structure of the tree would be complete if you do the query with additional where
```php
$collection = $node->findDescendants()->get();
$collection2 = $node->findDescendants()->where('url', '=', 'slug')->get();
```
Building tree structure on PHP side - if some nodes will be missing, these branches will not be built
```php
$treeRoot = $root->buildTree($root->findDescendants()->get())
```
### Getting leaf nodes
```php
Tree::getLeaves();
```
### Map from array
Three new roots, first with descendants
```php
Tree::mapArray(
array(
array(
'children' => array(
array(
'children' => array(
array(
'children' => array(
array(
'children' => array()
),
array(
'children' => array()
)
)
),
array(
'children' => array()
)
)
),
array(
'children' => array()
)
)
),
array(
'children' => array()
),
array(
'children' => array()
)
)
);
```
### Rendering tree
You can render tree built by the function buildTree
```php
$html = $root->render(
'ul',
function ($node) {
return '<li>' . $node->title . '{sub-tree}</li>';
},
TRUE
);
echo $html;
```
## Events
All tree models have additional events:
* updatingParent
* updatedParent
* updatedDescendants
You can use them for example to update additional tables
## Support
If you enjoy my work, please consider making a small donation, so I can continue to maintain and create new software to help
other users.
[](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=6YKG4RZRQF3GS)
<file_sep><?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateTreeTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create(
'trees',
function (Blueprint $table) {
$table->increments('id');
$table->string('path', 255)->nullable();
$table->integer('parent_id')->unsigned()->nullable();
$table->integer('level')->default(0);
$table->timestamps();
$table->index(array('path', 'parent_id'));
$table->foreign('parent_id')->references('id')->on('trees')->on_delete('CASCADE');
}
);
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('trees');
}
}
<file_sep><?php
spl_autoload_register( // Autoload because we're using \Eloquent alias provided by Orchestra
function ($class) {
require_once 'Model/Tree.php';
}
);
class Test extends Orchestra\Testbench\TestCase {
/**
* Default preparation for each test
*/
public function setUp()
{
parent::setUp();
$this->loadMigrationsFrom(
[
'--database' => 'testbench',
'--realpath' => realpath(__DIR__ . '/migrations'),
]
);
}
public function tearDown()
{
parent::tearDown();
Tree::__resetBootedStaticProperty();
}
/**
* New node saved as root
*
* @test
*/
public function can_create_new_node_as_root()
{
$root = new Tree();
$this->assertNotEmpty($root->setAsRoot()); // Should return this
$this->assertTrue($root->isRoot(), 'Assert root node');
// Assert path and level set properly
$this->assertEquals($root->id, 1);
$this->assertEquals($root->path, $root->id . '/');
$this->assertEquals($root->level, 0);
$this->assertEmpty($root->parent, 'Expected no parent');
$root2 = new Tree();
$this->assertNotEmpty($root2->save()); // Standard save - we expect root node
$this->assertTrue($root2->isRoot(), 'Assert root node');
// Assert path, level and parent set properly
$this->assertEquals($root2->id, 2);
$this->assertEquals($root2->path, $root2->id . '/');
$this->assertEquals($root2->level, 0);
$this->assertEmpty($root2->parent, 'Expected no parent');
}
/**
* New node saved as child
*
* @test
*/
public function can_create_new_node_as_child()
{
$root = with(new Tree())->setAsRoot();
$child = with(new Tree())->setChildOf($root);
// Assert path, level and parent set properly
$this->assertEquals($root->path . $child->id . '/', $child->path, 'Wrong children path!');
$this->assertEquals($root->level + 1, $child->level, 'Wrong children level!');
$this->assertEquals($root->id, $child->parent_id, 'Wrong children parent!');
$this->assertEquals($root->path, $child->parent->path, 'Wrong children parent!');
}
/**
* New node saved as sibling
*
* @test
*/
public function can_create_new_node_as_sibling()
{
$sibling = with(new Tree())->setAsRoot();
$node = with(new Tree())->setSiblingOf($sibling);
// Assert path, level and parent set properly
$this->assertEquals($node->id . '/', $node->path, 'Wrong sibling path!');
$this->assertEquals($sibling->level, $node->level, 'Wrong sibling level!');
$this->assertEquals($sibling->parent_id, $node->parent_id, 'Wrong sibling parent!');
$this->assertEquals($sibling->parent, $node->parent, 'Wrong sibling parent!');
}
/**
* Change existing node to root node
*
* @test
*/
public function testChangeNodeToRoot()
{
$root = with(new Tree())->setAsRoot();
$node = with(new Tree())->setChildOf($root);
$this->assertEquals($root->path, $node->parent->path);
$node->setAsRoot(); // Change node to became root
$this->assertEmpty($node->parent, 'New root expected to have no parent');
$this->assertEquals($node->level, 0, 'Root node should have level set to 0');
$this->assertEquals($node->id . '/', $node->path, ' Root path should look like - root_id/');
$this->assertEquals($node->parent_id, null, 'New root parent_id expected to be NULL');
$this->assertEquals($node->parent, null, 'New root parent relation should be set to NULL');
}
/**
* Get all children for specific node
*
* @test
*/
public function can_find_children_for_node()
{
$root = with(new Tree())->setAsRoot();
$node = with(new Tree())->setChildOf($root);
$node2 = with(new Tree())->setChildOf($root);
$correct[] = $node;
$correct[] = $node2;
// Getting all children for this root
foreach ($root->children as $key => $child) {
$this->assertEquals($correct[$key]->path, $child->path); // Child path same as returned from children relation
$this->assertEquals($correct[$key]->parent, $child->parent);// Child parent same as returned from children relation
}
// children becomes root node
$newRoot = $node->setAsRoot();
$this->assertTrue($newRoot->isRoot(), 'Assert root node');
$this->assertEmpty($newRoot->parent, 'Expected no parent');
// Modify correct pattern
$correct[0] = $node2;
unset($correct[1]);
// Getting all children for old root
foreach ($root->children()->get() as $key => $child) { // We must refresh children relation
$this->assertEquals($correct[$key]->path, $child->path); // Child path same as returned from children relation
$this->assertEquals($correct[$key]->parent, $child->parent);// Child parent same as returned from children relation
}
$this->assertEquals([], $newRoot->children->toArray(), 'New Root expects to have no children');
}
/**
* Get all ancestors for specific node
*
* @test
*/
public function can_find_ancestors_for_node()
{
extract($this->_createSampleTree()); // Build sample data
$this->assertEquals($child1_1->id, $child1_1_1->parent->id, 'Node expects to have a specific parent');
$correct = [
$root,
$child1,
$child1_1,
$child1_1_1
];
foreach ($child1_1_1->findAncestors()->get() as $key => $ancestor) {
$this->assertEquals($correct[$key]->path, $ancestor->path); // Ancestor path same as returned from findAncestors()
$this->assertEquals($correct[$key]->parent, $ancestor->parent);// Ancestor path same as returned from findAncestors()
}
}
/**
* Get all descendants for specific node
*
* @test
*/
public function can_get_all_descendants_for_node()
{
extract($this->_createSampleTree());
$this->assertEquals(0, $child1_1_1->children()->count(), 'Node expected to be leaf');
$correct = [
$child1,
$child1_1,
$child1_1_1
];
foreach ($child1->findDescendants()->get() as $key => $descendant) {
$this->assertEquals($correct[$key]->path, $descendant->path); // Same as returned from findDescendants()
$this->assertEquals($correct[$key]->parent, $descendant->parent);// Same as returned from findDescendants()
}
}
/**
* Get root for specific node
*
* @test
*/
public function cat_find_root_node()
{
extract($this->_createSampleTree());
$this->assertEquals($root->toArray(), $child1_1_1->findRoot()->toArray(), 'Expected root node');
}
/**
* Recursive node updating
*
* @test
*/
public function can_move_sub_tree()
{
extract($this->_createAdvancedTree());
$this->assertEquals($child2_2->toArray(), $child2_2_1->parent->toArray(), 'Node expects to have a specific parent');
$this->assertEquals($child2_2_1->level, 3, 'Node expects to have a specific level');
// Move whole subtree
$child2_2->setAsRoot();
$this->assertEquals(0, $child2_2->level, 'Node expects to have a specific level');
$this->assertEquals(1, with(Tree::find($child2_2_1->id))->level, 'Node expects to have a specific level');
$this->assertEquals(1, with(Tree::find($child2_2_2->id))->level, 'Node expects to have a specific level');
$this->assertEquals(2, with(Tree::find($child2_2_2_1->id))->level, 'Node expects to have a specific level');
$this->assertEquals(
$child2_2->id,
preg_replace('/\/.+/', '', with(Tree::find($child2_2_2_1->id))->path),
'Node expects to have a specific path'
);
}
/**
* Tree building on PHP side
*
* @test
*/
public function can_build_complete_tree()
{
extract($this->_createAdvancedTree());
$treeRoot = $root->buildTree($root->findDescendants()->get());
$this->assertEquals($root->id, $treeRoot->id, 'Specific child expected');
$this->assertEquals($treeRoot->children[0]->id, $child1->id, 'Specific child expected');
$this->assertEquals($treeRoot->children[0]->children[0]->id, $child1_1->id, 'Specific child expected');
$this->assertEquals($treeRoot->children[0]->children[0]->children[0]->id, $child1_1_1->id, 'Specific child expected');
$this->assertEquals($treeRoot->children[1]->id, $child2->id, 'Specific child expected');
$this->assertEquals($treeRoot->children[1]->children[1]->children[0]->id, $child2_2_1->id, 'Specific child expected');
}
/**
* Tree building on PHP side
*
* @test
*/
public function can_build_sub_tree()
{
extract($this->_createAdvancedTree());
$treeRoot = $child1->buildTree($child1->findDescendants()->get());
$this->assertEquals($child1->id, $treeRoot->id, 'Specific child expected');
$this->assertEquals($treeRoot->children[0]->id, $child1_1->id, 'Specific child expected');
$this->assertEquals($treeRoot->children[0]->children[0]->id, $child1_1_1->id, 'Specific child expected');
}
/**
* Tree building on PHP side
*
* @test
*/
public function can_build_complete_trees()
{
extract($this->_createAdvancedTrees());
$nodes = $root->orderBy('level', 'ASC')->get(); // We get all nodes
$treeRoots = $root->buildTree($nodes); // And we should build two trees
$this->assertEquals(count($treeRoots), 2, 'We shoul have exactly 2 roots');
$this->assertEquals($treeRoots[0]->children[0]->id, $child1->id, 'Specific child expected');
$this->assertEquals($treeRoots[0]->children[0]->children[0]->id, $child1_1->id, 'Specific child expected');
$this->assertEquals($treeRoots[0]->children[0]->children[0]->children[0]->id, $child1_1_1->id, 'Specific child expected');
$this->assertEquals($treeRoots[0]->children[1]->id, $child2->id, 'Specific child expected');
$this->assertEquals($treeRoots[0]->children[1]->children[1]->children[0]->id, $child2_2_1->id, 'Specific child expected');
$this->assertEquals($treeRoots[1]->children[0]->id, $child4->id, 'Specific child expected');
$this->assertEquals($treeRoots[1]->children[0]->children[0]->id, $child4_1->id, 'Specific child expected');
$this->assertEquals($treeRoots[1]->children[0]->children[0]->children[0]->id, $child4_1_1->id, 'Specific child expected');
$this->assertEquals($treeRoots[1]->children[1]->id, $child5->id, 'Specific child expected');
$this->assertEquals($treeRoots[1]->children[1]->children[1]->children[0]->id, $child5_2_1->id, 'Specific child expected');
}
/**
* Tree building on PHP side
*
* @test
*/
public function it_returns_null_if_cant_build_tree()
{
extract($this->_createSampleTree());
$treeRoots = $root->buildTree(new \Illuminate\Database\Eloquent\Collection()); // Empty collection, so we can't build tree
$this->assertNull($treeRoots);
}
/**
* Tree building from array
*
* @test
*/
public function can_map_array()
{
Tree::mapArray(
[
[
'children' => [
[
'children' => [
[
'children' => [
[
'children' => []
],
[
'children' => []
]
]
],
[
'children' => []
]
]
],
[
'children' => []
]
]
],
[
'children' => []
],
[
'children' => []
]
]
);
$this->assertEquals(3, Tree::getRoots()->count(), 'Expected numer of Roots');
$this->assertEquals(7, Tree::find(1)->findDescendants()->count(), 'Expected numer of Descendants');
$this->assertEquals(2, Tree::find(1)->children()->count(), 'Expected numer of Children');
$this->assertEquals(4, Tree::find(5)->findAncestors()->count(), 'Expected numer of Ancestors'); // Most nested
}
/**
* getting leaf nodes
*
* @test
*/
public function get_leaf_nodes()
{
extract($this->_createSampleTree());
$correct = [
$child2,
$child3,
$child1_1_1
];
foreach($root->getLeaves()->get() as $key=>$node )
{
$this->assertEquals($correct[$key]->toArray(),$node->toArray());
}
}
/**
* getting leaf nodes if the tree is only one node(root)
*
* @test
*/
public function get_leaf_nodes_root_only()
{
$root= with(new Tree())->setAsRoot();
$correct = [
$root->toArray()
];
$this->assertEquals($correct,$root->getLeaves()->get()->toArray());
}
/**
* Define environment setup.
*
* @param Illuminate\Foundation\Application $app
*
* @return void
*/
protected function getEnvironmentSetUp($app)
{
// reset base path to point to our package's src directory
$app['path.base'] = __DIR__ . '/../src';
$app['config']->set('database.default', 'testbench');
$app['config']->set(
'database.connections.testbench',
[
'driver' => 'sqlite',
'database' => ':memory:',
'prefix' => '',
]
);
}
/**
* Helper function
*
* @return array
*/
protected function _createSampleTree()
{
$tree = [];
$tree['root'] = with(new Tree())->setAsRoot();
$tree['child1'] = with(new Tree())->setChildOf($tree['root']);
$tree['child2'] = with(new Tree())->setChildOf($tree['root']);
$tree['child3'] = with(new Tree())->setChildOf($tree['root']);
$tree['child1_1'] = with(new Tree())->setChildOf($tree['child1']);
$tree['child1_1_1'] = with(new Tree())->setChildOf($tree['child1_1']);
return $tree;
}
/**
* Helper function
*
* @return array
*/
protected function _createAdvancedTree()
{
$tree = [];
$tree['root'] = with(new Tree())->setAsRoot();
$tree['child1'] = with(new Tree())->setChildOf($tree['root']);
$tree['child2'] = with(new Tree())->setChildOf($tree['root']);
$tree['child3'] = with(new Tree())->setChildOf($tree['root']);
$tree['child1_1'] = with(new Tree())->setChildOf($tree['child1']);
$tree['child2_1'] = with(new Tree())->setChildOf($tree['child2']);
$tree['child2_2'] = with(new Tree())->setChildOf($tree['child2']);
$tree['child1_1_1'] = with(new Tree())->setChildOf($tree['child1_1']);
$tree['child2_2_1'] = with(new Tree())->setChildOf($tree['child2_2']);
$tree['child2_2_2'] = with(new Tree())->setChildOf($tree['child2_2']);
$tree['child2_2_2_1'] = with(new Tree())->setChildOf($tree['child2_2_2']);
return $tree;
}
/**
* Helper function
*
* @return array
*/
protected function _createAdvancedTrees()
{
$tree = [];
$tree['root'] = with(new Tree())->setAsRoot();
$tree['child1'] = with(new Tree())->setChildOf($tree['root']);
$tree['child2'] = with(new Tree())->setChildOf($tree['root']);
$tree['child3'] = with(new Tree())->setChildOf($tree['root']);
$tree['child1_1'] = with(new Tree())->setChildOf($tree['child1']);
$tree['child2_1'] = with(new Tree())->setChildOf($tree['child2']);
$tree['child2_2'] = with(new Tree())->setChildOf($tree['child2']);
$tree['child1_1_1'] = with(new Tree())->setChildOf($tree['child1_1']);
$tree['child2_2_1'] = with(new Tree())->setChildOf($tree['child2_2']);
$tree['child2_2_2'] = with(new Tree())->setChildOf($tree['child2_2']);
$tree['child2_2_2_1'] = with(new Tree())->setChildOf($tree['child2_2_2']);
$tree['root2'] = with(new Tree())->setAsRoot();
$tree['child4'] = with(new Tree())->setChildOf($tree['root2']);
$tree['child5'] = with(new Tree())->setChildOf($tree['root2']);
$tree['child6'] = with(new Tree())->setChildOf($tree['root']);
$tree['child4_1'] = with(new Tree())->setChildOf($tree['child4']);
$tree['child5_1'] = with(new Tree())->setChildOf($tree['child5']);
$tree['child5_2'] = with(new Tree())->setChildOf($tree['child5']);
$tree['child4_1_1'] = with(new Tree())->setChildOf($tree['child4_1']);
$tree['child5_2_1'] = with(new Tree())->setChildOf($tree['child5_2']);
$tree['child5_2_2'] = with(new Tree())->setChildOf($tree['child5_2']);
$tree['child5_2_2_1'] = with(new Tree())->setChildOf($tree['child5_2_2']);
return $tree;
}
}
|
85fae740e6abb94d9273e79a2391f8c1868b7df0
|
[
"Markdown",
"PHP"
] | 8
|
PHP
|
burnz/eloquent-tree
|
de4065b9ef3977702d62227bf9a5afccb710fa82
|
071b21b23c97cde21cc3d4812e3bc3e2b1698064
|
refs/heads/master
|
<repo_name>oxsala/Android-Oxplorer<file_sep>/src/com/androidrss/preference/RemoverMandant.java
package com.androidrss.preference;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import protobuf.data.wbList.WbListData;
import protobuf.data.wbList.WbListData.Wb;
import aexp.explist.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.Toast;
import com.sskk.example.bookprovidertest.provider.NewDBAdapter;
//import com.sskk.example.bookprovidertest.provider.BookProviderMetaData;
public class RemoverMandant extends Activity {
boolean isAllCheckedMandant_Remove = false;
CharSequence[] arr_CS_allMandants_Remove;
List<String> MandantListEnablefromDB_Remove = new ArrayList();
AlertDialog adSelectMandant_Remove;
boolean[] isCheckedMandantListfromDB_Remove;
private final List<String> WBListRemovedfromMandantSelected_Remove = new ArrayList();
private final List<String> MandantListSelectedfromDialog_Remove = new ArrayList();
NewDBAdapter mDB;
List<Wb> listWb;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.remove_mandant);
mDB = new NewDBAdapter(getApplicationContext());
mDB.openDB();
updateMandantinDB_Remove();
prepareDialog_Remove();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK: {
// finish();
Intent intent = new Intent();
intent.setClass(RemoverMandant.this,
aexp.explist.ANDROID_RSS_READER.class);
startActivity(intent);
finish();
mDB.closeDB();
}
}
return false;
}
public void openDialogWithMandants_Remove() {
adSelectMandant_Remove = new AlertDialog.Builder(this)
.setTitle("Select Mandant to Remove :")
.setIcon(R.drawable.star_big_on)
.setMultiChoiceItems(arr_CS_allMandants_Remove,
isCheckedMandantListfromDB_Remove,
new DialogInterface.OnMultiChoiceClickListener() {
public void onClick(DialogInterface dialog,
int whichButton, boolean isChecked) {
// THEM Code:
if (isCheckedMandantListfromDB_Remove[whichButton] = true) {
MandantListSelectedfromDialog_Remove
.add(arr_CS_allMandants_Remove[whichButton]
.toString());
// MandantListUriSelectedfromDialog.add(MandantListUriEnablefromDB.get(whichButton));
} else {
isCheckedMandantListfromDB_Remove[whichButton] = isChecked;
}
}
})
.setPositiveButton(R.string.check_all,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
// THEM COde cho Check All
if (isAllCheckedMandant_Remove) {
isAllCheckedMandant_Remove = false;
} else {
isAllCheckedMandant_Remove = true;
}
setCheckAllMandant_Remove();
}
})
.setNeutralButton("Remove",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
removeSelectedMandants_Remove();
}
})
.setNegativeButton(R.string.alert_dialog_cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
Intent intent = new Intent();
intent.setClass(RemoverMandant.this,
aexp.explist.ANDROID_RSS_READER.class);
startActivity(intent);
finish();
mDB.closeDB();
}
}).show();
}
public void setCheckAllMandant_Remove() {
if (isAllCheckedMandant_Remove) {
for (int i = 0; i < MandantListEnablefromDB_Remove.size(); i++) {
isCheckedMandantListfromDB_Remove[i] = true;
MandantListSelectedfromDialog_Remove
.add(MandantListEnablefromDB_Remove.get(i));
// MandantListUriSelectedfromDialog.add(MandantListUriEnablefromDB.get(i));
}
} else {
for (int i = 0; i < MandantListEnablefromDB_Remove.size(); i++) {
isCheckedMandantListfromDB_Remove[i] = false;
}
}
openDialogWithMandants_Remove();
}
public void removeSelectedMandants_Remove() {
// updateMandantinDB();
for (int i = 0; i < MandantListSelectedfromDialog_Remove.size(); i++) {
getWbDataProtobuf_Remove(MandantListSelectedfromDialog_Remove
.get(i));
}
removeMandant_Remove();
mDB.closeDB();
//MandantListSelectedfromDialog_Remove.clear();
// MandantListUriSelectedfromDialog.clear();
Toast.makeText(this, "Remove Mandant Successfully !",
Toast.LENGTH_SHORT).show();
Intent intent = new Intent();
intent.setClass(RemoverMandant.this,
aexp.explist.ANDROID_RSS_READER.class);
startActivity(intent);
finish();
mDB.closeDB();
}
public void prepareDialog_Remove() {
String[] ssMandants = new String[MandantListEnablefromDB_Remove.size()];
isCheckedMandantListfromDB_Remove = new boolean[MandantListEnablefromDB_Remove
.size()];
for (int i = 0; i < MandantListEnablefromDB_Remove.size(); i++) {
ssMandants[i] = MandantListEnablefromDB_Remove.get(i);
isCheckedMandantListfromDB_Remove[i] = false;
}
arr_CS_allMandants_Remove = ssMandants;
openDialogWithMandants_Remove();
}
public void updateMandantinDB_Remove() {
MandantListEnablefromDB_Remove.clear();
Cursor c = mDB.getMandantByAdded("1");
if (c.moveToFirst()) {
do {
MandantListEnablefromDB_Remove.add(c.getString(1));
} while (c.moveToNext());
}
c.close();
}
public void getWbDataProtobuf_Remove(String Mandant) {
try {
InputStream is = new URL("https://my-ea.oxseed.net/" + Mandant
+ "/ext/oxplorer?content=wbList&login=admin&pass=<PASSWORD>")
.openStream();
WbListData.WbList data = WbListData.WbList.parseFrom(is);
listWb = data.getWbList();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
for (Wb wbLoop : listWb) {
WBListRemovedfromMandantSelected_Remove
.add("[" + Mandant + "]" + "_" + wbLoop.getId());
}
} catch (Exception e) {
Log.e("DayTrader", "Exception getting ProtocolBuffer data", e);
}
}
public void removeMandant_Remove() {
for (int i = 0; i < MandantListSelectedfromDialog_Remove.size(); i++) {
mDB.deleteMandant(MandantListSelectedfromDialog_Remove.get(i));
}
for (int j = 0; j < WBListRemovedfromMandantSelected_Remove.size(); j++) {
mDB.deleteWorkBasket(WBListRemovedfromMandantSelected_Remove.get(j));
}
}
}
<file_sep>/src/com/android/TestSegment/RSSImageData_Reader.java
package com.android.TestSegment;
public class RSSImageData_Reader {
private String width = null;
private String height = null;
RSSImageData_Reader(){
}
void setWidth(String value)
{
width = value;
}
void setHeight(String value)
{
height = value;
}
public String getWidth()
{
return width;
}
public String getHeight()
{
return height;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return width;
}
}
<file_sep>/src/aexp/explist/showFullImage.java
package aexp.explist;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PointF;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.FloatMath;
import android.view.Display;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.Toast;
import com.android.TestSegment.RSSFeed_Reader_Segment;
import com.android.TestSegment.RSSHandler_Reader_Segment;
import com.hots.zoom.ImageZoomView;
import com.hots.zoom.TouchZoomListener;
import com.hots.zoom.ZoomControl;
import com.test.androidtest.ActionItem;
import com.test.androidtest.QuickAction;
public class showFullImage extends Activity implements OnTouchListener {
private ProgressDialog progDailog;
private RSSFeed_Reader_Segment myRssFeed_Segment = null;
private final String imageUrl = "";
private String fullimage;
String t;
String LinkDocument;
ImageView comicview;
float zoomfactor;
Context context;
Bitmap kangoo;
private int scaledHeight;
private int scaledWidth;
private int widthAndroid;
private int heightAndroid;
float touchX = 0;
float touchY = 0;
float upX = 0;
float upY = 0;
float curx = 0;
float cury = 0;
float x = 1.0f;
float y = 1.0f;
float dx = 0;
float dy = 0;
private static final int INVALID_POINTER_ID = -1;
private float mPosX;
private float mPosY;
private float mLastTouchX;
private float mLastTouchY;
String[] arInfo;
private final int mActivePointerId = INVALID_POINTER_ID;
private int setzoom;
private final List<String> ListSmallImage = new ArrayList();
private final List<String> ListFullImage = new ArrayList();
private final List<String> ListLinkImage = new ArrayList();
private String messageLinkProcess;
private String messageLinkWB;
private String messageDocName;
private int setimage = 0;
private int page;
// TextView pageindex;
private String TitleDoc;
float downXValue;
float currentX;
float downYValue;
float currentY;
private String move;
private ScaleGestureDetector mScaleDetector;
private float mScaleFactor = 1.f;
Matrix matrix = new Matrix();
Matrix savedMatrix = new Matrix();
// We can be in one of these 3 states
static final int NONE = 0;
static final int DRAG = 1;
static final int ZOOM = 2;
int mode = NONE;
// Remember some things for zooming
PointF start = new PointF();
PointF mid = new PointF();
float oldDist = 1f;
private String TextTest;
private final List<String> SegmentX = new ArrayList();;
private final List<String> SegmentY = new ArrayList();;
private final List<String> SegmentWidth = new ArrayList();;
private final List<String> SegmentHeight = new ArrayList();;
private float dw, dh, newX, newY;
private float spaceX = 0;
private float spaceY = 0;
private float deltaX;
private float m, n, o, p;
float scale;
double SegmentX2;
double SegmentY2;
double SegmentH;
double SegmentW;
int minDelta;
double ScaleWidth;
double ScaleHeight;
int dwidth;
int dheight;
int height;
private String OCR;
private static final int ID_CREDITOR = 1;
private static final int ID_AMOUNT = 2;
private static final int ID_CURRENCY = 3;
private static final int ID_TYPE = 4;
QuickAction mQuickAction;
private EditText NewValueEditText;
private String NewValue;
List<String> FirstListIndex = new ArrayList<String>();
List<String> ValueListIndex = new ArrayList<String>();
private int positionChange;
private String IndexSelected;
private final double hs = 1.04;
private LinearLayout layoutZoomView;
private ImageZoomView mZoomView;
private ZoomControl mZoomControl;
private TouchZoomListener mZoomListener;
private Context mContext;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.showfullimage);
Bundle bundle = this.getIntent().getExtras();
CharSequence textMessage3 = bundle.getCharSequence("messageLinkWB");
messageLinkWB = "" + textMessage3;
CharSequence textDocName = bundle.getCharSequence("messageDocName");
messageDocName = "" + textDocName;
readRss_Segment();
LinearLayout layMain = (LinearLayout) this.findViewById(R.id.myScreen);
setImage();
layMain.setOnTouchListener(this);
layMain.addView(new Mens(this));
FirstListIndex.add("Coca Cola");
FirstListIndex.add("100,00");
FirstListIndex.add("Euro");
FirstListIndex.add("bill");
populateView();
/*
* ActionItem creditorItem = new ActionItem(ID_CREDITOR,
* "Creditor :"+ValueListIndex.get(0),
* getResources().getDrawable(R.drawable.creditor_icon)); ActionItem
* amountItem = new ActionItem(ID_AMOUNT,
* "Amount :"+ValueListIndex.get(1),
* getResources().getDrawable(R.drawable.amount_icon)); ActionItem
* currencyItem = new ActionItem(ID_CURRENCY,
* "Currency :"+ValueListIndex.get(2),
* getResources().getDrawable(R.drawable.currency_icon)); ActionItem
* typeItem = new ActionItem(ID_TYPE, "Type :"+ValueListIndex.get(3),
* getResources().getDrawable(R.drawable.type_icon)); // mQuickAction =
* new QuickAction(this);
*
* mQuickAction.addActionItem(creditorItem);
* mQuickAction.addActionItem(amountItem);
* mQuickAction.addActionItem(currencyItem);
* mQuickAction.addActionItem(typeItem);
*/
// setup the action item click listener
}
public class Mens extends View {
Button undo_Btn;
public Mens(Context context) {
super(context);
mScaleDetector = new ScaleGestureDetector(context,
new ScaleListener());
setFocusable(true);
undo_Btn = new Button(context);
undo_Btn.measure(150, 150); // size of view
int width = undo_Btn.getMeasuredWidth();
int height = undo_Btn.getMeasuredHeight();
int right = 100;
int top = 200;
undo_Btn.layout(right, top, right + width, top + height);
// img1=;
undo_Btn.setBackgroundDrawable(getResources().getDrawable(
R.drawable.i_symbol));
undo_Btn.setVisibility(VISIBLE);
undo_Btn.setId(10);
undo_Btn.setPadding(50, 50, 50, 50);
undo_Btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
}
});
/*
* tview= new TextView(context); tview.measure(400,400);
* tview.setText("AAAA");
*/
}
public class ScaleListener extends
ScaleGestureDetector.SimpleOnScaleGestureListener {
@Override
public boolean onScale(ScaleGestureDetector detector) {
mScaleFactor *= detector.getScaleFactor();
// Don't let the object get too small or too large.
mScaleFactor = Math.max(0.1f, Math.min(mScaleFactor, 5.0f));
invalidate();
return true;
}
}
@Override
protected void onDraw(Canvas canvas) {
Paint paint = new Paint();
canvas.drawColor(Color.BLACK);
// Matrix zoommatrix=new Matrix();
// zoommatrix.setScale(mScaleFactor, mScaleFactor);
// canvas.translate(mPosX, mPosY);
// canvas.scale(mScaleFactor, mScaleFactor);
canvas.drawBitmap(kangoo, matrix, paint);
paint.setColor(Color.RED);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(3);
int x = myRssFeed_Segment.getList().size();
double[] DeltaH = new double[x];
Display display = getWindowManager().getDefaultDisplay();
dwidth = display.getWidth();
dheight = display.getHeight();
// height=Math.round(dwidth*(809.0F/594));//828.652
height = Math.round(dwidth * (2921.0F / 2115));// 828.652
// dwidth=500;
// dheight=500;
// ScaleWidth =(594.0F/(dwidth*hs));//width=600 thi
// ScaleWidth=3.525, = 320 thi ScaleWidth =6.609
// ScaleHeight=(809.0F/(height));
ScaleWidth = (2115.0F / (dwidth * hs));// width=600 thi
// ScaleWidth=3.525, = 320
// thi ScaleWidth =6.609
ScaleHeight = (2921.0F / (height * hs));
for (int i = 0; i < x; i++) {
double a = Double.parseDouble(SegmentX.get(i));
double b = Double.parseDouble(SegmentY.get(i));
double c = Double.parseDouble(SegmentWidth.get(i));
double d = Double.parseDouble(SegmentHeight.get(i));
newY = touchY /* + dh - spaceY */;
newX = touchX /* + dw - spaceX */;
SegmentX2 = (a / ScaleWidth);
SegmentY2 = (b / ScaleHeight);
SegmentH = (d / ScaleHeight);
SegmentW = (c / ScaleWidth);
DeltaH[i] = Math.sqrt((newX - SegmentX2) * (newX - SegmentX2)
+ (newY - SegmentY2) * (newY - SegmentY2));
}
minDelta = getMinValue(DeltaH);
double a = Double.parseDouble(SegmentX.get(minDelta));
double b = Double.parseDouble(SegmentY.get(minDelta));
double c = Double.parseDouble(SegmentWidth.get(minDelta));
double d = Double.parseDouble(SegmentHeight.get(minDelta));
// SegmentX2 = (float) (a /(ImageWidth/dwidth)/(maxWidth/dWidth);
SegmentX2 = (a / ScaleWidth) * 1.5;
SegmentH = (d / ScaleHeight);
SegmentW = (c / ScaleWidth);
SegmentY2 = (b / ScaleHeight);
/*
* if(minDelta==17||minDelta==18){ hs=1.02; SegmentY2 = (double) (b
* /ScaleWidth); } else if(minDelta==15||minDelta==16){ hs=1.025;
* SegmentY2 = (double) (b /ScaleWidth); } else
* if(minDelta==13||minDelta==14){ hs=1.03; SegmentY2 = (double) (b
* /ScaleWidth); } else if(minDelta==11||minDelta==12){ hs=1.035;
* SegmentY2 = (double) (b /ScaleWidth); } else
* if(minDelta==9||minDelta==10){ hs=1.040; SegmentY2 = (double) (b
* /ScaleWidth); } else if(minDelta==7||minDelta==8){ hs=1.045;
* SegmentY2 = (double) (b /ScaleWidth); } else { SegmentY2 =
* (double) (b / ScaleWidth); }
*/
canvas.drawRect((float) (SegmentX2 - SegmentW / 2),
(float) (SegmentY2 - SegmentH / 2),
(float) (SegmentX2 + SegmentW / 2),
(float) (SegmentY2 + SegmentH / 2), paint);
canvas.restore();
invalidate();
}
}
public Bitmap DecodeFile(String Url) {
try {
URL aURL = new URL(Url);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
Bitmap bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
return bm;
} catch (Exception e) {
return null;
}
}
public void setImage() {
Display display = getWindowManager().getDefaultDisplay();
dwidth = display.getWidth();
dheight = display.getHeight();
// height=Math.round(dwidth*(809.0F/594));
height = Math.round(dwidth * (2921.0F / 2115));
kangoo = DecodeFile("https://ox6a.oxseed.net/services/ocr-archive?action=show_image&document_id=20100629154625261000817AE59111D22744D07CC9EB55708AE4B0000000028a6ba6f1a&mandant=condor&image_output_format=png_gray&max_width=500&max_height=600");
// kangoo=DecodeFile("http://172.16.17.32/RssSample3.1/imgs/IMG.png");
// kangoo=DecodeFile("https://ox6a.oxseed.net/services/ocr-archive?action=show_image&document_id=20100629154835621000826FFBB07EC5DD73C7BCCE07C4DF1C4A600000000b750c91781&mandant=condor&image_output_format=png_gray&max_width=700&max_height=800");
// kangoo = Bitmap.createScaledBitmap(kangoo,320,442, true);
// kangoo = Bitmap.createScaledBitmap(kangoo,594,809, true);
// kangoo = Bitmap.createScaledBitmap(kangoo, dwidth, height, true);
}
private void readRss_Segment() {
try {
URL rssUrl = new URL(
"https://ox6a.oxseed.net/services/ocr-archive?action=show_segmentation&page_nr=0&document_id=20100629154625261000817AE59111D22744D07CC9EB55708AE4B0000000028a6ba6f1a&mandant=condor");
/*
* URL rssUrl = new URL(
* "https://ox6a.oxseed.net/services/ocr-archive?action=show_segmentation&document_id=20100629154835621000826FFBB07EC5DD73C7BCCE07C4DF1C4A600000000b750c91781&mandant=condor"
* );
*/
SAXParserFactory mySAXParserFactory = SAXParserFactory
.newInstance();
SAXParser mySAXParser = mySAXParserFactory.newSAXParser();
XMLReader myXMLReader = mySAXParser.getXMLReader();
RSSHandler_Reader_Segment myRSSHandler_Segment = new RSSHandler_Reader_Segment();
myXMLReader.setContentHandler(myRSSHandler_Segment);
InputSource myInputSource = new InputSource(rssUrl.openStream());
myXMLReader.parse(myInputSource);
myRssFeed_Segment = myRSSHandler_Segment.getFeed();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (myRssFeed_Segment != null) {
int x = myRssFeed_Segment.getList().size();
// TextTest =
// myRssFeed_Segment.getListImageData().get(0).getHeight();
for (int i = 0; i < x; i++) {
SegmentX.add((myRssFeed_Segment.getList().get(i).getX()));
SegmentY.add((myRssFeed_Segment.getList().get(i).getY()));
SegmentHeight.add((myRssFeed_Segment.getList().get(i).getH()));
SegmentWidth.add((myRssFeed_Segment.getList().get(i).getW()));
}
/*
* Calendar c = Calendar.getInstance(); String strCurrentTiime =
* "\n(Time of Reading - " + c.get(Calendar.HOUR_OF_DAY) + " : " +
* c.get(Calendar.MINUTE) + ")\n";
*
* feedTitle.setText(myRssFeed.getX() + strCurrentTiime);
* feedDescribtion.setText(myRssFeed.getY());
* feedPubdate.setText(myRssFeed.getW());
* feedLink.setText(myRssFeed.getH());
*
* MyCustomAdapter adapter = new MyCustomAdapter(this,
* R.layout.rowreader, myRssFeed.getList());
* setListAdapter(adapter);
*/
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_LEFT: {
if (!(setimage == 0)) {
setimage = setimage - 1;
page = setimage + 1;
// pageindex.setText("Page "+page);
Toast.makeText(this, "Page " + page, Toast.LENGTH_SHORT).show();
showProcessBar();
// setImage();
} else {
}
break;
}
case KeyEvent.KEYCODE_DPAD_RIGHT: {
// zoomcontrols.setFocusable(true);
if (setimage < ListFullImage.size() - 1) {
setimage = setimage + 1;
page = setimage + 1;
// pageindex.setText("Page "+page);
Toast.makeText(this, "Page " + page, Toast.LENGTH_SHORT).show();
showProcessBar();
} else {
}
break;
}
case KeyEvent.KEYCODE_BACK: {
Intent intent = new Intent();
Bundle bundle = new Bundle();
CharSequence textmessageLinkProcess;
textmessageLinkProcess = messageLinkProcess;
bundle.putCharSequence("LinkProcess", textmessageLinkProcess);
CharSequence textmessageLinkWB;
textmessageLinkWB = messageLinkWB;
CharSequence textDocName;
textDocName = messageDocName;
bundle.putCharSequence("messageDocName", textDocName);
bundle.putCharSequence("messageLinkWB", textmessageLinkWB);
intent.putExtras(bundle);
intent.setClass(showFullImage.this, ViewImagesActivity.class);
startActivity(intent);
finish();
}
}
return true;
}
private final OnClickListener onZoomOut = new OnClickListener() {
public void onClick(View v) {
setzoom = 1;
x -= 0.2f;
y -= 0.2f;
}
};
private final OnClickListener onZoomIn = new OnClickListener() {
public void onClick(View v) {
setzoom = 1;
x += 0.2f;
y += 0.2f;
}
};
public void reload() {
Intent intent = getIntent();
finish();
startActivity(intent);
}
public void showProcessBar() {
progDailog = ProgressDialog.show(showFullImage.this, "Loading Page...",
"please wait....", true);
new Thread() {
@Override
public void run() {
try {
setImage();
// progDailog.dismiss();
// just doing some long operation
sleep(300);
} catch (Exception e) {
}
handler.sendEmptyMessage(0);
progDailog.dismiss();
}
}.start();
}
public void sleep() {
new Thread() {
@Override
public void run() {
try {
// progDailog.dismiss();
// just doing some long operation
sleep(10000);
} catch (Exception e) {
}
}
}.start();
}
private final Handler handler = new Handler() {
// @Override
@Override
public void handleMessage(Message msg) {
// setTitle("Processing Done");
}
};
private void dumpEvent(MotionEvent event) {
String names[] = { "DOWN", "UP", "MOVE", "CANCEL", "OUTSIDE",
"POINTER_DOWN", "POINTER_UP", "7?", "8?", "9?" };
StringBuilder sb = new StringBuilder();
int action = event.getAction();
int actionCode = action & MotionEvent.ACTION_MASK;
sb.append("event ACTION_").append(names[actionCode]);
if (actionCode == MotionEvent.ACTION_POINTER_DOWN
|| actionCode == MotionEvent.ACTION_POINTER_UP) {
sb.append("(pid ").append(
action >> MotionEvent.ACTION_POINTER_ID_SHIFT);
sb.append(")");
}
sb.append("[");
for (int i = 0; i < event.getPointerCount(); i++) {
sb.append("#").append(i);
sb.append("(pid ").append(event.getPointerId(i));
sb.append(")=").append((int) event.getX(i));
sb.append(",").append((int) event.getY(i));
if (i + 1 < event.getPointerCount()) {
sb.append(";");
}
}
sb.append("]");
// Log.d(TAG, sb.toString());
}
/** Determine the space between the first two fingers */
private float spacing(MotionEvent event) {
float x = event.getX(0) - event.getX(1);
float y = event.getY(0) - event.getY(1);
return FloatMath.sqrt(x * x + y * y);
}
/** Calculate the mid point of the first two fingers */
private void midPoint(PointF point, MotionEvent event) {
float x = event.getX(0) + event.getX(1);
float y = event.getY(0) + event.getY(1);
point.set(x / 2, y / 2);
}
//@Override
public boolean onTouch(View v, MotionEvent event) {
dumpEvent(event);
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
Display display = getWindowManager().getDefaultDisplay();
dwidth = display.getWidth();
dheight = display.getHeight();
touchX = (int) event.getX();
touchY = (int) event.getY();
if (touchX > 5 && touchX < 20 && touchY > 2 && touchY < 40) {
Intent intent = new Intent();
Bundle bundle = new Bundle();
CharSequence textMessage;
CharSequence textDocName;
textMessage = "" + messageLinkWB;
textDocName = "" + messageDocName;
bundle.putCharSequence("messageLinkWB", textMessage);
bundle.putCharSequence("messageDocName", textDocName);
intent.putExtras(bundle);
intent.setClass(showFullImage.this, IndexDoc.class);
startActivity(intent);
finish();
}
savedMatrix.set(matrix);
start.set(event.getX(), event.getY());
if (minDelta == 7 || minDelta == 9 || minDelta == 11
|| minDelta == 13 || minDelta == 15 || minDelta == 17) {
OCR = "Oxseed";
} else if (minDelta == 8 || minDelta == 10 || minDelta == 12
|| minDelta == 14 || minDelta == 16 || minDelta == 18) {
OCR = "Faxfunktionstest";
} else {
OCR = "Unknown";
}
setTitle("W=" + dwidth + " H=" + dheight);
//mQuickAction.show(v);
mode = DRAG;
break;
case MotionEvent.ACTION_POINTER_DOWN:
oldDist = spacing(event);
if (oldDist > 10f) {
savedMatrix.set(matrix);
midPoint(mid, event);
mode = ZOOM;
}
break;
case MotionEvent.ACTION_UP:
upX = (int) event.getX();
upY = (int) event.getY();
spaceX = spaceX + (upX - touchX);
spaceY = spaceY + (upY - touchY);
// setTitle(OCR);
case MotionEvent.ACTION_POINTER_UP:
mode = NONE;
break;
case MotionEvent.ACTION_MOVE:
if (mode == DRAG) {
float newDist = spacing(event); scale = newDist/oldDist;
if(scale==1f){ if(event.getX() - start.x>0){
setTitle("forward image"); } else{
setTitle("backward image"); } } // ...
matrix.set(savedMatrix); matrix.postTranslate(event.getX() -
start.x, event.getY() - start.y);
} else if (mode == ZOOM) {
float newDist = spacing(event);
// Log.d(TAG, "newDist=" + newDist);
if (newDist > 10f) {
matrix.set(savedMatrix);
scale = newDist / oldDist;
spaceX = spaceX * scale / 2;
spaceY = spaceY * scale / 2;
matrix.postScale(scale, scale, mid.x, mid.y);
if (scale < 1) { scale = 1f; setTitle("CANNOT ZOOM IN");
} else { matrix.postScale(scale, scale, mid.x, mid.y); }
}
}
break;
}
// view.setImageMatrix(matrix);
return true; // indicate event was handled
}
public static int getMinValue(double[] numbers) {
double minValue = numbers[0];
int min = 0;
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] < minValue) {
minValue = numbers[i];
min = i;
}
}
return min;
}
public static float getMaxValue(float[] numbers) {
float maxValue = numbers[0];
float maxi = 0;
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] > maxValue) {
maxValue = numbers[i];
maxi = i;
}
}
return maxValue;
}
private void showAddDialog() {
final String TAG = "test";
final Dialog loginDialog = new Dialog(this);
loginDialog.getWindow().setFlags(
WindowManager.LayoutParams.FLAG_BLUR_BEHIND,
WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
loginDialog.setTitle("Change Value");
LayoutInflater li = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View dialogView = li.inflate(R.layout.add_dailog, null);
loginDialog.setContentView(dialogView);
loginDialog.show();
NewValueEditText = (EditText) dialogView.findViewById(R.id.newValue);
NewValueEditText.setText(IndexSelected);
NewValueEditText.setOnClickListener(new View.OnClickListener() {
//@Override
public void onClick(View v) {
NewValueEditText.setText("");
}
});
Button addButton = (Button) dialogView.findViewById(R.id.add_button);
Button cancelButton = (Button) dialogView
.findViewById(R.id.cancel_button);
addButton.setOnClickListener(new OnClickListener() {
// @Override
public void onClick(View v) {
NewValue = NewValueEditText.getText().toString();
loginDialog.dismiss();
FirstListIndex.remove(positionChange);
FirstListIndex.add(positionChange, NewValue);
populateView();
Toast
.makeText(
getBaseContext(),
"You've changed succesfully to new value : "
+ NewValue, Toast.LENGTH_LONG).show();
}
});
cancelButton.setOnClickListener(new OnClickListener() {
// @Override
public void onClick(View v) {
loginDialog.dismiss();
}
});
}
public void populateView() {
ValueListIndex.removeAll(ValueListIndex);
for (int i = 0; i < FirstListIndex.size(); i++) {
ValueListIndex.add(FirstListIndex.get(i));
}
ActionItem creditorItem = new ActionItem(ID_CREDITOR, "Creditor :"
+ ValueListIndex.get(0), getResources().getDrawable(
R.drawable.creditor_icon));
ActionItem amountItem = new ActionItem(ID_AMOUNT, "Amount :"
+ ValueListIndex.get(1), getResources().getDrawable(
R.drawable.amount_icon));
ActionItem currencyItem = new ActionItem(ID_CURRENCY, "Currency :"
+ ValueListIndex.get(2), getResources().getDrawable(
R.drawable.currency_icon));
ActionItem typeItem = new ActionItem(ID_TYPE, "Type :"
+ ValueListIndex.get(3), getResources().getDrawable(
R.drawable.type_icon));
mQuickAction = new QuickAction(this);
mQuickAction.addActionItem(creditorItem);
mQuickAction.addActionItem(amountItem);
mQuickAction.addActionItem(currencyItem);
mQuickAction.addActionItem(typeItem);
mQuickAction
.setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() {
//@Override
public void onItemClick(QuickAction quickAction, int pos,
int actionId) {
ActionItem actionItem = quickAction.getActionItem(pos);
positionChange = pos;
IndexSelected = ValueListIndex.get(pos);
showAddDialog();
Toast.makeText(showFullImage.this,
actionItem.getTitle(), Toast.LENGTH_SHORT)
.show();
}
});
// setup on dismiss listener, set the icon back to normal
mQuickAction.setOnDismissListener(new PopupWindow.OnDismissListener() {
//@Override
public void onDismiss() {
// mMoreIv.setImageResource(R.drawable.ic_list_more);
mQuickAction.dismiss();
}
});
}
}
<file_sep>/src/aexp/explist/ANDROID_RSS_READER.java
package aexp.explist;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import madant.data.protobuf.MandantData;
import madant.data.protobuf.MandantData.Mandant;
import protobuf.com.mandant.MandantData.MandantDefinition.WorkBasket;
import protobuf.data.wbList.WbListData;
import protobuf.data.wbList.WbListData.Wb;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ExpandableListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.text.Html;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleExpandableListAdapter;
import android.widget.TextView;
import android.widget.Toast;
import basketProcessIdInfo.data.protobuf.BasketProcessIdInfo;
import basketProcessIdInfo.data.protobuf.BasketProcessIdInfo.A_Basket_ProcessId_And_Date;
import com.androidrss.preference.RemoverMandant;
import com.sskk.example.bookprovidertest.provider.NewDBAdapter;
import com.test.androidtest.QuickAction;
public class ANDROID_RSS_READER extends ExpandableListActivity implements
Runnable {
private Handler mHandler = new Handler();
private boolean keepRunning = true;
private long interval = 30000;
private int idgroupClicked = 1;
private int id2groupClicked = 1;
private int IDNOGROUP = 1;
private static final String GROUP_NAME = "GroupName";
private static final String GROUP_DELETEBUTTON = "GROUP_DELETEBUTTON";
private static final String GROUP_EDITBUTTON = "GROUP_EDITBUTTON";
private static final String WB_NAME = "workbname";
private static final String TIME_TEMP = "ItemName2";
private static final String COUNT_TEMP = "ItemName3";
private ProgressDialog progDailog;
AlertDialog adSelectWB;
AlertDialog adSelectMandant;
AlertDialog adSelectgroup1;
AlertDialog adSelectGroup;
boolean[] isCheckedWBListfromServer;
boolean[] isCheckedGroupListfromDB;
private final List<String> test = new ArrayList();
boolean isAllChecked = false;
boolean isAllCheckedGroup = false;
boolean isAllCheckedMandant = false;
CharSequence[] arr_CS_allMandants;
CharSequence[] arr_CS_allWBs;
CharSequence[] arr_CS_allGroups;
private TextView view;
private TextView view2;
private TextView group;
private TextView workbasket;
// private TextView data;
private int whichbtn;
private CheckBox cb;
private String IdGroup;
List<String> ListTimeDateGroup = new ArrayList();
// List<List<String>> ListAllListItems = new ArrayList<List<String>>();;
// List<List<String>> ListAllListTimeDate = new ArrayList<List<String>>();;
// List<List<String>> ListAllListCount = new ArrayList<List<String>>();;
// List<List<String>> ListAllListMandantFromMandantAdded = new
// ArrayList<List<String>>();;
List<String> MandantListEnablefromDB = new ArrayList();
List<String> MandantListfromServer = new ArrayList();
boolean[] isCheckedMandantListfromServer;
List<String> MandantListSelectedfromDialog = new ArrayList();
// List<String> WBListfromServer = new ArrayList();
private final List<String> WbListFromServer = new ArrayList();
List<String> WBListEnablefromDB = new ArrayList();
List<String> GroupListEnablefromDB = new ArrayList();
List<String> TimeDateListfromServer = new ArrayList();
List<String> TimeDateListEnablefromDB = new ArrayList();
List<String> ListProcess_PID_FromServer = new ArrayList();
List<String> ListProcess_PID_FromDB = new ArrayList();
List<String> ListProcess_PID_FromReaded = new ArrayList();
List<String> ListProcess_PID_READED_FromDB = new ArrayList();
String[] ListItem;
private EditText mGroupName;
ExpandableListAdapter mAdapter;
private String selectedGrouptoMove;
// private String selectedGrouptoRemove;
private static final int CUSTOM_DIALOG = 1;
private static final int DEFAULT_DIALOG = 2;
private String newGroup;
private static final String TAG = "ExpList";
private int x, y;
private String itemClicked;
private String WBUriClicked;
private String idgrouptoMove;
private int idgrouptoRemove;
private int numberOfGroup;
private int numberOfWBenable;
private String SetAddGroup;
private String messagefromClicked;
private ListView listChecked;
//private List<Item> DataChecked;
List<String> ListItemChecked = new ArrayList();
private final int size_group = 20;
private final int size_workbasket = 18;
private final int size_data = 16;
private int Color_WorkBasket = 0xFFFF0000;
private int Color_TimeStamp = 0xffffffff;
private int Color_GroupName = 0xffffff00;
private int Size_GroupName = 18;
private int Size_WorkBasket = 18;
private int Size_TimeStamp = 18;
String item;
String val2;
private int[] color = { 0xdedede, 0xfff, 0xfff, 0xfff, 0xFFFF0000 };
List<String> IndexGroupExpandable = new ArrayList();
private long[] expandedIds;
private String GroupNameClicked;
// MandantData.MandantCOLLECTION portfolio1;
// List<MandantDefinition> listMandant;
List<Mandant> listMandant;
List<Wb> listWb;
List<WorkBasket> listWBs;
List<A_Basket_ProcessId_And_Date> listProcessIdAndDate;
QuickAction mQuickAction;
private static final int ID_ADD_MANDANT = 1;
private static final int ID_REMOVE_MANDANT = 2;
boolean[] isCheckedMandantListfromDB;
boolean isAllCheckedMandant_Remove = false;
CharSequence[] arr_CS_allMandants_Remove;
List<String> MandantListEnablefromDB_Remove = new ArrayList();
AlertDialog adSelectMandant_Remove;
boolean[] isCheckedMandantListfromDB_Remove;
private final List<String> WBListRemovedfromMandantSelected_Remove = new ArrayList();
private final List<String> MandantListSelectedfromDialog_Remove = new ArrayList();
private long differenceSeconds;
private long differenceSecondsMinutes;
private long differenceSecondsHours;
private long differenceSecondsDays;
private long differenceSecondsMonths;
private long differenceSecondsYears;
private String timerLoop;
private ParserTask parserTask;
private ProgressBar mProgressBar;
private String atest = "a";
private MainCountDown countDown;
NewDBAdapter mDB;
private final int[] RemoveGroup_Icon = { R.drawable.no_group,
R.drawable.removegroupicon, R.drawable.removegroupicon,
R.drawable.removegroupicon, R.drawable.removegroupicon,
R.drawable.removegroupicon, R.drawable.removegroupicon,
R.drawable.removegroupicon, R.drawable.removegroupicon,
R.drawable.removegroupicon, R.drawable.removegroupicon,
R.drawable.removegroupicon, R.drawable.removegroupicon };
private final int[] SortGroup_Icon = { R.drawable.no_group,
R.drawable.down_arrow, R.drawable.down_arrow,
R.drawable.down_arrow, R.drawable.down_arrow,
R.drawable.down_arrow, R.drawable.down_arrow,
R.drawable.down_arrow, R.drawable.down_arrow,
R.drawable.down_arrow, R.drawable.down_arrow,
R.drawable.down_arrow, R.drawable.down_arrow };
private final int[] RenameGroup_Icon = { R.drawable.no_group,
R.drawable.edit, R.drawable.edit,
R.drawable.edit, R.drawable.edit,
R.drawable.edit, R.drawable.edit,
R.drawable.edit, R.drawable.edit,
R.drawable.edit, R.drawable.edit,
R.drawable.edit, R.drawable.edit };
MandantData.MandantList Mandantdata;
WbListData.WbList WBdata;
BasketProcessIdInfo.All_Baskets_ProcessId_And_Date Processdata;
double testint = 0;
String DoneConverted;
String ItemNotConverted = new String();
private String language = "en";
private String StringWBClicked = "";
int totalCountPId;
List<String> ListTestProcessIdDate = new ArrayList();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
getTestProcessDataProtobuf();
Log.w(TAG, "ONCREATE.......");
mDB = new NewDBAdapter(getApplicationContext());
mDB.openDB();
Cursor CurCountItemClicked = mDB.getItemClickByID();
if (CurCountItemClicked.getCount() == 0) {
mDB.insertItemClicked("itemClicked", "ItemNotConverted");
} else {
}
CurCountItemClicked.close();
Cursor curLanguage = mDB.getLanguageByID();
if (curLanguage.getCount() == 0) {
mDB.insertLanguageType("languageName", "en");
} else {
if (curLanguage.moveToFirst()) {
do {
language = curLanguage.getString(1);
} while (curLanguage.moveToNext());
}
}
curLanguage.close();
view = (TextView) findViewById(R.id.tv);
//view2 = (TextView) findViewById(R.id.tv2);
// view2.setText(language);
mGroupName = (EditText) findViewById(R.id.namegroup);
mProgressBar = (ProgressBar) findViewById(R.id.progress_bar);
/*
* for (int i = 0; i < data.length; i++) {
* deleteGroupIcon[i]=BitmapFactory.decodeResource(this.getResources(),
* data[i]);
* deleteGroupIcon2[i]=Bitmap.createScaledBitmap(deleteGroupIcon[i], 32,
* 32, false); }
*/
/*
* if (checkInternetConnection() == true) { view2.setText("Co ket noi");
* } else { view2.setText("Khong co ket noi"); }
*/
getMandantDataProtobuf();
getMandantListFromServer();
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
SharedPreferences myPreference = PreferenceManager
.getDefaultSharedPreferences(this);
String ColorGroupName = new String();
ColorGroupName = ""
+ myPreference.getString("listPrefTextColorGroup", "Black");
if (ColorGroupName.equals("Yellow")) {
Color_GroupName = 0xffffff00;
} else if (ColorGroupName.equals("Red")) {
Color_GroupName = 0xffff0000;
} else if (ColorGroupName.equals("Black")) {
Color_GroupName = 0xff000000;
} else if (ColorGroupName.equals("White")) {
Color_GroupName = 0xffffffff;
} else if (ColorGroupName.equals("Green")) {
Color_GroupName = 0xff00ff00;
} else if (ColorGroupName.equals("Blue")) {
Color_GroupName = 0xff0000ff;
} else if (ColorGroupName.equals("Pink")) {
Color_GroupName = 0xffff00ff;
} else if (ColorGroupName.equals("Turquoise")) {
Color_GroupName = 0xff00ffff;
}
String ColorWorkBasket = new String();
ColorWorkBasket = ""
+ myPreference.getString("listPrefTextColorWorkBasket", "Red");
if (ColorWorkBasket.equals("Yellow")) {
Color_WorkBasket = 0xffffff00;
} else if (ColorWorkBasket.equals("Red")) {
Color_WorkBasket = 0xffff0000;
} else if (ColorWorkBasket.equals("Black")) {
Color_WorkBasket = 0xff000000;
} else if (ColorWorkBasket.equals("White")) {
Color_WorkBasket = 0xffffffff;
} else if (ColorWorkBasket.equals("Green")) {
Color_WorkBasket = 0xff00ff00;
} else if (ColorWorkBasket.equals("Blue")) {
Color_WorkBasket = 0xff0000ff;
} else if (ColorWorkBasket.equals("Pink")) {
Color_WorkBasket = 0xffff00ff;
} else if (ColorWorkBasket.equals("Turquoise")) {
Color_WorkBasket = 0xff00ffff;
}
String ColorTimeStamp = new String();
ColorTimeStamp = ""
+ myPreference.getString("listPrefTextColorTimestamp", "Black");
if (ColorTimeStamp.equals("Yellow")) {
Color_TimeStamp = 0xffffff00;
} else if (ColorTimeStamp.equals("Red")) {
Color_TimeStamp = 0xffff0000;
} else if (ColorTimeStamp.equals("Black")) {
Color_TimeStamp = 0xff000000;
} else if (ColorTimeStamp.equals("White")) {
Color_TimeStamp = 0xffffffff;
} else if (ColorTimeStamp.equals("Green")) {
Color_TimeStamp = 0xff00ff00;
} else if (ColorTimeStamp.equals("Blue")) {
Color_TimeStamp = 0xff0000ff;
} else if (ColorTimeStamp.equals("Pink")) {
Color_TimeStamp = 0xffff00ff;
} else if (ColorTimeStamp.equals("Turquoise")) {
Color_TimeStamp = 0xff00ffff;
}
String textSizeGroupName = new String();
textSizeGroupName = ""
+ myPreference.getString("listPrefTextSizeGroup", "Small");
// Size_GroupName=Integer.parseInt(textSizeGroupName);
if (textSizeGroupName.equals("Medium")) {
Size_GroupName = 20;
} else if (textSizeGroupName.equals("Small")) {
Size_GroupName = 16;
} else if (textSizeGroupName.equals("Very small")) {
Size_GroupName = 13;
} else if (textSizeGroupName.equals("Large")) {
Size_GroupName = 22;
} else if (textSizeGroupName.equals("Xlarge")) {
Size_GroupName = 25;
}
String textSizeWorkBasket = new String();
textSizeWorkBasket = ""
+ myPreference
.getString("listPrefTextSizeWorkBasket", "Small");
// Size_WorkBasket=Integer.parseInt(textSizeWorkBasket);
if (textSizeWorkBasket.equals("Medium")) {
Size_WorkBasket = 20;
} else if (textSizeWorkBasket.equals("Small")) {
Size_WorkBasket = 16;
} else if (textSizeWorkBasket.equals("Very small")) {
Size_WorkBasket = 13;
} else if (textSizeWorkBasket.equals("Large")) {
Size_WorkBasket = 22;
} else if (textSizeWorkBasket.equals("Xlarge")) {
Size_WorkBasket = 25;
}
String textSizeTimeStamp = new String();
textSizeTimeStamp = ""
+ myPreference.getString("listPrefTextSizeTimeStamp", "Small");
// Size_TimeStamp=Integer.parseInt(textSizeTimeStamp);
if (textSizeTimeStamp.equals("Medium")) {
Size_TimeStamp = 20;
} else if (textSizeTimeStamp.equals("Small")) {
Size_TimeStamp = 16;
} else if (textSizeTimeStamp.equals("Very small")) {
Size_TimeStamp = 13;
} else if (textSizeTimeStamp.equals("Large")) {
Size_TimeStamp = 22;
} else if (textSizeTimeStamp.equals("Xlarge")) {
Size_TimeStamp = 25;
}
// run();
}
public void convertWBName(String listconvert, String WbConvert) {
String[] arInfo;
arInfo = listconvert.split(",");
for (int i = 0; i < arInfo.length; i++) {
if (arInfo[i].contains(WbConvert)) {
item = arInfo[i].substring(11);
} else {
}
}
itemClicked = item.replace("}", "");
}
public String convertWBID(String listconvert) {
String mandant = new String();
String WB = new String();
String MandantConverted = new String();
String[] arInfo;
arInfo = listconvert.split("_");
for (int i = 0; i < arInfo.length; i++) {
mandant = arInfo[0];
WB = arInfo[1];
}
MandantConverted = mandant.replace("[", "");
MandantConverted = MandantConverted.replace("]", "");
DoneConverted = WB + "_" + MandantConverted;
return DoneConverted;
}
@Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
Object o1 = this.getExpandableListAdapter().getGroup(groupPosition);
Object o2 = this.getExpandableListAdapter().getChild(groupPosition,
childPosition);
String GroupClicked = o1.toString();
String ChildClicked = o2.toString();
// view2.setText(itemClicked);
convertWBName(ChildClicked, "workbname");
ItemNotConverted = itemClicked;
convertWBID(itemClicked);
itemClicked = DoneConverted;
getProcessDataProtobuf(itemClicked);
ListProcess_PID_FromReaded.clear();
for (A_Basket_ProcessId_And_Date A_Basket_ProcessId_And_Date_Loop : listProcessIdAndDate) {
totalCountPId = A_Basket_ProcessId_And_Date_Loop.getPIdCount();
if (totalCountPId == 0) {
Toast.makeText(ANDROID_RSS_READER.this,
"Sorry, No Data For This Process", Toast.LENGTH_LONG)
.show();
} else {
for (int i = 0; i < A_Basket_ProcessId_And_Date_Loop
.getPIdCount(); i++) {
ListProcess_PID_FromReaded
.add(A_Basket_ProcessId_And_Date_Loop.getPId(i));
}
for (int i = 0; i < ListProcess_PID_FromReaded.size(); i++) {
mDB.changeProcessIsReaded(ListProcess_PID_FromReaded.get(i));
}
String CountTemp = new String();
int unread;
int count = 0;
for (int m = 0; m < A_Basket_ProcessId_And_Date_Loop
.getPIdCount(); m++) {
Cursor cur = mDB.getProcessByAdded(""
+ A_Basket_ProcessId_And_Date_Loop.getPId(m));
count = count + cur.getCount();
cur.close();
}
unread = totalCountPId - count;
CountTemp = ("[" + unread + "/"
+ A_Basket_ProcessId_And_Date_Loop.getPIdCount() + "]");
mDB.UpdateCountWB(CountTemp, ItemNotConverted);
Cursor CurCountClicked = mDB
.getCountClickedWbByName(ItemNotConverted);
int countWBClicked = 0;
if (CurCountClicked.moveToFirst()) {
do {
StringWBClicked = CurCountClicked.getString(0);
countWBClicked = Integer.parseInt(StringWBClicked) + 1;
// count2=count2+1;
} while (CurCountClicked.moveToNext());
}
CurCountClicked.close();
mDB.UpdateCountClickedWB("" + countWBClicked, ItemNotConverted);
mDB.UpdateItemClicked(itemClicked, ItemNotConverted);
Toast.makeText(ANDROID_RSS_READER.this, itemClicked,
Toast.LENGTH_LONG).show();
messagefromClicked = o2.toString();
Intent intent = new Intent();
intent.setClass(ANDROID_RSS_READER.this,
ShowListProcessWithDocs.class);
startActivity(intent);
//finish();
// view2.setText(""+ListProcess_PID_FromReaded.size());
// mDB.closeDB();
setTitle("GOING TO LIST PROCESS FOR WB : " + itemClicked);
}
}
return true;
}
public class MyExpandableListAdapter extends SimpleExpandableListAdapter {
private final List<? extends Map<String, ?>> mGroupData;
private final String[] mGroupFrom;
private final int[] mGroupTo;
private final List<? extends List<? extends Map<String, ?>>> mChildData;
private final String[] mChildFrom;
private final int[] mChildTo;
private Activity context;
public MyExpandableListAdapter(Context context,
List<? extends Map<String, ?>> groupData, int groupLayout,
String[] groupFrom, int[] groupTo,
List<? extends List<? extends Map<String, ?>>> childData,
int childLayout, String[] childFrom, int[] childTo) {
super(context, groupData, groupLayout, groupFrom, groupTo,
childData, childLayout, childFrom, childTo);
mChildData = childData;
mChildFrom = childFrom;
mChildTo = childTo;
mGroupData = groupData;
mGroupFrom = groupFrom;
mGroupTo = groupTo;
}
@Override
public View getChildView(int groupPosition, int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
View v;
if (convertView == null) {
v = newChildView(isLastChild, parent);
} else {
v = convertView;
}
bindView(v, mChildData.get(groupPosition).get(childPosition),
mChildFrom, mChildTo, groupPosition, childPosition);
return v;
}
private void bindView(View view, Map<String, ?> data, String[] from,
int[] to, int groupPosition, int childPosition) {
int len = to.length - 1;
for (int i = 0; i < len; i++) {
TextView v = (TextView) view.findViewById(to[i]);
if (v != null) {
if (to[i] == R.id.r3) {
String UnreadCountString = ((String) data.get(from[i]))
.substring(0, 2).replace("[", "");
if (UnreadCountString.equals("0")) {
v.setText((String) data.get(from[i]));
} else {
v.setTextColor(0xFFFF0000);
v.setText(Html.fromHtml("<b>"
+ (String) data.get(from[i]) + "</b>"));
}
} else {
v.setText((String) data.get(from[i]));
}
if (to[i] == R.id.child) {
v.setTextColor(Color_WorkBasket);
v.setTextSize(Size_WorkBasket);
}
if (to[i] == R.id.r2) {
v.setTextColor(Color_TimeStamp);
v.setTextSize(Size_TimeStamp);
}
}
}
}
@Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
View parentView = convertView;
if (parentView == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
parentView = vi.inflate(R.layout.group_row, null);
}
bindGroupView(parentView, mGroupData.get(groupPosition),
mGroupFrom, mGroupTo, groupPosition);
return parentView;
}
private void bindGroupView(View view, Map<String, ?> Groupdata,
String[] from, int[] to, int groupPosition) {
int len = to.length;
for (int i = 0; i < len; i++) {
TextView v = (TextView) view.findViewById(to[i]);
if (v != null && to[i] == R.id.groupname) {
v.setText((String) Groupdata.get(from[i]));
v.setTextColor(Color_GroupName);
v.setTextSize(Size_GroupName);
}
}
for (int i = 1; i < len; i++) {
final int t = groupPosition;
final int x = t + 1;
IdGroup = "" + x;
Button Button_group = (Button) view.findViewById(to[i]);
// Button_group.setBackgroundColor(color[groupPosition]);
/*
* if(groupPosition==0&&mGroupData.get(groupPosition).containsValue
* ("No_Group")){ Button_group.setBackgroundColor(0xdedede); }
*/
if (Button_group != null && to[i] == R.id.delete_group) {
Button_group.setBackgroundDrawable(getResources()
.getDrawable(RemoveGroup_Icon[groupPosition]));
// Button_group.(deleteGroupIcon2[groupPosition]);
Button_group.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String GroupClicked = mGroupData.get(t).toString();
// setTitle(""+mGroupData.get(t).toString().substring(50));
String[] arInfo;
arInfo = GroupClicked.split(",");
for (int i = 0; i < arInfo.length; i++) {
if (arInfo[i].contains("GroupName")) {
item = arInfo[i].substring(11);
} else {
}
}
itemClicked = item.replace("}", "");
if (itemClicked.equals("No_Group")) {
openDialog1();
} else {
openDialogRemoveGroup();
}
}
});
} else if (Button_group != null && to[i] == R.id.edit_group) {
Button_group.setBackgroundDrawable(getResources()
.getDrawable(RenameGroup_Icon[groupPosition]));
Button_group.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String GroupClicked = mGroupData.get(t).toString();
// setTitle(""+mGroupData.get(t).toString().substring(50));
String[] arInfo;
arInfo = GroupClicked.split(",");
for (int i = 0; i < arInfo.length; i++) {
if (arInfo[i].contains("GroupName")) {
item = arInfo[i].substring(11);
} else {
}
}
itemClicked = item.replace("}", "");
if (itemClicked.equals("No_Group")) {
openDialog2();
} else {
Intent intent = new Intent();
Bundle bundle = new Bundle();
CharSequence textMessage;
textMessage = "" + itemClicked;
bundle.putCharSequence("messageNameGroup",
textMessage);
intent.putExtras(bundle);
intent.setClass(ANDROID_RSS_READER.this,
RenameGroup.class);
startActivity(intent);
//finish();
//mDB.closeDB();
}
}
});
} else if (Button_group != null && to[i] == R.id.sort_group) {
Button_group.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String GroupClicked = mGroupData.get(t).toString();
String[] arInfo;
arInfo = GroupClicked.split(",");
for (int i = 0; i < arInfo.length; i++) {
if (arInfo[i].contains("GroupName")) {
item = arInfo[i].substring(11);
} else {
}
}
itemClicked = item.replace("}", "");
for (int j = 0; j < GroupListEnablefromDB.size(); j++) {
if (GroupListEnablefromDB.get(j).equals(
itemClicked)) {
int num = j + 1;
idgroupClicked = num;
id2groupClicked = num + 1;
}
}
if (idgroupClicked == numberOfGroup) {
} else {
// mDB.openDB();
mDB.changeIDGroup("" + idgroupClicked, "100");
mDB.changeIDGroup("" + id2groupClicked, ""
+ idgroupClicked);
mDB.changeIDGroup("100", "" + id2groupClicked);
updateNumberOfGroupinDB();
mDB.changeIDWB("" + idgroupClicked, "100");
mDB.changeIDWB("" + id2groupClicked, ""
+ idgroupClicked);
mDB.changeIDWB("100", "" + id2groupClicked);
// getListItemForEachGroup();
// showProcessBar();
expandable();
}
}
});
}
}
}
}
public void expandable() {
long startTime = System.currentTimeMillis();
if (numberOfGroup == 0) {
view.setText("There is no group");
} else {
view.setText("There are " + numberOfGroup + " Groups");
// view.setText(""+ListTestProcessIdDate.size()+ListTestProcessIdDate.get(0)+ListTestProcessIdDate.get(1));
}
String[] groups = new String[numberOfGroup];
for (int i = 0; i < numberOfGroup; i++) {
groups[i] = GroupListEnablefromDB.get(i);
}
List<Map<String, String>> groupData = new ArrayList<Map<String, String>>();
for (int j = 0; j < groups.length; ++j) {
Map<String, String> curGroupMap = new HashMap<String, String>();
groupData.add(curGroupMap);
curGroupMap.put(GROUP_NAME, groups[j]);
curGroupMap.put(GROUP_DELETEBUTTON, "");
curGroupMap.put(GROUP_EDITBUTTON, "");
}
List<List<String>> ListAllListItems = new ArrayList<List<String>>();
;
List<List<String>> ListAllListTimeDate = new ArrayList<List<String>>();
;
List<List<String>> ListAllListCount = new ArrayList<List<String>>();
;
int t = numberOfGroup + 1;
for (int i = 1; i < t; i++) {
Cursor c = mDB.getWbBy_InGroup_ID("" + i);
List<String> ListItemGroup = new ArrayList();
List<String> ListTimeDateGroup = new ArrayList();
List<String> ListItemCountGroup = new ArrayList();
if (c.moveToFirst()) {
do {
ListItemGroup.add(c.getString(1));
ListTimeDateGroup.add(c.getString(5));
ListItemCountGroup.add(c.getString(4));
} while (c.moveToNext());
}
ListAllListItems.add(ListItemGroup);
ListAllListTimeDate.add(ListTimeDateGroup);
ListAllListCount.add(ListItemCountGroup);
c.close();
}
List<List<Map<String, String>>> childData = new ArrayList<List<Map<String, String>>>();
for (int i = 0; i < numberOfGroup; i++) {
populateDataExpandableListView(childData, ListAllListItems.get(i),
ListAllListCount.get(i), ListAllListTimeDate.get(i));
}
mAdapter = new MyExpandableListAdapter(this, groupData,
R.layout.group_row, new String[] { GROUP_NAME,
GROUP_DELETEBUTTON, GROUP_EDITBUTTON }, new int[] {
R.id.groupname, R.id.sort_group, R.id.delete_group,
R.id.edit_group }, childData,
R.layout.child_row_screen1, new String[] { WB_NAME, TIME_TEMP,
COUNT_TEMP }, new int[] { R.id.child, R.id.r2, R.id.r3,
R.id.r4 });
setListAdapter(mAdapter);
registerForContextMenu(getExpandableListView());
getExpandableListView().setOnGroupClickListener(
new OnGroupClickListener() {
// @Override
public boolean onGroupClick(ExpandableListView parent,
View v, final int groupPosition, long id) {
atest = "b";
int NumExpandId = groupPosition + 1;
String GroupClicked = getExpandableListView()
.getExpandableListAdapter()
.getGroup(groupPosition).toString();
String[] arInfo;
arInfo = GroupClicked.split(",");
for (int i = 0; i < arInfo.length; i++) {
if (arInfo[i].contains("GroupName")) {
item = arInfo[i].substring(11);
} else {
}
}
GroupNameClicked = item.replace("}", "");
// mDB.openDB();
if (IndexGroupExpandable.get(groupPosition).equals("1")) {
mDB.renameExpandId("1", "0", GroupNameClicked);
updateNumberOfGroupinDB();
} else if (IndexGroupExpandable.get(groupPosition)
.equals("0")) {
mDB.renameExpandId("0", "1", GroupNameClicked);
updateNumberOfGroupinDB();
}
// mDB.closeDB();
setTitle(GroupNameClicked);
return false;
}
});
for (int j = 0; j < numberOfGroup; j++) {
if (IndexGroupExpandable.get(j).equals("0")) {
getExpandableListView().collapseGroup(j);
} else {
getExpandableListView().expandGroup(j);
}
}
// mDB.closeDB();
// view2.setText(""+ListProcess_PID_FromDB.size());
// view2.setText(""+ListProcess_PID_FromDB.size()+ListProcess_PID_FromDB.get(0)+" "+ListProcess_PID_FromDB.get(1)+" "+ListProcess_PID_FromDB.get(2)+" "+ListProcess_PID_FromDB.get(3)+" "+ListProcess_PID_FromDB.get(4));
long endTime = System.currentTimeMillis();
System.out.println("expandable() took " + (endTime - startTime)
+ " MiliSeconds");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, 0, 0, "Create Group").setIcon(R.drawable.add_group);
menu.add(0, 3, 0, "Add Mandant").setIcon(R.drawable.add_mandant);
menu.add(0, 6, 0, "Remove Mandant").setIcon(R.drawable.recycle_icon);
menu.add(1, 4, 1, "Refresh").setIcon(R.drawable.refresh);
menu.add(1, 5, 1, "Move To Group").setIcon(R.drawable.move);
menu.add(1, 1, 1, "More").setIcon(R.drawable.setting);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case 0:
addgroup();
break;
case 2:
// RemoveGroupDialog();
break;
case 1:
startActivity(new Intent(ANDROID_RSS_READER.this,
com.androidrss.preference.Setting.class));
// finish();
//mDB.closeDB();
break;
case 3:
updateMandantinDB();
// MandantListfromServer.removeAll(MandantListEnablefromDB);
String[] ssMandants = new String[MandantListfromServer.size()];
isCheckedMandantListfromServer = new boolean[MandantListfromServer
.size()];
for (int i = 0; i < MandantListfromServer.size(); i++) {
ssMandants[i] = MandantListfromServer.get(i);
isCheckedMandantListfromServer[i] = false;
// MandantListfromServer.removeAll(MandantListEnablefromDB);
}
arr_CS_allMandants = ssMandants;
openDialogWithMandants();
// populateQuickActionDialog();
// mQuickAction.show(v);
break;
case 4:
reload();
break;
case 5:
moveToGroup();
break;
case 6:
Intent intent = new Intent();
intent.setClass(ANDROID_RSS_READER.this, RemoverMandant.class);
startActivity(intent);
//finish();
// System.exit(0);
// mDB.closeDB();
break;
}
return false;
}
public void addgroup() {
int x = GroupListEnablefromDB.size();
Intent intent = new Intent();
ArrayList<String> al = new ArrayList<String>();
for (int i = 0; i < x; i++) {
al.add(GroupListEnablefromDB.get(i));
}
setTitle("" + x);
Bundle bundle = new Bundle();
bundle.putStringArrayList("temp1", al);
intent.putExtras(bundle);
intent.setClass(ANDROID_RSS_READER.this, AddGroup.class);
startActivity(intent);
//mDB.closeDB();
//finish();
setTitle("Going To Add Group View");
}
public void moveToGroup() {
Intent intent = new Intent();
intent.setClass(ANDROID_RSS_READER.this, MoveToGroup.class);
startActivity(intent);
// finish();
// mDB.closeDB();
setTitle("Going To Move To Group View");
}
public void openDialogWithMandants() {
adSelectMandant = new AlertDialog.Builder(this)
.setTitle("Select Mandant to Add :")
.setIcon(R.drawable.star_big_on)
.setMultiChoiceItems(arr_CS_allMandants,
isCheckedMandantListfromServer,
new DialogInterface.OnMultiChoiceClickListener() {
public void onClick(DialogInterface dialog,
int whichButton, boolean isChecked) {
// THEM Code:
if (isCheckedMandantListfromServer[whichButton] = true) {
MandantListSelectedfromDialog
.add(arr_CS_allMandants[whichButton]
.toString());
// MandantListUriSelectedfromDialog.add(MandantListUrifromServer.get(whichButton));
} else {
isCheckedMandantListfromServer[whichButton] = isChecked;
}
}
})
.setPositiveButton(R.string.check_all,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
// THEM COde cho Check All
if (isAllCheckedMandant) {
isAllCheckedMandant = false;
} else {
isAllCheckedMandant = true;
}
setCheckAllMandant();
}
})
.setNeutralButton("Add", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/*
* countDown = new MainCountDown(180, 180);
* countDown.start();
*/
/*
* mProgressBar.setVisibility(View.VISIBLE); countDown =
* new MainCountDown(180, 180); countDown.start();
*/
updateMandantinDB();
addMandanttoDB();
/*
* MandantListSelectedfromDialog.clear(); countDown =
* new MainCountDown(180, 180); countDown.start();
*/
// reload();
updateNumberOfGroupinDB();
updateMandantinDB();
getWBListFromUri();
updateWBinDB();
addWBtoDB();
expandable();
// reload();
/*
* updateMandantinDB(); getWBListFromUri();
* updateWBinDB(); addWBtoDB();
* getListItemForEachGroup(); expandable();
*/
MandantListSelectedfromDialog.clear();
}
})
.setNegativeButton(R.string.alert_dialog_cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
MandantListSelectedfromDialog.clear();
}
}).show();
}
public void setCheckAllMandant() {
if (isAllCheckedMandant) {
for (int i = 0; i < MandantListfromServer.size(); i++) {
isCheckedMandantListfromServer[i] = true;
MandantListSelectedfromDialog.add(MandantListfromServer.get(i));
}
} else {
for (int i = 0; i < MandantListfromServer.size(); i++) {
isCheckedMandantListfromServer[i] = false;
}
}
openDialogWithMandants();
}
public void openDialogWithWBs() {
test.clear();
adSelectWB = new AlertDialog.Builder(this)
.setTitle(R.string.alert_dialog_multi_choice)
.setIcon(R.drawable.alert)
.setMultiChoiceItems(arr_CS_allWBs, isCheckedWBListfromServer,
new DialogInterface.OnMultiChoiceClickListener() {
public void onClick(DialogInterface dialog,
int whichButton, boolean isChecked) {
if (isCheckedWBListfromServer[whichButton] = true) {
test.add(arr_CS_allWBs[whichButton]
.toString());
} else {
isCheckedWBListfromServer[whichButton] = isChecked;
}
}
})
.setPositiveButton(R.string.check_all,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
if (isAllChecked) {
isAllChecked = false;
} else {
isAllChecked = true;
}
setCheckAllWB();
}
})
.setNeutralButton(R.string.alert_dialog_ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
addSelectedItems();
}
})
.setNegativeButton(R.string.alert_dialog_cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
}
}).show();
}
public void setCheckAllWB() {
if (isAllChecked) {
for (int i = 0; i < WbListFromServer.size(); i++) {
isCheckedWBListfromServer[i] = true;
test.add(WbListFromServer.get(i));
}
} else {
for (int i = 0; i < WbListFromServer.size(); i++) {
isCheckedWBListfromServer[i] = false;
}
}
openDialogWithWBs();
}
public void getTestProcessDataProtobuf() {
long startTime = System.currentTimeMillis();
try {
InputStream is = new URL(
"http://192.168.16.121:8080/moxseed/spring/basketapp?basketIds=inbox_ani23012012,storage_ani2301201&responseType=protobuf&action=getbasketsprocessidslist")
.openStream();
Processdata = BasketProcessIdInfo.All_Baskets_ProcessId_And_Date
.parseFrom(is);
listProcessIdAndDate = Processdata.getABasketProcessIdAndDateList();
for (A_Basket_ProcessId_And_Date A_Basket_ProcessId_And_Date_Loop : listProcessIdAndDate) {
ListTestProcessIdDate.add(A_Basket_ProcessId_And_Date_Loop.getBasketId());
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long endTime = System.currentTimeMillis();
System.out.println("getProcessDataProtobuf() took "
+ (endTime - startTime) + " MiliSeconds");
}
public void getProcessDataProtobuf(String WorkBasket) {
long startTime = System.currentTimeMillis();
try {
InputStream is = new URL(
"http://192.168.16.121:8080/moxseed/spring/basketapp?basketIds="
+ WorkBasket
+ "&responseType=protobuf&action=getbasketsprocessidslist")
.openStream();
Processdata = BasketProcessIdInfo.All_Baskets_ProcessId_And_Date
.parseFrom(is);
listProcessIdAndDate = Processdata.getABasketProcessIdAndDateList();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long endTime = System.currentTimeMillis();
System.out.println("getProcessDataProtobuf() took "
+ (endTime - startTime) + " MiliSeconds");
}
public void getMandantDataProtobuf() {
long startTime = System.currentTimeMillis();
try {
InputStream is = new URL(
// "https://my-ea.oxseed.net/oxseedadmin/ext/oxplorer?content=mandantList&login=admin&pass=<PASSWORD>")
"http://192.168.16.121:8888/oxseedadmin/ext/oxplorer?content=mandantList&login=admin&pass=<PASSWORD>&format=pbf")
.openStream();
Mandantdata = MandantData.MandantList.parseFrom(is);
listMandant = Mandantdata.getMandantList();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
// view2.setText("CONNECT TIME OUT");
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long endTime = System.currentTimeMillis();
System.out.println("getMandantDataProtobuf take : "
+ (endTime - startTime) + " (MiliSeconds)");
}
public void getMandantListFromServer() {
long startTime = System.currentTimeMillis();
try {
for (Mandant mandant : listMandant) {
MandantListfromServer.add(mandant.getId());
}
} catch (Exception e) {
Log.e("TRANG TRADER 1", "Exception getting ProtocolBuffer data", e);
}
long endTime = System.currentTimeMillis();
System.out.println("getMandantListFromServer() took "
+ (endTime - startTime) + " MiliSeconds");
}
public void getWbDataProtobuf(String Mandant) {
long startTime = System.currentTimeMillis();
try {
InputStream is = new URL("http://192.168.16.121:8888/" + Mandant
+ "/ext/oxplorer?content=wbList&login=admin&pass=<PASSWORD>&format=pbf")
.openStream();
WBdata = WbListData.WbList.parseFrom(is);
listWb = WBdata.getWbList();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
for (Wb wbLoop : listWb) {
// WbListFromServer.add(wbLoop.getId() + "_" + Mandant);
WbListFromServer
.add("[" + Mandant + "]" + "_" + wbLoop.getId());
}
} catch (Exception e) {
/*WbListFromServer
.add("[" + Mandant + "]" + "_Null");*/
Log.e("TRANG TRADER 2", "Exception getting ProtocolBuffer data", e);
}
long endTime = System.currentTimeMillis();
System.out.println("getWbDataProtobuf() took " + (endTime - startTime)
+ " MiliSeconds");
}
public void getWBListFromUri() {
long startTime = System.currentTimeMillis();
try {
for (int i = 0; i < MandantListSelectedfromDialog.size(); i++) {
getWbDataProtobuf(MandantListSelectedfromDialog.get(i));
}
} catch (Exception e) {
Log.e("TRANG TRADER 3 ", "Exception getting ProtocolBuffer data", e);
Log.w(TAG, "Wblist size : " + WbListFromServer.size());
}
long endTime = System.currentTimeMillis();
System.out.println("getWBListFromUri() took " + (endTime - startTime)
+ " MiliSeconds");
}
// ------------------------ADD WORKBASKET TO DB----------------------------
public void addWBtoDB() {
SimpleDateFormat df = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
java.util.Date timestamp = null;
String CountTemp = new String();
for (int i = 0; i < WbListFromServer.size(); i++) {
if (WBListEnablefromDB.contains(WbListFromServer.get(i))) {
} else {
convertWBID(WbListFromServer.get(i));
getProcessDataProtobuf(DoneConverted);
try {
for (A_Basket_ProcessId_And_Date A_Basket_ProcessId_And_Date_Loop : listProcessIdAndDate) {
timestamp = df.parse(A_Basket_ProcessId_And_Date_Loop
.getLastBuildDate());
int unread;
int count = 0;
int total = A_Basket_ProcessId_And_Date_Loop
.getPIdCount();
for (int m = 0; m < A_Basket_ProcessId_And_Date_Loop
.getPIdCount(); m++) {
Cursor cur = mDB.getProcessByAdded(""
+ A_Basket_ProcessId_And_Date_Loop
.getPId(m));
count = count + cur.getCount();
cur.close();
}
if (total<count) {
unread=0;
}
else {
unread = total - count;
}
CountTemp = ("["
+ unread
+ "/"
+ A_Basket_ProcessId_And_Date_Loop
.getPIdCount() + "]");
}
} catch (java.text.ParseException e) {
e.printStackTrace();
}
getSecondsDifference(timestamp);
if (differenceSeconds <= 0) {
timerLoop = "Just Now";
} else if (differenceSecondsYears >= 1) {
timerLoop = differenceSecondsYears + " Year ago";
} else if (differenceSecondsMonths >= 1
&& differenceSecondsMonths <= 12) {
timerLoop = differenceSecondsMonths + " Months ago";
} else if (differenceSecondsDays >= 1
&& differenceSecondsDays <= 30) {
timerLoop = differenceSecondsDays + " Days ago";
} else if (differenceSecondsHours >= 1
&& differenceSecondsHours <= 24) {
timerLoop = differenceSecondsHours + " Hours ago";
} else if (differenceSecondsMinutes >= 1
&& differenceSecondsMinutes <= 60) {
timerLoop = differenceSecondsMinutes + " Minutes ago";
}
mDB.insertNewWorkBasket(WbListFromServer.get(i), "1", "1",
CountTemp, timerLoop);
getListProcess_PID();
for (int m = 0; m < ListProcess_PID_FromServer.size(); m++) {
mDB.insertNewProcess(ListProcess_PID_FromServer.get(m),
"type_id", "type_name", "0");
}
updateWBinDB();
}
}
}
public void getListProcess_PID() {
ListProcess_PID_FromServer.clear();
try {
for (A_Basket_ProcessId_And_Date A_Basket_ProcessId_And_Date_Loop : listProcessIdAndDate) {
for (int i = 0; i < A_Basket_ProcessId_And_Date_Loop
.getPIdCount(); i++) {
ListProcess_PID_FromServer
.add(A_Basket_ProcessId_And_Date_Loop.getPId(i));
// mDB.insertUnreadCountProcess(""+A_Basket_ProcessId_And_Date_Loop.getPIdCount());
}
}
} catch (Exception e) {
Log.e("DayTrader", "Exception getting ProtocolBuffer data", e);
}
}
public void updateWBinDB() {
WBListEnablefromDB.clear();
// mDB.openDB();
Cursor c = mDB.getWbByEnable("1");
if (c.moveToFirst()) {
do {
WBListEnablefromDB.add(c.getString(1));
} while (c.moveToNext());
}
c.close();
updateProcess_PIDinDB();
}
public void updateProcess_PIDinDB() {
ListProcess_PID_FromDB.clear();
Cursor c = mDB.getProcessByAdded("0");
if (c.moveToFirst()) {
do {
ListProcess_PID_FromDB.add(c.getString(1));
} while (c.moveToNext());
}
c.close();
}
public void addSelectedItems() {
updateWBinDB();
addWBtoDB();
updateNumberOfGroupinDB();
// getListItemForEachGroup();
expandable();
}
public void addGrouptoDB(String groupname) {
int num = numberOfGroup + 1;
mDB.insertNewGroup(groupname, "1", "1", "" + num);
updateNumberOfGroupinDB();
}
public void updateNumberOfGroupinDB() {
long startTime = System.currentTimeMillis();
// mDB.openDB();
GroupListEnablefromDB.clear();
IndexGroupExpandable.clear();
// mDB.openDB();
Cursor cursor = mDB.getGroupByEnable("1");
numberOfGroup = cursor.getCount();
for (int i = 0; i < numberOfGroup; i++) {
int num = i + 1;
Cursor c = mDB.getGroupByPosition("1", "" + num);
if (c.moveToFirst()) {
do {
GroupListEnablefromDB.add(c.getString(1));
} while (c.moveToNext());
}
c.close();
}
cursor.close();
Cursor cursorExpand = mDB.getExpand("1");
if (cursorExpand.moveToFirst()) {
do {
IndexGroupExpandable.add(cursorExpand.getString(3));
} while (cursorExpand.moveToNext());
}
cursorExpand.close();
long endTime = System.currentTimeMillis();
System.out.println("updateNumberOfGroupinDB() took "
+ (endTime - startTime) + " MiliSeconds");
}
public void addMandanttoDB() {
for (int x = 0; x < MandantListSelectedfromDialog.size(); x++) {
mDB.insertNewMandant(MandantListSelectedfromDialog.get(x), "1");
}
}
public void updateMandantinDB() {
MandantListEnablefromDB.clear();
// mDB.openDB();
Cursor c = mDB.getMandantByAdded("1");
if (c.moveToFirst()) {
do {
MandantListEnablefromDB.add(c.getString(1));
} while (c.moveToNext());
}
c.close();
MandantListfromServer.removeAll(MandantListEnablefromDB);
}
public void ChangeIdWB(int idgroup, int NumOfGroup) {
int extra;
extra = NumOfGroup - idgroup;
for (int i = 0; i < extra; i++) {
int j = i + 1;
int OldID = idgroup + j;
int NewID = idgroup + i;
mDB.changeIDWB("" + OldID, "" + NewID);
// mDB.closeDB();
}
}
public void showProcessBar() {
progDailog = ProgressDialog.show(ANDROID_RSS_READER.this,
"Processing data...", "Refreshesing, please wait....", true);
new Thread() {
@Override
public void run() {
try {
sleep(1500);
} catch (Exception e) {
}
handler.sendEmptyMessage(0);
progDailog.dismiss();
}
}.start();
}
private final Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
}
};
private int count;
public void deleteAll() {
mDB.DropDatabase(getApplicationContext());
}
public void populateDataExpandableListView(
List<List<Map<String, String>>> childData,
List<String> ListItemWbName, List<String> ListItemCountTemp,
List<String> ListItemTimeTemp) {
List<Map<String, String>> children = new ArrayList<Map<String, String>>();
children = new ArrayList<Map<String, String>>();
for (int j = 0; j < ListItemWbName.size(); ++j) {
Map<String, String> curChildMap = new HashMap<String, String>();
children.add(curChildMap);
curChildMap.put(WB_NAME, ListItemWbName.get(j));
// curChildMap.put(TIME_TEMP, "9 months ago");
curChildMap.put(TIME_TEMP, ListItemTimeTemp.get(j));
curChildMap.put(COUNT_TEMP, ListItemCountTemp.get(j));
}
childData.add(children);
}
private void openDialog1() {
new AlertDialog.Builder(this)
.setTitle("Report")
.setIcon(R.drawable.dialog_warning)
.setMessage("You cannot Remove No_Group")
.setNegativeButton(R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialoginterface, int i) {
}
})
.show();
}
private void openDialog2() {
new AlertDialog.Builder(this)
.setTitle("Report")
.setIcon(R.drawable.dialog_warning)
.setMessage("You cannot Rename No_Group")
.setNegativeButton(R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialoginterface, int i) {
}
})
.show();
}
private void openDialog_CheckConnection() {
new AlertDialog.Builder(this)
.setTitle("Report")
.setIcon(R.drawable.dialog_warning)
.setMessage("Problem with your Connection..Try again later")
.setNegativeButton(R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialoginterface, int i) {
}
})
.show();
}
private void openDialogRemoveGroup() {
new AlertDialog.Builder(this)
.setTitle("Report")
.setIcon(R.drawable.dialog_warning)
.setMessage(
"Are you sure to remove group " + itemClicked + " ?")
.setNeutralButton(R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialoginterface, int i) {
for (int j = 0; j < GroupListEnablefromDB
.size(); j++) {
if (GroupListEnablefromDB.get(j).equals(
itemClicked)) {
int num = j + 1;
idgrouptoRemove = num;
}
}
// removeGroup(itemClicked, idgrouptoRemove);
// mDB.openDB();
/*
* mDB.removeGroup(selectedGrouptoRemove,
* idgrouptoRemove);
*/
int t = idgrouptoRemove + 1;
int n = numberOfGroup + 1;
/*
* for (int k = t; k < n; k++) { int m = k - 1;
* mDB.changeIDGroup("" + k, "" + m); }
*/
mDB.deleteGroup(itemClicked);
/*
* ChangeIdWB(idgrouptoRemove,
* GroupListEnablefromDB.size());
*/
updateWBinDB();
updateNumberOfGroupinDB();
// getListItemForEachGroup();
expandable();
// reload();
}
})
.setNegativeButton(R.string.alert_dialog_cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
}
}).show();
}
public long getSecondsDifference(java.util.Date timestamp) {
final Calendar calendar = Calendar.getInstance(Locale.getDefault());
int offset = TimeZone.getDefault().getOffset(timestamp.getTime());
if (TimeZone.getDefault().inDaylightTime(
Calendar.getInstance().getTime())) {
offset = offset - TimeZone.getDefault().getDSTSavings();
}
final long referenceSeconds = (timestamp.getTime() + offset) / 1000;
final long currentTimeSeconds = (calendar.getTimeInMillis()) / 1000;
differenceSeconds = (currentTimeSeconds - referenceSeconds);
differenceSecondsMinutes = differenceSeconds / 60;
differenceSecondsHours = differenceSecondsMinutes / 60;
differenceSecondsDays = differenceSecondsHours / 24;
differenceSecondsMonths = differenceSecondsDays / 30;
differenceSecondsYears = differenceSecondsMonths / 12;
return differenceSeconds;
}
@Override
protected void onStart() {
super.onStart();
parserTask = new ParserTask();
parserTask.execute();
}
private class ParserTask extends AsyncTask<String, Integer, Long> {
public ParserTask() {
}
@Override
protected void onPreExecute() {
}
@Override
protected Long doInBackground(String... params) {
updateNumberOfGroupinDB();
if (numberOfGroup == 0) {
newGroup = "No_Group";
addGrouptoDB(newGroup);
} else {
updateMandantinDB();
getWBListFromUri();
updateWBinDB();
addWBtoDB();
}
return null;
}
@Override
protected void onPostExecute(Long arg0) {
expandable();
//setTitle("" + testint);
Log.w(TAG, "MAndantInDB : " + MandantListEnablefromDB.size());
// view2.setText("WBListEnablefromDB Size :"+
// WBListEnablefromDB.size());
Log.w(TAG, "numberOfGroup : " + numberOfGroup);
mProgressBar.setVisibility(View.GONE);
// mDB.closeDB();
}
}
public class MainCountDown extends CountDownTimer {
public MainCountDown(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
@Override
public void onFinish() {
parserTask = new ParserTask();
parserTask.execute();
}
@Override
public void onTick(long millisUntilFinished) {
}
}
public void reload() {
mDB.closeDB();
startActivity(getIntent());
// finish();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK: {
mDB.closeDB();
// finish();
System.exit(0);
}
}
return false;
}
private Boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni != null && ni.isConnected()) {
return true;
}
return false;
}
private boolean checkInternetConnection() {
try {
Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec("ping fr.yahoo.com -c 1"); // other
// servers,
// for
// example
proc.waitFor();
int exit = proc.exitValue();
if (exit == 0) { // normal exit
return true;
} else { // abnormal exit, so decide that the server is not
// reachable
}
} catch (Exception e) {
}
return false;
}
/*
* public void loadtime() { testint =testint+ Math.random(); }
*/
public void run() {
new Thread(new Runnable() {
public void run() {
while (keepRunning) {
try {
if (!keepRunning)
return;
Thread.sleep(interval);
if (!keepRunning)
return;
mHandler.post(new Runnable() {
// @Override
public void run() {
if (!keepRunning)
return;
// showProcessBar();
expandable();
}
});
} catch (Exception e) {
// TODO: handle exception
}
}
}
}).start();
if (!keepRunning)
return;
}
public synchronized void stopRunning() {
this.keepRunning = false;
}
@Override
protected void onDestroy() {
stopRunning();
super.onDestroy();
}
@Override
protected void onStop() {
stopRunning();
super.onStop();
}
@Override
protected void onPause() {
stopRunning();
super.onPause();
}
}<file_sep>/src/aexp/explist/MainActivity.java
package aexp.explist;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.DecelerateInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import com.hots.transition3d.Rotate3dAnimation;
public class MainActivity extends Activity {
private LinearLayout layout;
private ImageView imageview;
private Context mContext;
private ProgressBar mProgressBar;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
mProgressBar = (ProgressBar) findViewById(R.id.progress_bar);
mContext = this;
layout = (LinearLayout) findViewById(R.id.main_activity_layout);
imageview = (ImageView) findViewById(R.id.main_activity_image);
MainCountDown countdown = new MainCountDown(4000, 4000);
countdown.start();
}
public class MainCountDown extends CountDownTimer {
public MainCountDown(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
@Override
public void onFinish() {
applyRotation(0, 90);
}
@Override
public void onTick(long millisUntilFinished) {
}
}
private void applyRotation(float start, float end) {
final float centerX = layout.getWidth() / 2.0f;
final float centerY = layout.getHeight() / 2.0f;
final Rotate3dAnimation rotation = new Rotate3dAnimation(start, end,
centerX, centerY, 310.0f, true);
rotation.setDuration(700);
rotation.setFillAfter(true);
rotation.setInterpolator(new AccelerateInterpolator());
rotation.setAnimationListener(new DisplayNextView());
layout.startAnimation(rotation);
}
private final class DisplayNextView implements Animation.AnimationListener {
public void onAnimationStart(Animation animation) {
}
public void onAnimationEnd(Animation animation) {
layout.post(new SwapViews());
}
public void onAnimationRepeat(Animation animation) {
}
}
private final class SwapViews implements Runnable {
public void run() {
final float centerX = layout.getWidth() / 2.0f;
final float centerY = layout.getHeight() / 2.0f;
Rotate3dAnimation rotation;
imageview.setVisibility(View.GONE);
rotation = new Rotate3dAnimation(90, 180, centerX, centerY, 310.0f,
false);
rotation.setDuration(700);
rotation.setFillAfter(true);
rotation.setInterpolator(new DecelerateInterpolator());
layout.startAnimation(rotation);
Intent intent = new Intent(mContext,ANDROID_RSS_READER.class);
mContext.startActivity(intent);
finish();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
System.gc();
}
}<file_sep>/src/com/sskk/example/bookprovidertest/provider/NewDBAdapter.java
package com.sskk.example.bookprovidertest.provider;
import java.util.Locale;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;
import android.provider.BaseColumns;
import android.util.Log;
public class NewDBAdapter extends ContentProvider implements BaseColumns {
public static final String MANDANT_ID = "mandantId";
public static final String MANDANT_NAME = "mandantName";
public static final String MANDANT_ENABLE = "mandantEnable";
public static final String GROUP_ID = "groupId";
public static final String GROUP_NAME = "groupName";
public static final String GROUP_ENABLE = "groupEnable";
public static final String GROUP_EXPAND = "group_expand";
public static final String GROUP_POSITION = "groupPosition";
public static final String WB_ID = "wBId";
public static final String WB_NAME = "wBName";
public static final String WB_CLICK = "wb_click";
public static final String WB_INGROUP_ID = "wB_InGroup_ID";
public static final String WB_ENABLE = "wB_Enable";
public static final String WB_TOTAL_COUNT = "wB_Total_Count";
public static final String WB_TIME_DATE = "wB_Time_Date";
public static final String PROCESS_ID = "processId";
public static final String PROCESS_PID = "process_pid";
public static final String PROCESS_TYPE_ID = "process_typeid";
public static final String PROCESS_TYPE_NAME = "process_typename";
public static final String PROCESS_IS_READ = "process_isread";
public static final String DOCTYPE_ID = "docId";
public static final String DOCTYPE_OF_WB = "doc_typeOfWb";
public static final String DOCTYPE_ID_NAME = "doc_type_IdName";
public static final String DOCTYPE_COUNT_INDEX = "doc_type_count_index";
public static final String DOCTYPE_INGROUP_ID = "doc_typeInGroupID";
public static final String INDEX_ID = "index_Id";
public static final String INDEX_TYPE_ID = "index_typeId";
public static final String INDEX_TYPE_VALUE = "index_typeValue";
public static final String INDEX_OF_WB = "index_typeOfWb";
public static final String INDEX_INGROUP_ID = "index_typeInGroupID";
public static final String TRANSLATE_ID = "translateId";
public static final String TRANSLATE_IN_WB = "translateInWb";
public static final String TRANSLATE_TYPE = "translateType";
public static final String TRANSLATE_WORD = "translateWord";
public static final String TRANSLATE_VALUE = "translateValue";
public static final String LANGUAGE_NAME = "languageName";
public static final String LANGUAGE_TYPE = "languageType";
public static final String ITEM_CLICKED = "itemClicked";
public static final String ITEM_NOT_CONVERTED = "itemNotConverted";
public static final String ITEM_NUM = "ItemNum";
private static final String TAG = "NewDBAdapter";
public static final String COMMAND_ID = "commandId";
public static final String COMMAND_OF_WB = "commandOfWb";
public static final String COMMAND_NAME = "commandName";
public static final String DB_NAME = "OXPLORER";
private static final String DB_TABLE_MANDANT = "Mandants";
private static final String DB_TABLE_GROUP = "Groups";
private static final String DB_TABLE_WORKBASKET = "WorkBaskets";
private static final String DB_TABLE_PROCESS = "Process";
private static final String DB_TABLE_DOCTYPE = "Doctype";
private static final String DB_TABLE_INDEXTYPE = "Indextype";
private static final String DB_TABLE_TRANSLATE = "Translate";
private static final String DB_TABLE_LANGUAGE = "Language";
private static final String DB_TABLE_ITEM_CLICK = "ItemClick";
private static final String DB_TABLE_COMMAND = "Command";
private static final int DB_VERSION = 2;
private static final String DB_CREATE_MANDANT = "create table Mandants (mandantId integer primary key autoincrement, "
+ "mandantName text, " + "mandantEnable text);";
private static final String DB_CREATE_GROUP = "create table Groups (groupId integer primary key autoincrement, "
+ "groupName text, "
+ "groupEnable text, "
+ "group_expand text, "
+ "groupPosition text);";
private static final String DB_CREATE_WORKBASKET = "create table WorkBaskets (wBId integer primary key autoincrement, "
+ "wBName text, "
+ "wb_click text, "
+ "wB_InGroup_ID text, "
+ "wB_Enable text, "
+ "wB_Total_Count text, " + "wB_Time_Date text);";
private static final String DB_CREATE_PROCESS = "create table Process (processId integer primary key autoincrement, "
+ "process_pid text, "
+ "process_typeid text, "
+ "process_typename text, " + "process_isread text);";
private static final String DB_CREATE_DOCTYPE = "create table DocType (docId integer primary key autoincrement, "
+ "doc_typeOfWb text, "
+ "doc_type_IdName text, "
+ "doc_type_count_index text, " + "doc_typeInGroupID text);";
private static final String DB_CREATE_INDEXTYPE = "create table IndexType (index_Id integer primary key autoincrement, "
+ "index_typeId text, "
+ "index_typeValue text, "
+ "index_typeOfWb text, " + "index_typeInGroupID text);";
private static final String DB_CREATE_TRANSLATE = "create table Translate (translateId integer primary key autoincrement, "
+ "translateInWb text, "
+ "translateType text, "
+ "translateWord text, "
+ "translateValue text);";
private static final String DB_CREATE_LANGUAGE = "create table Language (languageId integer primary key autoincrement, "
+ "languageName text, "
+ "languageType text);";
private static final String DB_CREATE_ITEM_CLICKED = "create table ItemClick (itemClickId integer primary key autoincrement, "
+ "itemClicked text, "
+ "itemNotConverted text, "
+ "ItemNum text);";
private static final String DB_CREATE_COMMAND = "create table Command (commandId integer primary key autoincrement, "
+ "commandOfWb text, "
+ "commandName text);";
private final Context context;
private SQLiteDatabase db;
private DatabaseHelper DBHelper;
public NewDBAdapter(Context _context) {
this.context = _context;
}
private DatabaseHelper mOpenHelper;
private static class DatabaseHelper extends SQLiteOpenHelper {
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
try {
Log.w(TAG, "Creating DB.......");
db.execSQL(DB_CREATE_MANDANT);
db.execSQL(DB_CREATE_GROUP);
db.execSQL(DB_CREATE_WORKBASKET);
db.execSQL(DB_CREATE_PROCESS);
db.execSQL(DB_CREATE_DOCTYPE);
db.execSQL(DB_CREATE_INDEXTYPE);
db.execSQL(DB_CREATE_TRANSLATE);
db.execSQL(DB_CREATE_LANGUAGE);
db.execSQL(DB_CREATE_ITEM_CLICKED);
db.execSQL(DB_CREATE_COMMAND);
} catch (SQLException e) {
// TODO: handle exception
Log.w(TAG, "ERROR Creating DB.......");
e.printStackTrace();
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
Log.w(TAG, "Updating DB.......");
db.execSQL("DROP TABLE IF EXISTS Mandants");
db.execSQL("DROP TABLE IF EXISTS Groups");
db.execSQL("DROP TABLE IF EXISTS WorkBaskets");
db.execSQL("DROP TABLE IF EXISTS Process");
db.execSQL("DROP TABLE IF EXISTS DocType");
db.execSQL("DROP TABLE IF EXISTS Translates");
onCreate(db);
}
public DatabaseHelper(Context _context) {
// TODO Auto-generated constructor stub
super(_context, DB_NAME, null, DB_VERSION);
}
}
public NewDBAdapter openDB() throws SQLException {
DBHelper = new DatabaseHelper(context);
db = DBHelper.getWritableDatabase();
return this;
}
public void closeDB() {
Log.w(TAG, "DB is closing....");
db.close();
}
// -------------------------MANDANT------------------------------
public long insertNewMandant(String mandantName, String MandantAdded) {
ContentValues cv_mandant = new ContentValues();
cv_mandant.put(MANDANT_NAME, mandantName);
cv_mandant.put(MANDANT_ENABLE, MandantAdded);
return db.insert(DB_TABLE_MANDANT, null, cv_mandant);
}
public boolean deleteMandant(String mandantName) {
return db.delete(DB_TABLE_MANDANT, MANDANT_NAME + "=?",
new String[] { mandantName }) > 0;
}
public boolean updateMandant(long id, String mandantName,
String mandantEnable, String email) {
ContentValues cv_mandant = new ContentValues();
cv_mandant.put(MANDANT_ID, id);
cv_mandant.put(MANDANT_NAME, mandantName);
cv_mandant.put(MANDANT_ENABLE, mandantEnable);
return db.update(DB_TABLE_MANDANT, cv_mandant, MANDANT_ID + " = " + id,
null) > 0;
}
public Cursor getAllMandant() {
return db.query(DB_TABLE_MANDANT, new String[] { MANDANT_ID,
MANDANT_NAME, MANDANT_ENABLE }, null, null, null, null, null);
}
public Cursor getMandantById(long id) {
Cursor c = db.query(DB_TABLE_MANDANT, new String[] { MANDANT_ID,
MANDANT_NAME, MANDANT_ENABLE }, MANDANT_ID + " = " + id, null,
null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
public Cursor getMandantByName(String mandantName) {
Cursor c = db.query(DB_TABLE_MANDANT, new String[] { MANDANT_ID,
MANDANT_NAME, MANDANT_ENABLE }, MANDANT_NAME + " = '"
+ mandantName + "'", null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
public Cursor getMandantByAdded(String mandantAdded) {
Cursor c = db.query(DB_TABLE_MANDANT, new String[] { MANDANT_ID,
MANDANT_NAME, MANDANT_ENABLE }, MANDANT_ENABLE + " = '"
+ mandantAdded + "'", null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// ------------------------GROUP-----------------------------
public long insertNewGroup(String groupName, String groupEnable,
String groupExpand, String groupPosition) {
ContentValues cv_group = new ContentValues();
cv_group.put(GROUP_NAME, groupName);
cv_group.put(GROUP_ENABLE, groupEnable);
cv_group.put(GROUP_EXPAND, groupExpand);
cv_group.put(GROUP_POSITION, groupPosition);
return db.insert(DB_TABLE_GROUP, null, cv_group);
}
public boolean deleteGroup(String groupName) {
return db.delete(DB_TABLE_GROUP, GROUP_NAME + "=?",
new String[] { groupName }) > 0;
}
public boolean updateGroup(long id, String groupName, String groupEnable,
String groupExpand, String groupPosition) {
ContentValues cv_group = new ContentValues();
cv_group.put(GROUP_ID, id);
cv_group.put(GROUP_NAME, groupName);
cv_group.put(GROUP_ENABLE, groupEnable);
cv_group.put(GROUP_EXPAND, groupExpand);
cv_group.put(GROUP_POSITION, groupPosition);
return db.update(DB_TABLE_GROUP, cv_group, GROUP_ID + " = " + id, null) > 0;
}
public boolean changeIDGroup(String OldIDGroup, String NewIDGroup) {
ContentValues cv_group = new ContentValues();
cv_group.put(GROUP_POSITION, NewIDGroup);
return db.update(DB_TABLE_GROUP, cv_group, GROUP_ENABLE + "=?"
+ " and " + GROUP_POSITION + "=?", new String[] { "1",
OldIDGroup }) > 0;
}
public boolean renameGroup(String GroupOldName, String GroupNewName) {
ContentValues cv_group = new ContentValues();
cv_group.put(GROUP_NAME, GroupNewName);
return db.update(DB_TABLE_GROUP, cv_group, GROUP_NAME + "=?",
new String[] { GroupOldName }) > 0;
}
public boolean removeGroup(String groupremoved, int idgroup) {
ContentValues cv_group = new ContentValues();
cv_group.put(GROUP_ENABLE, "0");
cv_group.put(GROUP_POSITION, "1");
return db.update(DB_TABLE_GROUP, cv_group, GROUP_NAME + "=?" + " and "
+ GROUP_POSITION + "=?", new String[] { groupremoved,
"" + idgroup }) > 0;
}
public boolean renameExpandId(String ExpandOldId, String ExpandNewId,
String GroupName) {
ContentValues cv_group = new ContentValues();
cv_group.put(GROUP_EXPAND, ExpandNewId);
return db.update(DB_TABLE_GROUP, cv_group, GROUP_NAME + "=?" + " and "
+ GROUP_EXPAND + "=?", new String[] { GroupName, ExpandOldId }) > 0;
}
public Cursor getGrouptById(long id) {
Cursor c = db.query(DB_TABLE_GROUP, new String[] { GROUP_ID,
GROUP_NAME, GROUP_ENABLE, GROUP_EXPAND, GROUP_POSITION },
GROUP_ID + " = " + id, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
public Cursor getGroupByName(String groupName) {
Cursor c = db.query(DB_TABLE_GROUP, new String[] { GROUP_ID,
GROUP_NAME, GROUP_ENABLE, GROUP_EXPAND, GROUP_POSITION },
GROUP_NAME + " = '" + groupName + "'", null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
public Cursor getGroupByEnable(String groupEnable) {
Cursor c = db.query(DB_TABLE_GROUP, new String[] { GROUP_ID,
GROUP_NAME, GROUP_ENABLE, GROUP_EXPAND, GROUP_POSITION },
GROUP_ENABLE + " = '" + groupEnable + "'", null, null, null,
null);
if (c != null) {
c.moveToFirst();
}
return c;
}
public Cursor getGroupByPosition(String groupEnable, String Position) {
Cursor c = db.query(DB_TABLE_GROUP, new String[] { GROUP_ID,
GROUP_NAME, GROUP_ENABLE, GROUP_EXPAND, GROUP_POSITION },
GROUP_ENABLE + "=?" + " and " + GROUP_POSITION + "=?",
new String[] { "1", Position }, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
public Cursor getExpand(String groupEnable) {
Cursor c = db.query(DB_TABLE_GROUP, new String[] { GROUP_ID,
GROUP_NAME, GROUP_ENABLE, GROUP_EXPAND, GROUP_POSITION },
GROUP_ENABLE + " = '" + groupEnable + "'", null, null, null,
null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// ------------------------WORKBASKET-----------------------------
public long insertNewWorkBasket(String workBasketName,String inGroupID,
String wbEnable, String totalCount, String timeDate) {
ContentValues cv_wb = new ContentValues();
cv_wb.put(WB_NAME, workBasketName);
cv_wb.put(WB_CLICK, "0");
cv_wb.put(WB_INGROUP_ID, inGroupID);
cv_wb.put(WB_ENABLE, wbEnable);// bo di
cv_wb.put(WB_TOTAL_COUNT, totalCount);// bo di
cv_wb.put(WB_TIME_DATE, timeDate);// bo di
return db.insert(DB_TABLE_WORKBASKET, null, cv_wb);
}
public boolean deleteWorkBasket(String workBasketName) {
return db.delete(DB_TABLE_WORKBASKET, WB_NAME + "=?",
new String[] { workBasketName }) > 0;
}
public boolean updateWorkBasket(long id, String workBasketName,
String inGroupID, String wbEnable, String totalCount,
String timeDate) {
ContentValues cv_wb = new ContentValues();
cv_wb.put(WB_ID, id);
cv_wb.put(WB_NAME, workBasketName);
cv_wb.put(WB_INGROUP_ID, inGroupID);
cv_wb.put(WB_ENABLE, wbEnable);
cv_wb.put(WB_TOTAL_COUNT, totalCount);
cv_wb.put(WB_TIME_DATE, timeDate);
return db.update(DB_TABLE_WORKBASKET, cv_wb, WB_ID + " = " + id, null) > 0;
}
public boolean changeIDWB(String OldIDGroup, String NewIDGroup) {
ContentValues cv_wb = new ContentValues();
cv_wb.put(WB_INGROUP_ID, NewIDGroup);
return db.update(DB_TABLE_WORKBASKET, cv_wb, WB_ENABLE + "=?" + " and "
+ WB_INGROUP_ID + "=?", new String[] { "1", OldIDGroup }) > 0;
}
public boolean UpdateCountWB(String Count, String workBasketName) {
ContentValues cv_wb = new ContentValues();
cv_wb.put(WB_TOTAL_COUNT, Count);
return db.update(DB_TABLE_WORKBASKET, cv_wb, WB_NAME + "=?",
new String[] { workBasketName }) > 0;
}
public boolean moveItemToGroup(String Wbname, String IDGroup) {
ContentValues cv_wb = new ContentValues();
cv_wb.put(WB_INGROUP_ID, IDGroup);
return db.update(DB_TABLE_WORKBASKET, cv_wb, WB_ENABLE + "=?" + " and "
+ WB_NAME + "=?", new String[] { "1", Wbname }) > 0;
}
public Cursor getWbBy_InGroup_ID(String Wb_InGroup_Id) {
Cursor c = db.query(DB_TABLE_WORKBASKET, new String[] { WB_ID, WB_NAME,
WB_INGROUP_ID, WB_ENABLE, WB_TOTAL_COUNT, WB_TIME_DATE },
WB_ENABLE + "=?" + " and " + WB_INGROUP_ID + "=?",
new String[] { "1", Wb_InGroup_Id }, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
public Cursor getWbByEnable(String WbEnable) {
Cursor c = db.query(DB_TABLE_WORKBASKET, new String[] { WB_ID, WB_NAME,
WB_INGROUP_ID, WB_ENABLE, WB_TOTAL_COUNT, WB_TIME_DATE },
WB_ENABLE + " = " + WbEnable, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
public Cursor getWbByName(String wBName) {
Cursor c = db.query(DB_TABLE_WORKBASKET, new String[] { WB_ID, WB_NAME,
WB_INGROUP_ID, WB_ENABLE, WB_TOTAL_COUNT, WB_TIME_DATE },
WB_NAME + " = '" + wBName + "'", null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
public Cursor getCountClickedWbByName(String wBName) {
Cursor c = db.query(DB_TABLE_WORKBASKET, new String[] { WB_CLICK, WB_NAME},
WB_NAME + " = '" + wBName + "'", null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
public boolean UpdateCountClickedWB(String Count, String workBasketName) {
ContentValues cv_wb = new ContentValues();
cv_wb.put(WB_CLICK, Count);
return db.update(DB_TABLE_WORKBASKET, cv_wb, WB_NAME + "=?",
new String[] { workBasketName }) > 0;
}
// ------------------------PROCESS-----------------------------
public long insertNewProcess(String process_pid, String Process_TypeId,
String Process_TypeName, String Process_IsRead) {
ContentValues cv_process = new ContentValues();
cv_process.put(PROCESS_PID, process_pid);
cv_process.put(PROCESS_TYPE_ID, Process_TypeId);
cv_process.put(PROCESS_TYPE_NAME, Process_TypeName);
cv_process.put(PROCESS_IS_READ, Process_IsRead);
return db.insert(DB_TABLE_PROCESS, null, cv_process);
}
public boolean changeProcessIsReaded(String Process_PID) {
ContentValues cv_process = new ContentValues();
cv_process.put(PROCESS_IS_READ, "1");
return db.update(DB_TABLE_PROCESS, cv_process, PROCESS_IS_READ + "=?"
+ " and " + PROCESS_PID + "=?",
new String[] { "0", Process_PID }) > 0;
}
public Cursor getProcessByAdded(String Process_PID) {
Cursor c = db.query(DB_TABLE_PROCESS, new String[] { PROCESS_ID,
PROCESS_PID, PROCESS_TYPE_ID, PROCESS_TYPE_NAME,
PROCESS_IS_READ }, PROCESS_PID + "=?" + " and "
+ PROCESS_IS_READ + "=?", new String[] { Process_PID, "1" },
null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// ------------------------DOCTYPE-----------------------------
public long insertNewDocTypeID(String WBID, String DocTypeIdName,
String CountIndex, String InGroupID) {
ContentValues cv_doctype = new ContentValues();
cv_doctype.put(DOCTYPE_OF_WB, WBID);
cv_doctype.put(DOCTYPE_ID_NAME, DocTypeIdName);
cv_doctype.put(DOCTYPE_COUNT_INDEX, CountIndex);
cv_doctype.put(DOCTYPE_INGROUP_ID, InGroupID);
return db.insert(DB_TABLE_DOCTYPE, null, cv_doctype);
}
public Cursor getDocTypeIdNameByGroupIdAndWbID(String WbID, String InGroupID) {
Cursor c = db.query(DB_TABLE_DOCTYPE, new String[] {
DOCTYPE_OF_WB, DOCTYPE_ID_NAME, DOCTYPE_COUNT_INDEX,
DOCTYPE_INGROUP_ID }, DOCTYPE_OF_WB + "=?" + " and "
+ DOCTYPE_INGROUP_ID + "=?", new String[] { WbID, InGroupID },
null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
public Cursor getDocTypeIdNameByWbID(String WbID) {
Cursor c = db.query(DB_TABLE_DOCTYPE, new String[] { DOCTYPE_ID,
DOCTYPE_OF_WB, DOCTYPE_ID_NAME, DOCTYPE_COUNT_INDEX,
DOCTYPE_INGROUP_ID }, DOCTYPE_OF_WB + "=?",
new String[] { WbID }, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// ------------------------INDEX-----------------------------
public long insertNewIndexTypeID(String WbID, String IndexTypeID,
String IndexTypeValue, String InGroupID) {
ContentValues cv_indextype = new ContentValues();
cv_indextype.put(INDEX_OF_WB, WbID);
cv_indextype.put(INDEX_TYPE_ID, IndexTypeID);
cv_indextype.put(INDEX_TYPE_VALUE, IndexTypeValue);
cv_indextype.put(INDEX_INGROUP_ID, InGroupID);
return db.insert(DB_TABLE_INDEXTYPE, null, cv_indextype);
}
public Cursor getIndexTypeIdByGroupIdAndWbID(String WbID, String InGroupID) {
Cursor c = db.query(DB_TABLE_INDEXTYPE, new String[] {INDEX_OF_WB, INDEX_TYPE_ID,
INDEX_TYPE_VALUE,INDEX_INGROUP_ID }, INDEX_OF_WB
+ "=?" + " and " + INDEX_INGROUP_ID + "=?", new String[] {
WbID, InGroupID }, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// ------------------------TRANSLATE-----------------------------
public long insertNewTranslate(String translate_WB,String translate_type,
String translate_word, String translate_value) {
ContentValues cv_translate = new ContentValues();
cv_translate.put(TRANSLATE_IN_WB, translate_WB);
cv_translate.put(TRANSLATE_TYPE, translate_type);
cv_translate.put(TRANSLATE_WORD, translate_word);
cv_translate.put(TRANSLATE_VALUE, translate_value);
return db.insert(DB_TABLE_TRANSLATE, null, cv_translate);
}
public Cursor getTranslateByTypeAndWordAndWb(String Type, String Word, String Wb) {
Cursor c = db.query(DB_TABLE_TRANSLATE, new String[] {TRANSLATE_IN_WB, TRANSLATE_TYPE,
TRANSLATE_WORD, TRANSLATE_VALUE }, TRANSLATE_TYPE + "=?"
+ " and " + TRANSLATE_WORD + "=?"+ " and " + TRANSLATE_IN_WB + "=?", new String[] { Type, Word,Wb },
null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
public Cursor getTranslateByWbAndType(String WB,String Type) {
Cursor c = db.query(DB_TABLE_TRANSLATE, new String[] { TRANSLATE_IN_WB,TRANSLATE_TYPE,
TRANSLATE_VALUE }, TRANSLATE_IN_WB + "=?"+ " and " + TRANSLATE_TYPE + "=?",
new String[] { WB,Type }, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// ------------------------LANGUAGE-----------------------------
public long insertLanguageType(String language_name,String language_type) {
ContentValues cv_language = new ContentValues();
cv_language.put(LANGUAGE_NAME, language_name);
cv_language.put(LANGUAGE_TYPE, language_type);
return db.insert(DB_TABLE_LANGUAGE, null, cv_language);
}
public boolean UpdateLanguageDB(String language) {
ContentValues cv_language = new ContentValues();
cv_language.put(LANGUAGE_TYPE, language);
return db.update(DB_TABLE_LANGUAGE, cv_language, LANGUAGE_NAME + "=?",
new String[] { "languageName" }) > 0;
}
public Cursor getLanguageByID() {
Cursor c = db.query(DB_TABLE_LANGUAGE, new String[] { LANGUAGE_NAME,
LANGUAGE_TYPE },LANGUAGE_NAME + "=?", new String[] {"languageName"}, null,
null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// ------------------------ITEMCLICKED----------------------------
public long insertItemClicked(String item_name,String itemNotConverted) {
ContentValues cv_itemClicked = new ContentValues();
cv_itemClicked.put(ITEM_CLICKED, item_name);
cv_itemClicked.put(ITEM_NOT_CONVERTED, itemNotConverted);
cv_itemClicked.put(ITEM_NUM, "1");
return db.insert(DB_TABLE_ITEM_CLICK, null, cv_itemClicked);
}
public boolean UpdateItemClicked(String item_name,String itemNotConverted) {
ContentValues cv_itemClicked = new ContentValues();
cv_itemClicked.put(ITEM_CLICKED, item_name);
cv_itemClicked.put(ITEM_NOT_CONVERTED, itemNotConverted);
return db.update(DB_TABLE_ITEM_CLICK, cv_itemClicked, ITEM_NUM + "=?",
new String[] { "1" }) > 0;
}
public Cursor getItemClickByID() {
Cursor c = db.query(DB_TABLE_ITEM_CLICK, new String[] { ITEM_CLICKED,
ITEM_NOT_CONVERTED,ITEM_NUM },ITEM_NUM + "=?", new String[] {"1"}, null,
null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// ------------------------COMMAND----------------------------
public long insertCommand(String Wb,String CommandName) {
ContentValues cv_command = new ContentValues();
cv_command.put(COMMAND_OF_WB, Wb);
cv_command.put(COMMAND_NAME, CommandName);
return db.insert(DB_TABLE_COMMAND, null, cv_command);
}
public Cursor getCommandNameByWb(String Wb) {
Cursor c = db.query(DB_TABLE_COMMAND, new String[] { COMMAND_OF_WB,
COMMAND_NAME},COMMAND_OF_WB + "=?", new String[] {Wb}, null,
null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
@Override
public int delete(Uri uri, String where, String[] whereArgs) {
// TODO Auto-generated method stub
return 0;
}
@Override
public String getType(Uri uri) {
return null;
}
@Override
public Uri insert(Uri uri, ContentValues values) {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean onCreate() {
// TODO Auto-generated method stub
// return false;
mOpenHelper = new DatabaseHelper(getContext());
return true;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
return null;
}
@Override
public int update(Uri uri, ContentValues values, String where,
String[] whereArgs) {
// TODO Auto-generated method stub
return 0;
}
/*
* public void deleteAll(){ try{ DBHelper = new DatabaseHelper(context); db
* = DBHelper.getWritableDatabase(); db.delete(DB_NAME, null, null);
*
* }catch(Exception e){} }
*/
public void DropDatabase(Context context) {
context.deleteDatabase(db.getPath());
}
}<file_sep>/src/aexp/explist/ShowListPageWithImage.java
package aexp.explist;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.FloatMath;
import android.view.Display;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import com.android.TestSegment.RSSFeed_Reader_Segment;
import com.android.TestSegment.RSSHandler_Reader_Segment;
public class ShowListPageWithImage extends Activity implements OnTouchListener {
private ProgressDialog progDailog;
private RSSFeed_Reader_Segment myRssFeed_Segment = null;
private final String imageUrl = "";
// private ImageView imgView;
private String fullimage;
String t;
// DemoView demoview;
String LinkDocument;
// ZoomControls zoomcontrols;
ImageView comicview;
float zoomfactor;
Context context;
Bitmap kangoo;
private int scaledHeight;
private int scaledWidth;
private int widthAndroid;
private int heightAndroid;
float touchX = 0;
float touchY = 0;
float upX = 0;
float upY = 0;
float curx = 0;
float cury = 0;
float x = 1.0f;
float y = 1.0f;
float dx = 0;
float dy = 0;
private static final int INVALID_POINTER_ID = -1;
private float mPosX;
private float mPosY;
private float mLastTouchX;
private float mLastTouchY;
String[] arInfo;
private final int mActivePointerId = INVALID_POINTER_ID;
private int setzoom;
private final List<String> ListSmallImage = new ArrayList();
private final List<String> ListFullImage = new ArrayList();
private final List<String> ListLinkImage = new ArrayList();
private String messageLinkProcess;
private String messageLinkWB;
private final int setimage = 0;
private String setZoom = "0";
private int page;
// TextView pageindex;
private String TitleDoc;
float downXValue;
float currentX;
float downYValue;
float currentY;
private String move;
private ScaleGestureDetector mScaleDetector;
private float mScaleFactor = 1.f;
Matrix matrix = new Matrix();
Matrix savedMatrix = new Matrix();
// We can be in one of these 3 states
static final int NONE = 0;
static final int DRAG = 1;
static final int ZOOM = 2;
int mode = NONE;
// Remember some things for zooming
PointF start = new PointF();
PointF mid = new PointF();
float oldDist = 1f;
private String TextTest;
private final List<String> SegmentX = new ArrayList();;
private final List<String> SegmentY = new ArrayList();;
private final List<String> SegmentWidth = new ArrayList();;
private final List<String> SegmentHeight = new ArrayList();;
private float dw, dh, newX, newY;
private float spaceX = 0;
private float spaceY = 0;
private float deltaX;
private float m, n, o, p;
float scale;
float tl = 1;
float oldwidth, OldHeight;
float newwidth;
float dodai;
String text1 = "Creditor : Coca cola";
String text2 = "Type : bill";
String text3 = "Currency : USD";
String text4 = "Amount: 100,00€";
int img1 = R.drawable.i_symbol;
Drawable img2;
String modeview = "1";
private final Integer[] Imgid = { R.drawable.i1, R.drawable.i2,
R.drawable.i3 };
private final String[] LinkImage = {
"http://174.143.148.49/RssSample3.1/mandant/imgs/I1.png",
"http://192.168.127.12/RssSample3.1/mandant/imgs/I3.png",
"http://192.168.127.12/RssSample3.1/mandant/imgs/I2.png" };
int position;
private Gallery gallery;
private ImageView imgView;
private int HeightGallery;
private Button Option;
String extStorageDirectory;
Bitmap bm;
private final RSSFeed_Reader_Segment myRssFeed = null;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.showfullimage);
readRss_Segment();
LinearLayout layMain = (LinearLayout) this.findViewById(R.id.myScreen);
Bundle bundle = this.getIntent().getExtras();
CharSequence textMessage3 = bundle.getCharSequence("messageLinkWB");
messageLinkWB = "" + textMessage3;
position = 0;
// imgView = (ImageView) findViewById(R.id.ImageView01);
// imgView.setImageResource(Imgid[0]);
gallery = (Gallery) findViewById(R.id.examplegallery);
gallery.setAdapter(new AddImgAdp(this));
HeightGallery = gallery.getHeight();
gallery.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position,
long id) {
setImage(position);
ShowListPageWithImage.this.position = position;
}
});
extStorageDirectory = Environment.getExternalStorageDirectory()
.toString();
kangoo = DecodeFile(LinkImage[position]);
/*
* Bundle bundle = this.getIntent().getExtras(); CharSequence
* textMessage1 = bundle.getCharSequence("LinkDocument");
* LinkDocument=""+textMessage1; CharSequence textTitleDoc =
* bundle.getCharSequence("TitleDoc"); TitleDoc=""+textTitleDoc;
* setTitle(TitleDoc); // setTitle( TextTest); CharSequence textMessage2
* = bundle.getCharSequence("LinkProcess");
* messageLinkProcess=""+textMessage2;
*
* CharSequence textMessage3 = bundle.getCharSequence("messageLinkWB");
* messageLinkWB=""+textMessage3;
*
* getLinkThumnailForEachDocument(LinkDocument); for(int
* i=0;i<ListLinkImage.size();i++){ String h;
* h=ListLinkImage.get(i).replace("[","-");
* //h=LinkProcess.get(i).replace("]",""); arInfo = h.split("-");
* ListSmallImage.add(arInfo[0]);
* ListFullImage.add(arInfo[1].replace("]","")); page=setimage+1;
*
* }
*/
// layMain.addView(gallery);
// layMain.addView(Option);
setImage(position);
layMain.setOnTouchListener(this);
layMain.addView(new Mens(this));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, 1, 0, "Setting").setIcon(R.drawable.setting);
/*
* menu.add(0, 2, 0,"Remove Group") .setIcon(R.drawable.icon_delete);
*/
menu.add(0, 0, 0, "Add Group").setIcon(R.drawable.add_group);
menu.add(1, 3, 1, "Add Mandant").setIcon(R.drawable.add_mandant);
menu.add(1, 4, 1, "Refresh").setIcon(R.drawable.refresh);
menu.add(1, 5, 1, "Move To Group").setIcon(R.drawable.move);
// .setIcon(R.drawable.add_mandant);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case 0:
break;
}
return false;
}
public void getLinkThumnailForEachDocument(String uri) {
for (int i = 0; i < LinkImage.length; i++) {
ListLinkImage.add(LinkImage[i]);
}
}
public class Mens extends View implements OnTouchListener {
Button undo_Btn;
TextView tview;
Paint textPaint;
public Mens(Context context) {
super(context);
mScaleDetector = new ScaleGestureDetector(context,
new ScaleListener());
setFocusable(true);
undo_Btn = new Button(context);
undo_Btn.measure(150, 150); // size of view
int width = undo_Btn.getMeasuredWidth();
int height = undo_Btn.getMeasuredHeight();
int right = 100;
int top = 200;
undo_Btn.layout(right, top, right + width, top + height);
// img1=;
undo_Btn.setBackgroundDrawable(getResources().getDrawable(img1));
undo_Btn.setVisibility(VISIBLE);
undo_Btn.setId(10);
undo_Btn.setPadding(50, 50, 50, 50);
undo_Btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
setTitle("QUICK ACTION");
}
});
/*
* tview= new TextView(context); tview.measure(400,400);
* tview.setText("AAAA");
*/
}
public class ScaleListener extends
ScaleGestureDetector.SimpleOnScaleGestureListener {
@Override
public boolean onScale(ScaleGestureDetector detector) {
mScaleFactor *= detector.getScaleFactor();
// Don't let the object get too small or too large.
mScaleFactor = Math.max(0.1f, Math.min(mScaleFactor, 5.0f));
invalidate();
return true;
}
}
@Override
protected void onDraw(Canvas canvas) {
Paint paint = new Paint();
Paint paint2 = new Paint();
paint.isFilterBitmap();
canvas.drawColor(Color.BLACK);
// Matrix zoommatrix=new Matrix();
// zoommatrix.setScale(mScaleFactor, mScaleFactor);
// canvas.translate(mPosX, mPosY);
// canvas.scale(mScaleFactor, mScaleFactor);
canvas.drawBitmap(kangoo, matrix, paint);
undo_Btn.draw(canvas);
Paint paint3 = new Paint();
paint3.setColor(Color.BLACK);
paint3.setTextSize(20);
canvas.drawText(text1, 0, 80, paint3);
Paint paint4 = new Paint();
paint4.setColor(Color.BLACK);
paint4.setTextSize(20);
canvas.drawText(text2, 0, 100, paint4);
Paint paint5 = new Paint();
paint5.setColor(Color.BLACK);
paint5.setTextSize(20);
canvas.drawText(text3, 0, 120, paint5);
Paint paint6 = new Paint();
paint6.setColor(Color.BLACK);
paint6.setTextSize(20);
canvas.drawText(text4, 0, 140, paint6);
// canvas.scale(1, 1);
paint.setColor(Color.RED);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(3);
paint2.setColor(Color.BLUE);
paint2.setStyle(Paint.Style.STROKE);
paint2.setStrokeWidth(3);
int x = myRssFeed_Segment.getList().size();
for (int i = 0; i < x; i++) {
/*
* float a=Math.round(Float.parseFloat(SegmentX.get(i))/4.33);
* float b=Math.round(Float.parseFloat(SegmentY.get(i))/4.42);
* float
* c=Math.round(Float.parseFloat(SegmentWidth.get(i))/4.33);
* float
* d=Math.round(Float.parseFloat(SegmentHeight.get(i))/4.42);
*/
float a = Float.parseFloat(SegmentX.get(i));
float b = Float.parseFloat(SegmentY.get(i));
float c = Float.parseFloat(SegmentWidth.get(i));
float d = Float.parseFloat(SegmentHeight.get(i));
newY = touchY + dh - spaceY;
newX = touchX + dw - spaceX;
if ((newX > a) && (newX < (a + c)) && (newY > b)
&& (newY < (b + d)))
{
// canvas.drawRect(touchX,touchY-50,touchX+100,touchY+120,
// paint);
// RectF rect = new RectF(0,40,40,40);
// canvas.drawRect(rect, paint);
canvas.drawRect(newX - a, d - (newY - b), c - (newX - a),
newY - b, paint);
m = a;
n = b;
o = c;
p = d;
// canvas.drawRect(touchX-80,touchY-60,40+touchX,touchY-20,
// paint2);
// canvas.drawRect(Float.parseFloat(SegmentWidth.get(i))/2,Float.parseFloat(SegmentHeight.get(i))/2,Float.parseFloat(SegmentWidth.get(i))/2,Float.parseFloat(SegmentHeight.get(i))/2,
// paint);
} else {
// setTitle("K VE DUOC ");
}
}
// canvas.drawRect(touchX-40,touchY+40,40+touchX,touchY-40, paint);
canvas.restore();
invalidate();
int tx = Math.round(newX);
int ty = Math.round(newY);
// setTitle(""+SegmentX.get(0).toString());
// setTitle("m= "+m+"; n= "+n+"; o="+o+";p= "+p);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// ImageView view = (ImageView) v;
// Dump touch event to log
dumpEvent(event);
final View v = null;
// Handle touch events here...
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
touchX = (int) event.getX();
touchY = (int) event.getY();
savedMatrix.set(matrix);
start.set(event.getX(), event.getY());
// setTitle(""+touchX+"--"+touchY);
if (modeview.equals("1")) {
if (touchX > 5 && touchX < 20 && touchY > 2 && touchY < 40) {
// img1=R.drawable.white_small;
// setTitle("BBBBB");
showProcessBar4();
// text1="Amount : 100,000$";
// tview.setText("AAAA");
}
} else if (modeview.equals("2")) {
if (touchX > 5 && touchX < 20 && touchY > 2 && touchY < 40) {
showProcessBar();
}
}
// Log.d(TAG, "mode=DRAG");
mode = DRAG;
break;
case MotionEvent.ACTION_POINTER_DOWN:
oldDist = spacing(event);
// Log.d(TAG, "oldDist=" + oldDist);
if (oldDist > 10f) {
savedMatrix.set(matrix);
midPoint(mid, event);
mode = ZOOM;
// Log.d(TAG, "mode=ZOOM");
}
break;
case MotionEvent.ACTION_UP:
upX = (int) event.getX();
upY = (int) event.getY();
spaceX = spaceX + (upX - touchX);
spaceY = spaceY + (upY - touchY);
case MotionEvent.ACTION_POINTER_UP:
mode = NONE;
// Log.d(TAG, "mode=NONE");
break;
case MotionEvent.ACTION_MOVE:
if (mode == DRAG) {
if (setZoom.equals("0")) {
// if(scale==1f){
if (event.getX() - start.x > 0) {
// setImage3();
// showProcessBar3();
setTitle("Backward image");
} else {
setTitle("Forward image");
// setImage2();
// showProcessBar2();
}
// }
} else {
// ...
matrix.set(savedMatrix);
matrix.postTranslate(event.getX() - start.x, event
.getY()
- start.y);
setTitle("move DRAG");
}
} else if (mode == ZOOM) {
float newDist = spacing(event);
tl = newwidth / oldwidth;
if (newDist > 10f) {
matrix.set(savedMatrix);
scale = newDist / oldDist;
spaceX = spaceX * scale / 2;
spaceY = spaceY * scale / 2;
if (setZoom.equals("0") && scale < 1) {
setTitle("You cannot Zoom");
} else {
setZoom = "1";
matrix.postScale(scale, scale, mid.x, mid.y);
newwidth = kangoo.getWidth() * scale;
// setTitle("New Width "+newwidth+"oldDist: "+oldDist);
}
}
}
break;
}
// view.setImageMatrix(matrix);
return true; // indicate event was handled
}
//@Override
public boolean onTouch(View arg0, MotionEvent arg1) {
// TODO Auto-generated method stub
return false;
}
}
public Bitmap DecodeFile(String Url) {
try {
URL aURL = new URL(Url);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
Bitmap bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
return bm;
} catch (Exception e) {
return null;
}
}
public void setImage(int position) {
Display display = getWindowManager().getDefaultDisplay();
int dwidth = display.getWidth();
int dheight = display.getHeight() - 70;
kangoo = DecodeFile(LinkImage[position]);
kangoo = Bitmap.createScaledBitmap(kangoo, dwidth, dheight, true);
oldwidth = kangoo.getWidth();
OldHeight = kangoo.getHeight();
modeview = "1";
text1 = "";
text2 = "";
text3 = "";
text4 = "";
dw = 0;
dh = 0;
// setTitle("dwidth :" + dwidth + "dheight: " + dheight);
}
public void setImage2() {
Display display = getWindowManager().getDefaultDisplay();
int dwidth = display.getWidth();
int dheight = display.getHeight();
kangoo = DecodeFile("http://192.168.127.12/RssSample3.1/mandant/imgs/I1.png");
kangoo = Bitmap.createScaledBitmap(kangoo, dwidth, dheight, true);
dw = 0;
dh = 0;
}
public void setImage3() {
Display display = getWindowManager().getDefaultDisplay();
int dwidth = display.getWidth();
int dheight = display.getHeight();
kangoo = DecodeFile("http://174.143.148.49/RssSample3.1/mandant/imgs/I2.png");
kangoo = Bitmap.createScaledBitmap(kangoo, dwidth, dheight, true);
dw = 0;
dh = 0;
}
public void setImage4() {
Display display = getWindowManager().getDefaultDisplay();
int dwidth = display.getWidth();
int dheight = display.getHeight();
Drawable board = getResources().getDrawable(R.drawable.quickaction_background);
Bitmap bitmap2 = ((BitmapDrawable) board).getBitmap();
kangoo = Bitmap.createBitmap(bitmap2);
kangoo = Bitmap.createScaledBitmap(kangoo, dwidth, dheight, true);
modeview = "2";
text1 = "Creditor : Coca cola";
text2 = "Type : bill";
text3 = "Currency : USD";
text4 = "Amount: 100,00€";
oldwidth = kangoo.getWidth();
}
private void readRss_Segment() {
try {
URL rssUrl = new URL(
"http://192.168.127.12/RssSample3.1/mandant/workbasket/process/document/segment/ORG-segments.xml");
SAXParserFactory mySAXParserFactory = SAXParserFactory
.newInstance();
SAXParser mySAXParser = mySAXParserFactory.newSAXParser();
XMLReader myXMLReader = mySAXParser.getXMLReader();
RSSHandler_Reader_Segment myRSSHandler_Segment = new RSSHandler_Reader_Segment();
myXMLReader.setContentHandler(myRSSHandler_Segment);
InputSource myInputSource = new InputSource(rssUrl.openStream());
myXMLReader.parse(myInputSource);
myRssFeed_Segment = myRSSHandler_Segment.getFeed();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (myRssFeed_Segment != null) {
int x = myRssFeed_Segment.getList().size();
TextTest = myRssFeed_Segment.getList().get(0).getH().toString();
for (int i = 0; i < x; i++) {
SegmentX.add((myRssFeed_Segment.getList().get(i).getX()));
SegmentY.add((myRssFeed_Segment.getList().get(i).getY()));
SegmentHeight.add((myRssFeed_Segment.getList().get(i).getH()));
SegmentWidth.add((myRssFeed_Segment.getList().get(i).getW()));
}
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_LEFT: {
Toast.makeText(this, "LEFT", Toast.LENGTH_SHORT).show();
showProcessBar2();
break;
}
case KeyEvent.KEYCODE_DPAD_RIGHT: {
Toast.makeText(this, "RIGHT" + page, Toast.LENGTH_SHORT).show();
showProcessBar3();
break;
}
case KeyEvent.KEYCODE_DPAD_UP: {
break;
}
case KeyEvent.KEYCODE_DPAD_DOWN: {
break;
}
case KeyEvent.KEYCODE_DPAD_CENTER: {
break;
}
case KeyEvent.KEYCODE_BACK: {
Intent intent = new Intent();
Bundle bundle = new Bundle();
// CharSequence textmessageLinkProcess;
// textmessageLinkProcess=messageLinkProcess;
// bundle.putCharSequence("LinkProcess",textmessageLinkProcess);
CharSequence textmessageLinkWB;
textmessageLinkWB = messageLinkWB;
bundle.putCharSequence("messageLinkWB", textmessageLinkWB);
intent.putExtras(bundle);
intent.setClass(ShowListPageWithImage.this,
ShowListProcessWithDocs.class);
startActivity(intent);
finish();
}
}
return true;
}
private final OnClickListener onZoomOut = new OnClickListener() {
public void onClick(View v) {
setzoom = 1;
x -= 0.2f;
y -= 0.2f;
}
};
private final OnClickListener onZoomIn = new OnClickListener() {
public void onClick(View v) {
setzoom = 1;
x += 0.2f;
y += 0.2f;
}
};
public void reload() {
Intent intent = getIntent();
finish();
startActivity(intent);
}
public void showProcessBar() {
progDailog = ProgressDialog.show(ShowListPageWithImage.this, "",
"please wait....", true);
new Thread() {
@Override
public void run() {
try {
setImage(position);
sleep(300);
} catch (Exception e) {
}
handler.sendEmptyMessage(0);
progDailog.dismiss();
}
}.start();
}
public void showProcessBar3() {
progDailog = ProgressDialog.show(ShowListPageWithImage.this, "",
"please wait....", true);
new Thread() {
@Override
public void run() {
try {
setImage3();
sleep(300);
} catch (Exception e) {
}
handler.sendEmptyMessage(0);
progDailog.dismiss();
}
}.start();
}
public void showProcessBar2() {
progDailog = ProgressDialog.show(ShowListPageWithImage.this, "",
"please wait....", true);
new Thread() {
@Override
public void run() {
try {
setImage2();
sleep(300);
} catch (Exception e) {
}
handler.sendEmptyMessage(0);
progDailog.dismiss();
}
}.start();
}
public void showProcessBar4() {
progDailog = ProgressDialog.show(ShowListPageWithImage.this, "",
"please wait....", true);
new Thread() {
@Override
public void run() {
try {
setImage4();
sleep(300);
} catch (Exception e) {
}
handler.sendEmptyMessage(0);
progDailog.dismiss();
}
}.start();
}
public void sleep() {
new Thread() {
@Override
public void run() {
try {
sleep(10000);
} catch (Exception e) {
}
}
}.start();
}
private final Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
}
};
private void dumpEvent(MotionEvent event) {
String names[] = { "DOWN", "UP", "MOVE", "CANCEL", "OUTSIDE",
"POINTER_DOWN", "POINTER_UP", "7?", "8?", "9?" };
StringBuilder sb = new StringBuilder();
int action = event.getAction();
int actionCode = action & MotionEvent.ACTION_MASK;
sb.append("event ACTION_").append(names[actionCode]);
if (actionCode == MotionEvent.ACTION_POINTER_DOWN
|| actionCode == MotionEvent.ACTION_POINTER_UP) {
sb.append("(pid ").append(
action >> MotionEvent.ACTION_POINTER_ID_SHIFT);
sb.append(")");
}
sb.append("[");
for (int i = 0; i < event.getPointerCount(); i++) {
sb.append("#").append(i);
sb.append("(pid ").append(event.getPointerId(i));
sb.append(")=").append((int) event.getX(i));
sb.append(",").append((int) event.getY(i));
if (i + 1 < event.getPointerCount())
sb.append(";");
}
sb.append("]");
}
/** Determine the space between the first two fingers */
private float spacing(MotionEvent event) {
float x = event.getX(0) - event.getX(1);
float y = event.getY(0) - event.getY(1);
return FloatMath.sqrt(x * x + y * y);
}
/** Calculate the mid point of the first two fingers */
private void midPoint(PointF point, MotionEvent event) {
float x = event.getX(0) + event.getX(1);
float y = event.getY(0) + event.getY(1);
point.set(x / 2, y / 2);
}
//@Override
public boolean onTouch(View arg0, MotionEvent arg1) {
// TODO Auto-generated method stub
return false;
}
public class AddImgAdp extends BaseAdapter {
int GalItemBg;
private Context cont;
public AddImgAdp(Context c) {
cont = c;
TypedArray typArray = obtainStyledAttributes(R.styleable.GalleryTheme);
GalItemBg = typArray.getResourceId(
R.styleable.GalleryTheme_android_galleryItemBackground, 0);
typArray.recycle();
}
public AddImgAdp(Mens mens) {
// TODO Auto-generated constructor stub
}
public int getCount() {
return Imgid.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imgView = new ImageView(cont);
imgView.setImageResource(Imgid[position]);
imgView.setLayoutParams(new Gallery.LayoutParams(80, 70));
imgView.setScaleType(ImageView.ScaleType.FIT_XY);
imgView.setBackgroundResource(GalItemBg);
return imgView;
}
}
}
<file_sep>/src/aexp/explist/.svn/text-base/ShowDetail_Document.java.svn-base
package aexp.explist;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import android.app.ListActivity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.TestSegment.RSSItem_Reader;
import com.sskk.example.bookprovidertest.provider.BookProviderMetaData;
public class ShowDetail_Document extends ListActivity {
TextView feedTitle;
TextView feedDescribtion;
TextView feedPubdate;
TextView feedLink;
String[] arInfo;
private String imageUrl="";
private ImageView imgView;
private String message;
private int readcount;
private int unreadcount;
private String ProcessClicked;
List<String> ListProcessClicked = new ArrayList();
private List<String> LinkImage = new ArrayList();
String smallImage;
Integer[] mThumbIds;
private List<String> ListSmallImage = new ArrayList();
private List<String> ListFullImage = new ArrayList();
private String[] WBenableProj =
new String[] { BookProviderMetaData.BookTableMetaData._ID
,BookProviderMetaData.BookTableMetaData.WB_NAME
,BookProviderMetaData.BookTableMetaData.WB_URI
,BookProviderMetaData.BookTableMetaData.WB_EANABLE
,BookProviderMetaData.BookTableMetaData.TOTAL_COUNT
,BookProviderMetaData.BookTableMetaData.UNREAD_COUNT
,BookProviderMetaData.BookTableMetaData.INGROUP_ID };
private String[] ProcessClickedProj =
new String[] { BookProviderMetaData.BookTableMetaData._ID,
BookProviderMetaData.BookTableMetaData.PROCESS_OPENNED};
public class MyCustomAdapter extends ArrayAdapter<RSSItem_Reader> {
public MyCustomAdapter(Context context, int textViewResourceId,
List<RSSItem_Reader> list) {
super(context, textViewResourceId, list);
}
/*@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
//return super.getView(position, convertView, parent);
View row = convertView;
if(row==null){
LayoutInflater inflater=getLayoutInflater();
row=inflater.inflate(R.layout.rowreader, parent, false);
}
TextView listTitle=(TextView)row.findViewById(R.id.listtitle);
listTitle.setText(myRssFeed.getList().get(position).getTitle());
TextView listPubdate=(TextView)row.findViewById(R.id.listpubdate);
listPubdate.setText(myRssFeed.getList().get(position).getDescription());
ImageView imageView = (ImageView) row.findViewById(R.id.icon);
URL myFileUrl =null;
for(int i=0;i<ListSmallImage.size();i++){
Bitmap[] bmImg=new Bitmap[ListSmallImage.size()];
try {
//if (position == i){
myFileUrl= new URL(ListSmallImage.get(i));
//}
HttpURLConnection conn= (HttpURLConnection)myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
int length = conn.getContentLength();
InputStream is = conn.getInputStream();
bmImg[i] = BitmapFactory.decodeStream(is);
if (position == i){
imageView.setImageBitmap(bmImg[i]);
}
//imView.setImageBitmap(bmImg);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return row;
}*/
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.mainreader);
UpdateProcessClickedInDb();
Bitmap[] bmImg=new Bitmap[2];
Bundle bundle = this.getIntent().getExtras();
CharSequence textMessage = bundle.getCharSequence("message");
message=""+textMessage;
// getMandantListFromServer(message);
for(int i=0;i<LinkImage.size();i++){
String h;
h=LinkImage.get(i).replace("[","-");
//h=LinkImage.get(i).replace("]","");
arInfo = h.split("-");
ListSmallImage.add(arInfo[0]);
ListFullImage.add(arInfo[1].replace("]",""));
}
Toast.makeText(this,""+ListFullImage.get(0), Toast.LENGTH_SHORT).show();
//readRss();
}
/* private void readRss(){
setListAdapter(null);
try {
URL rssUrl = new URL(message);
SAXParserFactory mySAXParserFactory = SAXParserFactory.newInstance();
SAXParser mySAXParser = mySAXParserFactory.newSAXParser();
XMLReader myXMLReader = mySAXParser.getXMLReader();
RSSHandler_Reader myRSSHandler = new RSSHandler_Reader();
myXMLReader.setContentHandler(myRSSHandler);
InputSource myInputSource = new InputSource(rssUrl.openStream());
myXMLReader.parse(myInputSource);
myRssFeed = myRSSHandler.getFeed();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (myRssFeed!=null)
{
Calendar c = Calendar.getInstance();
String strCurrentTiime = "\n(Time of Reading - "
+ c.get(Calendar.HOUR_OF_DAY)
+ " : "
+ c.get(Calendar.MINUTE) + ")\n";
feedTitle.setText(myRssFeed.getTitle() + strCurrentTiime);
feedDescribtion.setText(myRssFeed.getDescription());
feedPubdate.setText(myRssFeed.getPubdate());
feedLink.setText(myRssFeed.getLink());
MyCustomAdapter adapter =
new MyCustomAdapter(this, R.layout.rowreader, myRssFeed.getList());
setListAdapter(adapter);
}
}*/
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Object o = this.getListAdapter().getItem(position);
String keyword = o.toString();
ProcessClicked= keyword;
if(ListProcessClicked.contains(ProcessClicked)){
Toast.makeText(this, ProcessClicked, Toast.LENGTH_LONG).show();
Intent intent = new Intent();
Bundle bundle= new Bundle();
CharSequence textMessage;
CharSequence textMessage1;
textMessage1=message;
textMessage =""+ListFullImage.get(position).toString();
bundle.putCharSequence("fullimage",textMessage);
bundle.putCharSequence("message",textMessage1);
intent.putExtras(bundle);
intent.setClass(ShowDetail_Document.this,showFullImage.class);
startActivity(intent);
finish();
setTitle("Showing Full Image");
}
else{
addProcessClickedtoDB(ProcessClicked);
UpdateProcessClickedInDb();
UpdateCountInDb();
Toast.makeText(this, ProcessClicked, Toast.LENGTH_LONG).show();
Intent intent = new Intent();
Bundle bundle= new Bundle();
CharSequence textMessage;
CharSequence textMessage1;
textMessage1=message;
textMessage =""+ListFullImage.get(position).toString();
bundle.putCharSequence("fullimage",textMessage);
bundle.putCharSequence("message",textMessage1);
intent.putExtras(bundle);
intent.setClass(ShowDetail_Document.this,showFullImage.class);
startActivity(intent);
finish();
setTitle("Showing Full Image");
}
}
/*
public void getMandantListFromServer(String uri){
try{
URL rssUrl = new URL(uri);
SAXParserFactory mySAXParserFactory = SAXParserFactory.newInstance();
SAXParser mySAXParser = mySAXParserFactory.newSAXParser();
XMLReader myXMLReader = mySAXParser.getXMLReader();
RSSHandler_Reader myRSSHandler = new RSSHandler_Reader();
myXMLReader.setContentHandler(myRSSHandler);
InputSource myInputSource = new InputSource(rssUrl.openStream());
myXMLReader.parse(myInputSource);
myRssFeed2 = myRSSHandler.getFeed();
int x = myRssFeed2.getList().size();
for(int i=0;i<x;i++){
LinkImage.add(myRssFeed2.getList().get(i).getLink());
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
menu.add(0, 0, 0, "Reload");
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch(item.getItemId()){
case (0):
//readRss();
break;
default:
break;
}
return true;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_LEFT: {
break;
}
case KeyEvent.KEYCODE_DPAD_RIGHT: {
break;
}
case KeyEvent.KEYCODE_DPAD_UP: {
//openDialog2();
break;
}
case KeyEvent.KEYCODE_DPAD_DOWN: {
break;
}
/* case KeyEvent.KEYCODE_DPAD_CENTER: {
break;
}*/
case KeyEvent.KEYCODE_BACK: {
//finish();
Intent intent = new Intent();
intent.setClass(ShowDetail_Document.this,aexp.explist.ANDROID_RSS_READER.class);
startActivity(intent);
finish();
}
}
return false;
}
public void CountReadinDB() {
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(BookProviderMetaData.BookTableMetaData.CONTENT_URI,
WBenableProj,"wbenable = ? AND wburi = ?",
new String[] { "1",message}, null);
int numberOfWBenable= cursor.getCount();
for ( int i = 0; i <numberOfWBenable ; i++ ){
cursor.moveToPosition(i );
int ColumnReadCount = cursor.getColumnIndex(BookProviderMetaData.BookTableMetaData.TOTAL_COUNT);
String nameReadCount = cursor.getString(ColumnReadCount);
readcount=Integer.parseInt(nameReadCount);
int ColumnUnReadCount = cursor.getColumnIndex(BookProviderMetaData.BookTableMetaData.UNREAD_COUNT);
String nameUnReadCount= cursor.getString(ColumnUnReadCount);
unreadcount=Integer.parseInt(nameUnReadCount);
}
}
public void UpdateCountInDb(){
CountReadinDB();
int read=readcount+1;
int unread=unreadcount-1;
ContentResolver contentResolver = getContentResolver();
ContentValues values1 = new ContentValues();
ContentValues values2 = new ContentValues();
values1.put(BookProviderMetaData.BookTableMetaData.TOTAL_COUNT,""+read);
values2.put(BookProviderMetaData.BookTableMetaData.UNREAD_COUNT,""+unread);
int count1 = contentResolver.update(BookProviderMetaData.BookTableMetaData.CONTENT_URI,
values1,"readcount = ? AND wburi = ?"
,new String[] {""+readcount,message});
int count2 = contentResolver.update(BookProviderMetaData.BookTableMetaData.CONTENT_URI,
values2,"unreadcount = ? AND wburi = ?"
,new String[] {""+unreadcount,message});
//Toast.makeText(this,"Rename Successfully !", Toast.LENGTH_SHORT).show();
}
public void addProcessClickedtoDB(String ProcessClicked) {
ContentResolver contentResolver = getContentResolver();
ContentValues values = new ContentValues();
values.put(BookProviderMetaData.BookTableMetaData.PROCESS_OPENNED,ProcessClicked);
Uri uri = contentResolver.insert(BookProviderMetaData.BookTableMetaData.CONTENT_URI, values);
}
public void UpdateProcessClickedInDb() {
ListProcessClicked.clear();
ContentResolver contentResolver = getContentResolver();
Cursor cursor1 = contentResolver.query(BookProviderMetaData.BookTableMetaData.CONTENT_URI,
ProcessClickedProj,null,null, null);
int x1= cursor1.getCount();
for ( int i = 0; i <x1 ; i++ ){
cursor1.moveToPosition(i );
int ColumnProcessClicked = cursor1.getColumnIndex(BookProviderMetaData.BookTableMetaData.PROCESS_OPENNED);
String ProcessClicked = cursor1.getString(ColumnProcessClicked);
ListProcessClicked.add(ProcessClicked);
}
}
}
<file_sep>/src/aexp/explist/test2.java
package aexp.explist;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import oxseed.ocr.data.OCRDATA;
import oxseed.ocr.data.OCRDATA.Page.Segment;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PointF;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.FloatMath;
import android.util.Log;
import android.view.Display;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.android.TestSegment.RSSFeed_Reader_Segment;
import com.test.androidtest.ActionItem;
import com.test.androidtest.QuickAction;
public class test2 extends Activity implements OnGestureListener,
OnTouchListener {
Boolean flag = true;
private int NONE = 0;
Path mPath;
static final int DRAG = 1;
static final int ZOOM = 2;
private GestureDetector gd;
int mode = NONE;
String TAG = "draw ";
DrawableImageView d;
private Matrix matrix = new Matrix();
private Matrix savedMatrix;
PointF mid = new PointF();
float scale = 1;
float curX, curY;
Bitmap kangoo;
private ParserTask parserTask;
private RSSFeed_Reader_Segment myRssFeed_Segment = null;
private final List<String> SegmentX = new ArrayList();;
private final List<String> SegmentY = new ArrayList();;
private final List<String> SegmentWidth = new ArrayList();;
private final List<String> SegmentHeight = new ArrayList();;
private double ImageX, ImageY;
private float deltaX, deltaY;
private int DeviceWidth, DeviceHeight;
private float FirstImageWidth, FirstImageHeight;
private float FitImageWidth, FitImageHeight;
private float SegmentXDraw, SegmentYDraw, SegmentHDraw, SegmentWDraw;
private float ScaleWidth, ScaleHeight;
private float ScaleFit;
private float SegmentXLoop, SegmentYLoop, SegmentHLoop, SegmentWLoop;
double SpaceX, SpaceY;
int minDelta;
float touchX = 0;
float touchY = 0;
int height;
int count = 0;
private ProgressBar mProgressBar;
LinearLayout l;
private MainCountDown countDown;
private String messageLinkWB;
private String messageDocName;
List<Segment> listSegment;
QuickAction mQuickAction;
private static final int ID_CREDITOR = 1;
private static final int ID_AMOUNT = 2;
private static final int ID_CURRENCY = 3;
private static final int ID_TYPE = 4;
List<String> ValueListIndex = new ArrayList<String>();
List<String> FirstListIndex = new ArrayList<String>();
private int positionChange;
private String IndexSelected;
private EditText NewValueEditText;
private String NewValue;
private final String[] LinkImage = {
"https://ox6a.oxseed.net/services/ocr-archive?action=show_image&document_id=20100629154625261000817AE59111D22744D07CC9EB55708AE4B0000000028a6ba6f1a&mandant=condor&image_output_format=png_gray&max_width=500&max_height=600"
,
"https://ox6a.oxseed.net/services/ocr-archive?action=show_image&document_id=20100629154835621000826FFBB07EC5DD73C7BCCE07C4DF1C4A600000000b750c91781&mandant=condor&image_output_format=png_gray&max_width=700&max_height=800"
,
"https://ox6a.oxseed.net/services/ocr-archive?action=show_image&document_id=20100629154625261000817AE59111D22744D07CC9EB55708AE4B0000000028a6ba6f1a&mandant=condor&image_output_format=png_gray&max_width=500&max_height=600"
};
/* * private final String[] LinkSegment = {
* "https://ox6a.oxseed.net/services/ocr-archive?action=show_segmentation&page_nr=0&document_id=20100629154625261000817AE59111D22744D07CC9EB55708AE4B0000000028a6ba6f1a&mandant=condor&response_format=xml"
* ,
* "https://ox6a.oxseed.net/services/ocr-archive?action=show_segmentation&document_id=20100629154835621000826FFBB07EC5DD73C7BCCE07C4DF1C4A600000000b750c91781&mandant=condor"
* ,
* "https://ox6a.oxseed.net/services/ocr-archive?action=show_segmentation&page_nr=0&document_id=20100629154625261000817AE59111D22744D07CC9EB55708AE4B0000000028a6ba6f1a&mandant=condor&response_format=xml"
* };
*/
/*
private final String[] LinkImage = { "http://thcslienha.edu.vn/i1.png",
"http://thcslienha.edu.vn/i2.png",
"http://thcslienha.edu.vn/i1.png",
"http://thcslienha.edu.vn/i1.png",
"http://thcslienha.edu.vn/i2.png",
"http://thcslienha.edu.vn/i1.png"};*/
private final String[] LinkSegment = {
"https://ox6a.oxseed.net/services/ocr-archive?action=show_segmentation&page_nr=0&document_id=20100629154625261000817AE59111D22744D07CC9EB55708AE4B0000000028a6ba6f1a&mandant=condor&response_format=protocol_buffer",
"https://ox6a.oxseed.net/services/ocr-archive?action=show_segmentation&page_nr=0&document_id=20100629154625261000817AE59111D22744D07CC9EB55708AE4B0000000028a6ba6f1a&mandant=condor&response_format=protocol_buffer",
"https://ox6a.oxseed.net/services/ocr-archive?action=show_segmentation&page_nr=0&document_id=20100629154625261000817AE59111D22744D07CC9EB55708AE4B0000000028a6ba6f1a&mandant=condor&response_format=protocol_buffer" };
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.view_image_activity);
FirstListIndex.add("Coca Cola");
FirstListIndex.add("100,00");
FirstListIndex.add("Euro");
FirstListIndex.add("bill");
populateView();
/*
* Bundle bundle = this.getIntent().getExtras(); CharSequence
* textMessage3 = bundle.getCharSequence("messageLinkWB"); messageLinkWB
* = "" + textMessage3; CharSequence textDocName =
* bundle.getCharSequence("messageDocName"); messageDocName = "" +
* textDocName;
*/
mProgressBar = (ProgressBar) findViewById(R.id.view_image_progress_bar);
l = (LinearLayout) findViewById(R.id.myScreen2);
Display display = getWindowManager().getDefaultDisplay();
DeviceWidth = display.getWidth();
DeviceHeight = display.getHeight();
getDataProtobuf(LinkSegment[0]);
// GlobalVariable.mBitmap = kangoo;
// FirstImageWidth = 2115.0F;
// FirstImageHeight = 2921.0F;
if (FirstImageWidth / DeviceWidth >= FirstImageHeight / DeviceHeight) {
ScaleFit = FirstImageWidth / DeviceWidth;
FitImageHeight = FirstImageHeight * 1.0F / ScaleFit;
FitImageWidth = DeviceWidth;
deltaX = 0;
deltaY = (DeviceHeight - FitImageHeight) / 2.0F;
} else if (FirstImageWidth / DeviceWidth < FirstImageHeight
/ DeviceHeight) {
ScaleFit = FirstImageHeight / DeviceHeight;
FitImageWidth = FirstImageWidth * 1.0F / ScaleFit;
FitImageHeight = DeviceWidth;
deltaX = (DeviceWidth - FitImageWidth) / 2.0F;
deltaY = 0;
}
// getSegmentListFromServer();
// readRss_Segment(LinkSegment[0]);
// setTitle("" + SegmentX.get(0) + "size=" + SegmentX.size());
// kangoo = DecodeFile(LinkImage[0]);
height = Math.round(DeviceWidth * (FirstImageHeight / FirstImageWidth));
gd = new GestureDetector((OnGestureListener) this);
}
public void onclick(View view) {
Log.e("height ", d.getMeasuredHeight() + "");
Log.e("width ", d.getMeasuredWidth() + "");
if (flag) {
flag = false;
} else {
flag = true;
}
}
public class DrawableImageView extends View {
private Bitmap mBitmap;
private Bitmap pic;
private Canvas mCanvas;
private final Paint mPaint;
private int a = 255;
private int r = 255;
private int g = 255;
private int b = 255;
private float width = 20;
float leftImage = 0;
float topImage = 0;
float test;
float lastX;
float lastY;
PointF start = new PointF();
float oldDist = 1f;
Button undo_Btn;
public DrawableImageView(Context c, Bitmap img) {
super(c);
undo_Btn = new Button(c);
undo_Btn.measure(40, 40); // size of view
int width = undo_Btn.getMeasuredWidth();
int height = undo_Btn.getMeasuredHeight();
int left = 320;
int top = 480;
undo_Btn.setPadding(320, 480, 0, 0);
// undo_Btn.setLayoutParams(new LayoutParams(width,height));
undo_Btn.layout(left, top, left + width, top + height);
undo_Btn.setBackgroundDrawable(getResources().getDrawable(
R.xml.i_symbol));
// undo_Btn.setBackgroundDrawable(@xml/thumbnail);
undo_Btn.setVisibility(VISIBLE);
// undo_Btn.setId(10);
// undo_Btn.setPadding(50, 250, 0, 0);
undo_Btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
}
});
pic = img;
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setARGB(a, r, g, b);
Bitmap newBitmap = Bitmap.createBitmap(img.getWidth(),
img.getHeight(), Bitmap.Config.RGB_565);
Canvas newCanvas = new Canvas();
newCanvas.setBitmap(newBitmap);
if (img != null) {
newCanvas.drawBitmap(img, 0, 0, null);
}
mBitmap = newBitmap;
Log.e("Bitmap height", mBitmap.getHeight() + "");
mCanvas = newCanvas;
mCanvas.setBitmap(mBitmap);
savedMatrix = new Matrix();
matrix = new Matrix();
savedMatrix.set(matrix);
invalidate();
}
public DrawableImageView(Context c, Bitmap img, int alpha, int red,
int green, int blue) {
this(c, img);
setColor(alpha, red, green, blue);
}
public DrawableImageView(Context c, Bitmap img, int alpha, int red,
int green, int blue, float w) {
this(c, img, alpha, red, green, blue);
width = w;
}
public Bitmap getBitmap() {
return mBitmap;
}
public void setWidth(float w) {
width = w;
}
public void setColor(int alpha, int red, int green, int blue) {
a = alpha;
r = red;
g = green;
b = blue;
mPaint.setARGB(a, r, g, b);
}
public void Undo() {
mCanvas.drawBitmap(mBitmap, 0, 0, null);
invalidate();
}
float scaleX;
float scaleY;
float mscale = 1;
@Override
protected void onLayout(boolean changed, int left, int top, int right,
int bottom) {
// super.onLayout(changed, left, top, right, bottom);
Log.e("on layout changed called ", "called method ");
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
Log.e("on size cahnged ", "called ");
// scaleX = (float) w / mBitmap.getWidth();
// scaleY = (float) h / mBitmap.getHeight();
//
scaleX = (float) oldw / w;
scaleY = (float) oldh / h;
Log.e("scale x | scale y", scaleX + " | " + scaleY);
scale = scaleX > scaleY ? scaleY : scaleX;
if (scale == 0)
scale = 1;
}
@Override
protected void onDraw(Canvas canvas) {
if (mBitmap != null) {
matrix = new Matrix();
Paint paint = new Paint();
matrix.postTranslate(leftImage, topImage);
matrix.postScale(scale, scale);
canvas.drawColor(Color.BLACK);
canvas.drawBitmap(mBitmap, matrix, paint);
paint.setColor(Color.RED);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(3);
int x = SegmentX.size();
float[] DeltaH = new float[x];
ImageY = (touchY - topImage * scale) / scale;
ImageX = (touchX - leftImage * scale) / scale;
for (int i = 0; i < x; i++) {
float a = Float.parseFloat(SegmentX.get(i));
float b = Float.parseFloat(SegmentY.get(i));
float c = Float.parseFloat(SegmentWidth.get(i));
float d = Float.parseFloat(SegmentHeight.get(i));
// curX = (event.getX() / scale) - (left * scale);
// curY = (event.getY() / scale) - (top * scale);
SegmentXLoop = (float) ((a / ScaleFit));
SegmentYLoop = (float) ((b / ScaleFit));
SegmentWLoop = (float) ((c / ScaleFit));
SegmentHLoop = (float) ((d / ScaleFit));
if (SegmentXLoop <= ImageX
&& ImageX <= SegmentXLoop + SegmentWLoop
&& SegmentYLoop <= ImageY
&& ImageY <= SegmentYLoop + SegmentHLoop) {
SegmentXDraw = SegmentXLoop;
SegmentYDraw = SegmentYLoop;
SegmentWDraw = SegmentWLoop;
SegmentHDraw = SegmentHLoop;
} else {
DeltaH[i] = (float) Math
.sqrt((ImageX - (SegmentXLoop + SegmentWLoop / 2))
* (ImageX - (SegmentXLoop + SegmentWLoop / 2))
+ (ImageY - (SegmentYLoop + SegmentHLoop / 2))
* (ImageY - (SegmentYLoop + SegmentHLoop / 2)));
}
minDelta = getMinValue(DeltaH);
float e = (float) (Float.parseFloat(SegmentX.get(minDelta)));
float f = (float) (Float.parseFloat(SegmentY.get(minDelta)));
float g = (float) (Float.parseFloat(SegmentWidth
.get(minDelta)));
float h = (float) (Float.parseFloat(SegmentHeight
.get(minDelta)));
SegmentXDraw = scale * (e / ScaleFit);
SegmentYDraw = scale * (f / ScaleFit);
SegmentWDraw = scale * (g / ScaleFit);
SegmentHDraw = scale * (h / ScaleFit);
}
canvas.drawRect(
(float) (SegmentXDraw + leftImage * scale),
(float) (SegmentYDraw + topImage * scale),
(float) (SegmentXDraw + leftImage * scale + SegmentWDraw),
(float) (SegmentYDraw + topImage * scale + SegmentHDraw),
paint);
undo_Btn.draw(canvas);
canvas.restore();
invalidate();
// canvas.drawRect(curX,curX,curX+30,curY+30,paint);
}
}
@Override
public boolean onTouchEvent( MotionEvent event) {
super.onTouchEvent(event);
touchX = event.getX();
touchY = event.getY();
Log.e("left ", leftImage + "");
Log.e("top ", topImage + "");
Log.e("Scale", scale + "");
Log.e("event.getX", event.getX() + "");
Log.e("event.getY", event.getY() + "");
Log.e("minDelta", minDelta + "");
float umin, umax, vmin, vmax, xmin, xmax, ymin, ymax;
xmin = 0;
ymin = 0;
xmax = this.getWidth();
ymax = this.getHeight();
umin = leftImage;
vmin = topImage;
umax = this.getWidth() - leftImage;
vmax = this.getHeight() - topImage;
float t = this.getWidth()/2;
test=t/scale-xmax;
curX = (event.getX() / scale) - (leftImage * scale);
curY = (event.getY() / scale) - (topImage * scale);
// if (flag) {
Log.e("left | top", leftImage + " | " + topImage);
Log.e("curX | curY", curX + " | " + curY);
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
savedMatrix.set(matrix);
start.set(event.getX(), event.getY());
Log.d(TAG, "mode=DRAG");
if (touchX > 5 && touchX < 20 && touchY > 2 && touchY < 40) {
Intent intent = new Intent();
Bundle bundle = new Bundle();
CharSequence textMessage;
CharSequence textDocName;
textMessage = "" + messageLinkWB;
textDocName = "" + messageDocName;
bundle.putCharSequence("messageLinkWB", textMessage);
bundle.putCharSequence("messageDocName", textDocName);
intent.putExtras(bundle);
intent.setClass(test2.this, IndexDoc.class);
startActivity(intent);
finish();
} else {
/*
* if (setCanvas.equals("1")) { mQuickAction.show(v); } else
* { mQuickAction.dismiss(); }
*/
}
mQuickAction.show(d);
mode = DRAG;
break;
case MotionEvent.ACTION_POINTER_DOWN:
oldDist = spacing(event);
Log.d(TAG, "oldDist=" + oldDist);
if (oldDist > 10f) {
savedMatrix.set(matrix);
midPoint(mid, event);
mode = ZOOM;
Log.d(TAG, "mode=ZOOM");
}
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_POINTER_UP:
mode = NONE;
Log.d(TAG, "mode=NONE");
break;
case MotionEvent.ACTION_MOVE:
mQuickAction.dismiss();
if (mode == DRAG) {
matrix.set(savedMatrix);
matrix.postTranslate(event.getX() - start.x, event.getY()
- start.y);
leftImage = leftImage + (event.getX() - start.x);
topImage = topImage + event.getY() - start.y;
if (leftImage * scale > this.getWidth() / 2) {
goLeft();
break;
} else if (leftImage< test) {
goRight();
break;
}
if (topImage * scale > this.getHeight() / 2) {
goBottom();
break;
} else if (topImage * scale < -(this.getHeight() / 2)) {
goTop();
break;
}
onLayout(true, (int) leftImage, (int) topImage,
(int) (this.getWidth() - leftImage),
(int) (this.getHeight() - topImage));
Log.e("left top position ", leftImage + " | " + topImage
+ "");
} else if (mode == ZOOM) {
float newDist = spacing(event);
Log.d(TAG, "newDist=" + newDist);
if (newDist > 10f) {
matrix.set(savedMatrix);
scale = newDist / oldDist;
matrix.postScale(scale, scale, mid.x, mid.y);
}
}
break;
}
// matrixTurning();
mCanvas.setMatrix(matrix);
invalidate();
// } else {
// }
return true;
}
private float spacing(MotionEvent event) {
float x = event.getX(0) - event.getX(1);
float y = event.getY(0) - event.getY(1);
return FloatMath.sqrt(x * x + y * y);
}
private void midPoint(PointF point, MotionEvent event) {
float x = event.getX(0) + event.getX(1);
float y = event.getY(0) + event.getY(1);
point.set(x / 2, y / 2);
}
}
/* @Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_LEFT: {
matrix.set(savedMatrix);
matrix.postScale(scale, scale, mid.x, mid.y);
if (scale == 1) {
} else {
scale = scale - 1;
}
break;
}
case KeyEvent.KEYCODE_DPAD_RIGHT: {
matrix.set(savedMatrix);
matrix.postScale(scale, scale, mid.x, mid.y);
if (scale == 5) {
} else {
scale = scale + 1;
}
break;
}
}
return false;
}*/
public Bitmap DecodeFile(String Url) {
try {
URL aURL = new URL(Url);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
Bitmap bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
return bm;
} catch (Exception e) {
return null;
}
}
public void getDataProtobuf(String Url) {
try {
InputStream is = new URL(Url).openStream();
OCRDATA.Page data = OCRDATA.Page.parseFrom(is);
FirstImageWidth = data.getImageWidth();
FirstImageHeight = data.getImageHeight();
listSegment = data.getSegmentList();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
SegmentX.clear();
SegmentY.clear();
SegmentHeight.clear();
SegmentWidth.clear();
try {
for (Segment segmentLoop : listSegment) {
SegmentX.add("" + segmentLoop.getX());
SegmentY.add("" + segmentLoop.getY());
SegmentWidth.add("" + segmentLoop.getW());
SegmentHeight.add("" + segmentLoop.getH());
}
} catch (Exception e) {
Log.e("DayTrader", "Exception getting ProtocolBuffer data", e);
}
}
public static int getMinValue(float[] numbers) {
float minValue = numbers[0];
int min = 0;
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] < minValue) {
minValue = numbers[i];
min = i;
}
}
return min;
}
/*
* // @Override public boolean onTouch(View arg0, MotionEvent arg1) { //
* TODO Auto-generated method stub return false; }
*/
public boolean onDown(MotionEvent e) {
// TODO Auto-generated method stub
return false;
}
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
// TODO Auto-generated method stub
return false;
}
public void onLongPress(MotionEvent e) {
// TODO Auto-generated method stub
}
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
float distanceY) {
// TODO Auto-generated method stub
return false;
}
public void onShowPress(MotionEvent e) {
// TODO Auto-generated method stub
}
public boolean onSingleTapUp(MotionEvent e) {
// TODO Auto-generated method stub
return false;
}
@Override
protected void onStart() {
super.onStart();
parserTask = new ParserTask();
parserTask.execute();
}
private class ParserTask extends AsyncTask<String, Integer, Long> {
public ParserTask() {
}
@Override
protected void onPreExecute() {
// getSegmentListFromServer();
// readRss_Segment(LinkSegment[count]);
}
@Override
protected Long doInBackground(String... params) {
return null;
}
@Override
protected void onPostExecute(Long arg0) {
kangoo = DecodeFile(LinkImage[count]);
kangoo = Bitmap.createScaledBitmap(kangoo, DeviceWidth, height,
true);
d = new DrawableImageView(test2.this, kangoo);
l.addView(d);
mProgressBar.setVisibility(View.GONE);
}
}
public void goLeft() {
//leftImage=topImage=0;
setNullAsyncTask();
if (count == 0) {
// count=0;
} else {
count = count - 1;
}
// kangoo = DecodeFile(LinkImage[count]);
// kangoo = Bitmap.createScaledBitmap(kangoo, DeviceWidth, height,
// true);
mProgressBar.setVisibility(View.VISIBLE);
countDown = new MainCountDown(180, 180);
countDown.start();
Toast.makeText(test2.this, "GO LEFT " + count, Toast.LENGTH_SHORT)
.show();
}
public void goRight() {
//leftImage=topImage=0;
setNullAsyncTask();
if (count == 5) {
// count=2;
} else {
count = count + 1;
}
mProgressBar.setVisibility(View.VISIBLE);
countDown = new MainCountDown(180, 180);
countDown.start();
Toast.makeText(test2.this, "GO RIGHT " + count, Toast.LENGTH_SHORT)
.show();
}
public void goTop() {
setNullAsyncTask();
mProgressBar.setVisibility(View.VISIBLE);
countDown = new MainCountDown(180, 180);
countDown.start();
Toast.makeText(test2.this, "BackWard Document", Toast.LENGTH_SHORT)
.show();
}
public void goBottom() {
setNullAsyncTask();
mProgressBar.setVisibility(View.VISIBLE);
countDown = new MainCountDown(180, 180);
countDown.start();
Toast.makeText(test2.this, "ForWard Document", Toast.LENGTH_SHORT)
.show();
}
private void setNullAsyncTask() {
if (parserTask != null) {
parserTask.cancel(true);
parserTask = null;
}
}
public class MainCountDown extends CountDownTimer {
public MainCountDown(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
@Override
public void onFinish() {
l.removeAllViews();
// GlobalVariable.clearBitmap();
parserTask = new ParserTask();
parserTask.execute();
}
@Override
public void onTick(long millisUntilFinished) {
}
}
public void populateView() {
ValueListIndex.removeAll(ValueListIndex);
for (int i = 0; i < FirstListIndex.size(); i++) {
ValueListIndex.add(FirstListIndex.get(i));
}
mQuickAction = new QuickAction(this);
for (int i = 0; i < ValueListIndex.size(); i++) {
int t = i+1;
ActionItem Item = new ActionItem(t,ValueListIndex.get(i)+": "
+ ValueListIndex.get(i), getResources().getDrawable(
R.drawable.creditor_icon));
mQuickAction.addActionItem(Item);
}
/* ActionItem creditorItem = new ActionItem(ID_CREDITOR, "Creditor :"
+ ValueListIndex.get(0), getResources().getDrawable(
R.drawable.creditor_icon));
ActionItem amountItem = new ActionItem(ID_AMOUNT, "Amount :"
+ ValueListIndex.get(1), getResources().getDrawable(
R.drawable.amount_icon));
ActionItem currencyItem = new ActionItem(ID_CURRENCY, "Currency :"
+ ValueListIndex.get(2), getResources().getDrawable(
R.drawable.currency_icon));
ActionItem typeItem = new ActionItem(ID_TYPE, "Type :"
+ ValueListIndex.get(3), getResources().getDrawable(
R.drawable.type_icon));
mQuickAction = new QuickAction(this);
mQuickAction.addActionItem(creditorItem);
mQuickAction.addActionItem(amountItem);
mQuickAction.addActionItem(currencyItem);
mQuickAction.addActionItem(typeItem);
*/
mQuickAction
.setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() {
// @Override
public void onItemClick(QuickAction quickAction, int pos,
int actionId) {
ActionItem actionItem = quickAction.getActionItem(pos);
positionChange = pos;
IndexSelected = ValueListIndex.get(pos);
showAddDialog();
Toast.makeText(test2.this, actionItem.getTitle(),
Toast.LENGTH_SHORT).show();
}
});
// setup on dismiss listener, set the icon back to normal
mQuickAction.setOnDismissListener(new PopupWindow.OnDismissListener() {
// @Override
public void onDismiss() {
// mMoreIv.setImageResource(R.drawable.ic_list_more);
mQuickAction.dismiss();
}
});
}
private void showAddDialog() {
final String TAG = "test";
final Dialog loginDialog = new Dialog(this);
loginDialog.getWindow().setFlags(
WindowManager.LayoutParams.FLAG_BLUR_BEHIND,
WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
loginDialog.setTitle("Change Value");
LayoutInflater li = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View dialogView = li.inflate(R.layout.add_dailog, null);
loginDialog.setContentView(dialogView);
loginDialog.show();
NewValueEditText = (EditText) dialogView.findViewById(R.id.newValue);
NewValueEditText.setText(IndexSelected);
NewValueEditText.setOnClickListener(new View.OnClickListener() {
// @Override
public void onClick(View v) {
NewValueEditText.setText("");
}
});
Button addButton = (Button) dialogView.findViewById(R.id.add_button);
Button cancelButton = (Button) dialogView
.findViewById(R.id.cancel_button);
addButton.setOnClickListener(new OnClickListener() {
// @Override
public void onClick(View v) {
NewValue = NewValueEditText.getText().toString();
loginDialog.dismiss();
FirstListIndex.remove(positionChange);
FirstListIndex.add(positionChange, NewValue);
populateView();
Toast.makeText(
getBaseContext(),
"You've changed succesfully to new value : " + NewValue,
Toast.LENGTH_LONG).show();
}
});
cancelButton.setOnClickListener(new OnClickListener() {
// @Override
public void onClick(View v) {
loginDialog.dismiss();
}
});
}
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
return false;
}
}<file_sep>/src/aexp/explist/RenameGroup.java
package aexp.explist;
import java.util.ArrayList;
import java.util.List;
import com.sskk.example.bookprovidertest.provider.NewDBAdapter;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class RenameGroup extends Activity {
private Button mRename;
List<String> GroupListEnablefromDB = new ArrayList();
private EditText mGroupName;
private String NewNameGroup;
private String OldNameGroup;
private String messageNameGroup;
NewDBAdapter mDB;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.renamegroup);
mDB = new NewDBAdapter(getApplicationContext());
mDB.openDB();
mGroupName = (EditText) findViewById(R.id.namegroup);
Bundle bundle = this.getIntent().getExtras();
CharSequence textMessage = bundle.getCharSequence("messageNameGroup");
messageNameGroup = "" + textMessage;
mGroupName.setText(messageNameGroup);
mGroupName.setOnClickListener(new View.OnClickListener() {
//@Override
public void onClick(View v) {
mGroupName.setText("");
}
});
updateNumberOfGroupinDB();
mRename = (Button) findViewById(R.id.RenameButton);
mRename.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
NewNameGroup = mGroupName.getText().toString();
renameGroup(messageNameGroup, NewNameGroup);
}
});
}
public void updateNumberOfGroupinDB() {
GroupListEnablefromDB.clear();
Cursor c = mDB.getGroupByEnable("1");
if (c.moveToFirst()) {
do {
GroupListEnablefromDB.add(c.getString(1));
} while (c.moveToNext());
}
c.close();
GroupListEnablefromDB.remove(0);
}
public void renameGroup(String GroupOldName, String GroupNewName) {
mDB.renameGroup(GroupOldName, GroupNewName);
Toast.makeText(this, "Rename Successfully !", Toast.LENGTH_SHORT)
.show();
Intent intent = new Intent();
intent.setClass(RenameGroup.this, ANDROID_RSS_READER.class);
startActivity(intent);
// finish();
// reload();
}
public void reload() {
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
<file_sep>/src/com/android/TestSegment/RSSHandler_Reader_Segment.java
package com.android.TestSegment;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class RSSHandler_Reader_Segment extends DefaultHandler {
final int state_unknown = 0;
final int state_x = 1;
final int state_y = 2;
final int state_h = 3;
final int state_w = 4;
final int state_segmentID = 5;
int currentState = state_unknown;
RSSFeed_Reader_Segment feed;
RSSItem_Reader item;
boolean itemFound = false;
public RSSHandler_Reader_Segment(){
}
public RSSFeed_Reader_Segment getFeed(){
return feed;
}
@Override
public void startDocument() throws SAXException {
// TODO Auto-generated method stub
feed = new RSSFeed_Reader_Segment();
item = new RSSItem_Reader();
}
@Override
public void endDocument() throws SAXException {
// TODO Auto-generated method stub
}
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
// TODO Auto-generated method stub
if (localName.equalsIgnoreCase("segment")){
itemFound = true;
item = new RSSItem_Reader();
currentState = state_unknown;
}
else if (localName.equalsIgnoreCase("x")){
currentState = state_x;
}
else if (localName.equalsIgnoreCase("y")){
currentState = state_y;
}
else if (localName.equalsIgnoreCase("h")){
currentState = state_h;
}
else if (localName.equalsIgnoreCase("w")){
currentState = state_w;
}
else if (localName.equalsIgnoreCase("segmentID")){
currentState = state_segmentID;
}
else{
currentState = state_unknown;
}
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
// TODO Auto-generated method stub
if (localName.equalsIgnoreCase("segment")){
feed.addItem(item);
}
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
// TODO Auto-generated method stub
String strCharacters = new String(ch,start,length);
if (itemFound==true){
// "item" tag found, it's item's parameter
switch(currentState){
case state_x:
item.setX(strCharacters);
break;
case state_y:
item.setY(strCharacters);
break;
case state_h:
item.setH(strCharacters);
break;
case state_w:
item.setW(strCharacters);
break;
case state_segmentID:
item.setSegmentID(strCharacters);
break;
default:
break;
}
}
else{
// not "item" tag found, it's feed's parameter
switch(currentState){
case state_x:
feed.setX(strCharacters);
break;
case state_y:
feed.setY(strCharacters);
break;
case state_h:
feed.setH(strCharacters);
break;
case state_w:
feed.setW(strCharacters);
break;
default:
break;
}
}
currentState = state_unknown;
}
}
|
85c0173316d9f92ec9056d68cf871b358f39392b
|
[
"Java"
] | 11
|
Java
|
oxsala/Android-Oxplorer
|
229c587e3109dc9e8d614b539347a79994a80476
|
077cd5b70560b1683a0271d9f6b66388c7fad1bf
|
refs/heads/master
|
<repo_name>Kick1911/unitest<file_sep>/tests/Makefile
ROOT = ..
include ../project.mk
include ../config.mk
DEBUG = -g3
TESTS_C = ${shell find . -name 'test_*.c'}
TESTS_OUT := ${TESTS_C:%.c=%.out}
all: shared_library ${TESTS_OUT}
${TESTS_OUT}: %.out: %.c
${call print,${GREEN}BIN $@}
${Q}${CC} $< -o $@ ${CFLAGS} ${LDFLAGS} ${APP_NAME:%=-l%}
shared_library:
${Q}DEBUG=-g3 ${MAKE} -C .. shared_library
test: all
@for exe in $(TESTS_OUT) ; do \
LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:${shell pwd}/.. valgrind --error-exitcode=1 --leak-check=full $$exe ; \
done
clean:
${call print,${BRIGHT_CYAN}CLEAN ${APP_NAME} tests}
${Q}${RM} ${TESTS_OUT}
.PHONY: clean all shared_library test
<file_sep>/Makefile
# Made with C Project Manager
# Author: <NAME> (<EMAIL>)
include config.mk
include project.mk
ARCHIVE_FILES := ${APP_NAME:%=lib%.a}
LIBRARY_FILES := ${APP_NAME:%=lib%.so}
all: set_debug_vars dep ${APP_NAME}
set_debug_vars:
${eval DEBUG = -g3}
${APP_NAME}: %: ${SRC_PATH}/%.o ${COMP_O} ${UTILS_O}
${call print,${GREEN}BIN $@}
${Q}${CC} $^ -o $@ ${CFLAGS} ${LDFLAGS}
%.o: %.c
${call print,${CYAN}CC $@}
${Q}${CC} -c $< -o $@ ${CFLAGS}
static_library: dep ${ARCHIVE_FILES}
${ARCHIVE_FILES}: ${COMP_O} ${UTILS_O}
${call print,${BROWN}AR $@}
${Q}cd ${LIB_PATH}; ar -x *.a || true
${Q}ar -cq $@ $^ ${shell find ${LIB_PATH} -name '*.o'}
set_pic:
${eval CFLAGS += -fPIC}
shared_library: set_pic dep ${LIBRARY_FILES}
${LIBRARY_FILES}: ${COMP_O} ${UTILS_O}
${call print,${BRIGHT_MAGENTA}LIB $@.${VERSION}}
${Q}${CC} -shared -Wl,-soname,$@ -o $@.${VERSION} $^ ${LDFLAGS}
${call print,${BRIGHT_CYAN}SYMLINK $@}
${Q}ln -sf $@.${VERSION} $@
dep: ${DEPENDENCIES:%=${LIB_PATH}/%}
test:
${MAKE} test -C tests
${LIB_PATH}/%:
${eval WORD_LIST = ${subst /, ,$@}}
${eval ORG = ${word 2, ${WORD_LIST}}}
${eval PROJECT = ${word 3, ${WORD_LIST}}}
${eval VERSION = ${word 4, ${WORD_LIST}}}
${eval LIB_NAME = ${word 5, ${WORD_LIST}}}
${eval NAME = ${word 1, ${subst ., ,${LIB_NAME:lib%=%}}}}
${Q}mkdir -p ${dir $@}
${call get_archive,${ORG}/${PROJECT},${VERSION},${LIB_NAME},$@}
${Q}mkdir -p ${INCLUDE_PATH}
${call get_header,${ORG}/${PROJECT},${VERSION},${NAME},${INCLUDE_PATH}}
${Q}ln -sf ${shell pwd}/$@ ${shell pwd}/${LIB_PATH}/${LIB_NAME}
set_prod_vars:
${eval DEBUG = -O3}
prod: set_prod_vars dep ${APP_NAME}
install: ${INSTALL_STEPS}
install_binary: ${INSTALL_PATH}/bin/
${call print,${GREEN}INSTALL $<}
${Q}cp ${APP_NAME} ${INSTALL_PATH}/bin/
install_static: ${ARCHIVE_FILES} ${APP_NAME:%=${SRC_PATH}/%.h} ${INSTALL_PATH}/include/ ${INSTALL_PATH}/lib/
${call print,${GREEN}INSTALL $<}
${Q}cp ${APP_NAME:%=${SRC_PATH}/%.h} ${INSTALL_PATH}/include/
${Q}cp ${ARCHIVE_FILES} ${INSTALL_PATH}/lib/
install_shared: ${APP_NAME:%=lib%.so.${VERSION}} ${APP_NAME:%=${SRC_PATH}/%.h} ${INSTALL_PATH}/include/ ${INSTALL_PATH}/lib/
${call print,${GREEN}INSTALL $<}
${Q}cp ${APP_NAME:%=${SRC_PATH}/%.h} ${INSTALL_PATH}/include/
${Q}cp ${APP_NAME:%=lib%.so.${VERSION}} ${INSTALL_PATH}/lib/
install_share_folder: ${APP_NAME:%=${INSTALL_PATH}/share/%}
${call print,${GREEN}INSTALL $<}
${Q}cp -R ${SHARE_PATH}/* ${APP_NAME:%=${INSTALL_PATH}/share/%}
${INSTALL_PATH}/%:
${call print,${GREEN}MKDIR $@}
${Q}mkdir -p $@
clean:
${call print,${BRIGHT_CYAN}CLEAN ${APP_NAME}}
${Q}${MAKE} -C tests clean
${Q}${RM} ${APP_NAME} ${APP_NAME:%=${SRC_PATH}/%.o} ${APP_NAME:%=lib%.*} ${COMP_O} ${UTILS_O}
.PHONY: clean set_prod_vars set_debug_vars prod all set_pic install install_share_folder install_shared install_binary install_static dep
<file_sep>/config.mk
ROOT ?= .
SRC_PATH = ${ROOT}/src
COMP_PATH = ${SRC_PATH}/components
DEP_PATH = ${SRC_PATH}/dependents
UTILS_PATH = ${SRC_PATH}/utils
TESTS_PATH = ${ROOT}/tests
INCLUDE_PATH = ${ROOT}/include
SHARE_PATH = ${ROOT}/share
LIB_PATH = ${ROOT}/lib
COMP_C = ${shell find ${COMP_PATH} -name '*.c'}
UTILS_C = ${shell find ${UTILS_PATH} -name '*.c'}
TESTS_C = ${shell find ${TESTS_PATH} -name '*.c'}
COMP_O = ${COMP_C:%.c=%.o}
UTILS_O = ${UTILS_C:%.c=%.o}
LDFLAGS += -L${ROOT} -L${LIB_PATH}
CFLAGS += ${DEBUG} -ansi -pedantic -Wall -Wno-deprecated-declarations -I${SRC_PATH} -I${INCLUDE_PATH}
ifneq ($(V),1)
Q := @
# Do not print "Entering directory ...".
MAKEFLAGS += --no-print-directory
endif
GREEN = \033[0;32m
BROWN = \033[0;33m
YELLOW = \033[1;33m
MAGENTA = \033[0;35m
BRIGHT_MAGENTA = \033[1;35m
CYAN = \033[0;36m
BRIGHT_CYAN = \033[1;36m
NC = \033[0m
define print
@echo -e ' ${1}${NC}'
endef
define get_archive
curl -L -f 'https://github.com/${1}/releases/download/${2}/${3}' \
-o ${4}
endef
define get_header
curl -L -f 'https://raw.githubusercontent.com/${1}/${2}/src/${3}.h' \
-o ${4}/${3}.h
endef
<file_sep>/tests/test_dot.c
#define T_REPORTER_DOT 1
#include "base_test.c"
<file_sep>/src/unitest.h
/**
* BSD 3-Clause License
*
* Copyright (c) 2019, <NAME> <<EMAIL>>
* 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 copyright holder 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.
*/
#ifndef UNITEST
#define UNITEST
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define T_SETUP_RESULT_SIZE (10)
#define T_SUITE_SETUP_RESULT_SIZE (10)
#define T_FAIL_COLOUR (31)
#define T_PASS_COLOUR (32)
#define T_GREY_COLOUR (90)
#define _T_DO_NOTHING do {} while(0)
#ifdef T_REPORTER_LIST
#define _T_SUITE_TITLE(msg) _T_DO_NOTHING
#define _T_TEST_FAIL_MSG(msg_format, a, b) \
char format[] = "[%s] %s:%d: "#msg_format"\n"; \
T_SET_COLOUR(stderr, T_FAIL_COLOUR); \
fprintf(stderr, "✘"); \
T_SET_COLOUR(stderr, T_GREY_COLOUR); \
fprintf(stderr, " %s: ", _suite_title); \
T_FAIL_DEBUG_MSG(format, a, b); \
T_RESET_COLOUR(stderr)
#define _T_TEST_PASS_MSG() \
T_SET_COLOUR(stdout, T_PASS_COLOUR); \
fprintf(stdout, "✔"); \
T_SET_COLOUR(stdout, T_GREY_COLOUR); \
fprintf(stdout, " %s %s\n", _suite_title, _test_title); \
T_RESET_COLOUR(stdout)
#define _T_CONCLUDE() \
if(T_PASSED < T_COUNT){ \
fprintf(stderr, "\n\n"); \
T_SET_COLOUR(stderr, T_FAIL_COLOUR); \
fprintf(stderr, "%d of %d tests failed\n", T_COUNT - T_PASSED, T_COUNT); \
T_RESET_COLOUR(stderr); \
return 1; \
} \
fprintf(stdout, "\n\n"); \
T_SET_COLOUR(stdout, T_PASS_COLOUR); \
fprintf(stdout, "%d tests completed\n", T_PASSED); \
T_RESET_COLOUR(stdout)
#elif T_REPORTER_DOT
#define _T_SUITE_TITLE(msg) _T_DO_NOTHING
#define _T_TEST_FAIL_MSG(msg, a, b) \
T_SET_COLOUR(stderr, T_FAIL_COLOUR); \
fprintf(stderr, "!"); \
T_RESET_COLOUR(stderr)
#define _T_TEST_PASS_MSG() \
T_SET_COLOUR(stdout, T_GREY_COLOUR); \
fprintf(stdout, "."); \
T_RESET_COLOUR(stdout)
#define _T_CONCLUDE() \
fprintf(stdout, "\n\n"); \
T_SET_COLOUR(stdout, T_PASS_COLOUR); \
fprintf(stdout, "%d passing\n", T_PASSED); \
T_RESET_COLOUR(stdout); \
if(T_PASSED < T_COUNT){ \
T_SET_COLOUR(stderr, T_FAIL_COLOUR); \
fprintf(stderr, "%d failing\n", T_COUNT - T_PASSED); \
T_RESET_COLOUR(stderr); \
return 1; \
}
#else
/** T_REPORTER_SPEC as default */
#define _T_SUITE_TITLE(msg) \
_PRINTF_INDENT(stdout); \
fprintf(stdout, "%s\n", msg)
#define _T_TEST_FAIL_MSG(msg_format, a, b) \
char format[] = "✘ [%s] %s:%d: "#msg_format"\n"; \
T_SET_COLOUR(stderr, T_FAIL_COLOUR); \
_PRINTF_INDENT(stderr); \
T_FAIL_DEBUG_MSG(format, a, b); \
T_RESET_COLOUR(stderr)
#define _T_TEST_PASS_MSG() \
T_SET_COLOUR(stdout, T_PASS_COLOUR); \
_PRINTF_INDENT(stdout); \
fprintf(stdout, "✔"); \
T_RESET_COLOUR(stdout); \
fprintf(stdout, " %s\n", _test_title)
#define _T_CONCLUDE() \
if(T_PASSED < T_COUNT){ \
T_SET_COLOUR(stderr, T_FAIL_COLOUR); \
fprintf(stderr, "✘ %d of %d tests failed\n", T_PASSED, T_COUNT); \
T_RESET_COLOUR(stderr); \
return 1; \
} \
T_SET_COLOUR(stdout, T_PASS_COLOUR); \
fprintf(stdout, "✔ %d tests completed\n", T_PASSED); \
T_RESET_COLOUR(stdout)
#endif
#define T_SUITE(title, code) \
_T_SUITE_TITLE(#title); \
T_PRINT_LEVEL++; \
{ \
char _title[] = #title; \
void** SUITE_SETUP_RESULT = NULL; \
_suite_title = _title; \
if(T_SUITE_SETUP_FUNC){ \
SUITE_SETUP_RESULT = (void**)malloc(sizeof(void*) * T_SUITE_SETUP_RESULT_SIZE); \
T_SUITE_SETUP_FUNC(SUITE_SETUP_RESULT); \
T_SUITE_SETUP_FUNC = 0; \
} \
{code;} \
if(T_SUITE_TEARDOWN_FUNC){ \
T_SUITE_TEARDOWN_FUNC(SUITE_SETUP_RESULT); \
T_SUITE_TEARDOWN_FUNC = 0; \
} \
_suite_title = NULL; /** reset suite title */ \
free(SUITE_SETUP_RESULT); \
} \
T_PRINT_LEVEL--
#define T_FAILED(msg, a, b) \
_T_TEST_FAIL_MSG(msg, a, b); \
T_FLAG = 1
#define T_PASSED() \
_T_TEST_PASS_MSG(); \
T_PASSED++
#define TEST(title, code) NEG_FLAG = 1; MAIN_TEST(title, code)
#define MAIN_TEST(title, code) T_FLAG = 0; T_COUNT++; \
{ \
char _title[] = #title; \
void** T_SETUP_RESULT = NULL; \
_test_title = _title; \
if(T_SETUP_FUNC){ \
T_SETUP_RESULT = (void**)malloc(sizeof(void*) * T_SETUP_RESULT_SIZE); \
T_SETUP_FUNC(T_SETUP_RESULT); \
} \
{code;} \
if(T_TEARDOWN_FUNC){ T_TEARDOWN_FUNC(T_SETUP_RESULT); } \
free(T_SETUP_RESULT); \
if(!T_FLAG){ \
T_PASSED(); \
} \
_test_title = NULL; /** reset test title */ \
}
#define ASSERT(statement, op1, op2, format) \
if(!!(statement) ^ NEG_FLAG){ T_FAILED(format, op1, op2); }
#define T_ASSERT(statement) \
ASSERT(statement, #statement, "", "%s%s")
#define T_ASSERT_STRING(a, b) \
ASSERT(!strcmp((a), (b)), (a), (b), "%s != %s")
#define T_ASSERT_CHAR(a, b) \
ASSERT((a) == (b), (a), (b), "%c != %c")
#define T_ASSERT_NUM(a, b) \
if(sizeof(a) <= sizeof(int)){ \
ASSERT((a) == (b), (a), (b), "%d != %d"); \
}else if(sizeof(a) == sizeof(long)){ \
ASSERT((a) == (b), (a), (b), "%ld != %ld"); \
}
#define T_ASSERT_FLOAT(a, b) \
ASSERT(fabs((a) - (b)) < T_EPSILON_FLOAT, (a), (b), "%f != %f")
#define T_ASSERT_DOUBLE(a, b) \
ASSERT(fabs((a) - (b)) < T_EPSILON_DOUBLE, (a), (b), "%f != %f")
#define _PRINTF_INDENT(stream) \
{ int i = T_PRINT_LEVEL; \
while(i--){ fprintf(stream, " "); } }
#define T_SET_COLOUR(stream, colour) fprintf(stream, "\033[1;%dm", colour)
#define T_RESET_COLOUR(stream) fprintf(stream, "\033[0m")
#define T_FAIL_DEBUG_MSG(format, a, b) \
fprintf(stderr, format, _test_title, __FILE__, __LINE__, (a), (b))
#define T_SETUP(func) T_SETUP_FUNC = func
#define T_TEARDOWN(func) T_TEARDOWN_FUNC = func
#define T_SUITE_SETUP(func) T_SUITE_SETUP_FUNC = func
#define T_SUITE_TEARDOWN(func) T_SUITE_TEARDOWN_FUNC = func
#define T_CONCLUDE _T_CONCLUDE
typedef void (*_test_function_t)(void**);
char T_FLAG, NEG_FLAG, *_test_title, *_suite_title;
int T_COUNT = 0, T_PASSED = 0, T_PRINT_LEVEL = 0;
double T_EPSILON_FLOAT = 0.000001,T_EPSILON_DOUBLE = 0.000000000000001;
_test_function_t T_SETUP_FUNC = 0, T_SUITE_SETUP_FUNC = 0;
_test_function_t T_TEARDOWN_FUNC = 0, T_SUITE_TEARDOWN_FUNC = 0;
#endif
<file_sep>/tests/test_list.c
#define T_REPORTER_SPEC 1
#include "base_test.c"
<file_sep>/tests/suite.c
#include <unitest.h>
#include <stdio.h>
#include <string.h>
#include <malloc.h>
#ifdef MAIN
#include <suite_functions.c>
int main(void){
#endif
T_SUITE_SETUP(&suite_setup);
T_SUITE_TEARDOWN(&suite_teardown);
T_SUITE(String test,
TEST(Character isEqual,
char* ptr = SUITE_SETUP_RESULT[1];
T_ASSERT_CHAR(*ptr, 'T');
);
TEST(String isEqual,
T_ASSERT_STRING((char*)SUITE_SETUP_RESULT[0], "This is a test");
);
);
T_SUITE(Binary operations,
TEST(Setup and teardown disabled,
/* Test teardown with valgrind */
T_ASSERT(!T_SETUP_RESULT);
);
TEST(OR,
T_ASSERT_NUM(1 | 0, 1);
);
TEST(XOR,
T_ASSERT_NUM(1 ^ 0, 1);
);
TEST(AND,
T_ASSERT_NUM(1 & 0, 0);
);
TEST(NOT,
T_ASSERT_NUM(!1, 0);
);
TEST(TWOs compliment,
T_ASSERT_NUM(~1, -2);
);
);
T_SUITE(Decimal operations,
TEST(Setup and teardown disabled,
/* Test teardown with valgrind */
T_ASSERT(!T_SETUP_RESULT);
);
TEST(Subtract,
T_ASSERT_NUM(1 - 0, 1);
);
TEST(Multiply,
T_ASSERT_NUM(1 * 0, 0);
);
TEST(Addition,
T_ASSERT_NUM(-1 + 1, 0);
);
TEST(Division,
T_ASSERT_FLOAT((double)1/5, (double)0.2);
);
);
#ifdef MAIN
T_CONCLUDE();
return 0;
}
#endif
<file_sep>/tests/suite_functions.c
void suite_setup(void** args){
char* ptr;
args[0] = "This is a test";
args[1] = malloc(sizeof(char));
ptr = args[1];
*ptr = 'T';
}
void suite_teardown(void** args){
free(args[1]);
}
<file_sep>/tests/base_test.c
#define _GNU_SOURCE
#include <unitest.h>
#include <stdio.h>
#include <string.h>
#include <malloc.h>
#include "suite_functions.c"
void print(char* a){
printf("%s\n", a);
}
void setup(void** args){
/** Set args - limited to 10 args */
args[0] = "I am Kick";
args[1] = malloc(sizeof(char));
}
void teardown(void** args){
/** Free all args */
free(args[1]);
}
int main(void){
FILE* save_stderr;
char* buffer;
size_t size;
TEST(Negative testing,
T_ASSERT(!(1 < 0));
/* T_ASSERT_NUM(1, 0);
long int a = 1 << 31;
long int b = a*a;
T_ASSERT_NUM(b, 0);
char n[] = "Kick";
char m[] = "Ness";
T_ASSERT_STRING(n, m); */
);
TEST(String tests,
char a[] = "nbionob <F9>82r32h9nrwn 9h489h 4<F9><F10><F3><F2>niom o";
char b[] = "nbionob <F9>82r32h9nrwn 9h489h 4<F9><F10><F3><F2>niom o";
T_ASSERT_STRING(a, b);
T_ASSERT_STRING("Kickness", "Kickness");
);
TEST(Integer tests,
int var = 1;
long int a = 1 << 31;
long int b = a*a;
T_ASSERT(1 == 1);
T_ASSERT_NUM(var, 1);
T_ASSERT_NUM(b, a*a);
);
T_SETUP(&setup);
T_TEARDOWN(&teardown);
TEST(Setup,
T_ASSERT_STRING((char*)T_SETUP_RESULT[0], "I am Kick");
);
TEST(Pointer tests,
char* a = NULL;
char* b = NULL;
a = malloc(sizeof(char) * 5);
strcpy(a, "Kick");
T_ASSERT(a);
T_ASSERT(!b);
free(a);
);
TEST(Float type tests,
float f = 3.14;
float* fp = &f;
T_ASSERT_FLOAT(0.5, 0.5f);
T_ASSERT_FLOAT((float) 22/7, (float) 22/7);
T_ASSERT_FLOAT(*fp, 3.14);
);
TEST(Double type tests,
double f = 3.14;
double* fp = &f;
T_ASSERT_FLOAT((double) 22/7, (double) 22/7);
T_ASSERT_FLOAT(*fp, 3.14);
);
T_SETUP(0);
T_TEARDOWN(0);
TEST(Disable setup,
T_ASSERT(!T_SETUP_RESULT);
);
save_stderr = stderr;
stderr = open_memstream(&buffer, &size);
TEST(Failing tests,
int var = 1;
T_ASSERT_NUM(var, 0);
T_ASSERT_CHAR('a', 'b');
T_ASSERT_FLOAT(0.465, 458.1375);
T_ASSERT_STRING("Not", "Equal");
T_ASSERT(5 == 9);
);
T_PASSED++;
fclose(stderr);
#ifdef __clang__
free(stderr);
#endif
printf("%s\n", buffer);
stderr = save_stderr;
/** Formatter tests */
#ifdef T_REPORTER_LIST
#elif T_REPORTER_DOT
TEST(Failed messages,
int count = 0;
char* ptr = buffer;
ptr = strchr(ptr, '!');
while(ptr){
T_ASSERT(ptr);
ptr = strchr(ptr+1, '!');
count++;
}
T_ASSERT_NUM(count, 5);
);
#else
/** T_REPORTER_SPEC */
{
char* failed_msgs[] = {"\"1 != 0\"",
"\"a != b\"",
"\"0.465000 != 458.137500\"",
"\"Not != Equal\"", "5 == 9", NULL};
char* start = buffer,
**ptr = failed_msgs,
*end;
while(*ptr){
char* ts = *ptr;
TEST(Failed messages,
end = strchr(start, '\n');
*end = 0;
T_ASSERT(strstr(start, ts));
start = end+1;
);
ptr++;
}
}
#endif
#include "suite.c"
free(buffer);
T_CONCLUDE();
return 0;
}
<file_sep>/project.mk
APP_NAME = unitest
VERSION = 0.0.1
INSTALL_PATH = /opt
CFLAGS += -DINSTALL_PATH=${INSTALL_PATH}
STATIC_DEP =
SHARED_DEP =
DEPENDENCIES =
LDFLAGS += ${STATIC_DEP:%=-l%} ${SHARED_DEP:%=-l%}<file_sep>/tests/test_spec.c
#define T_REPORTER_LIST 1
#include "base_test.c"
<file_sep>/README.md

# unitest
A unit testing framework for C. Written in 100% C89 ISO preprocessor code.
# Usage
I have designed this library to be easy-to-use. No init function needed (though, I am considering adding one). A `T_CONCLUDE` is needed at the end for final report and returning an error code if need be.
## Start testing
You can add all your code as the second parameter of the `TEST` macro.
```C
TEST(Integer tests,
long int a = 1 << 31;
long int b = a*a;
T_ASSERT(1 == 1);
T_ASSERT_NUM(1, 1);
T_ASSERT_NUM(b, a*a);
);
```
or simply call a function in the second parameter.
## Setup
A setup function can be added as follows:
```C
void setup(void** args);
T_SETUP(&setup);
```
The function should receive `void**` and return `void`.
By default you can 10 pointers to `args`. This can be changed with the definition, `T_SETUP_RESULT_SIZE`.
To access `args` in your test, use `T_SETUP_RESULT`.
To stop running the setup function, simply:
```C
T_SETUP(0);
```
## Teardown
You are responsible for deallocating all the memory you put into `T_SETUP_RESULT`.
The prototype for the teardown function follows the setup function. Adding the function is also similar.
## Test reporters
### Spec
This is the default reporter.
TODO: Add image
### List
To enable this reporter, compile with `-DT_REPORTER_LIST=1` argument.
TODO: Add image
### Dot
Looks like the python `unittest` reporter. To enable this reporter, compile with `-DT_REPORTER_DOT=1` argument.
TODO: Add image
## Test Suites
Test suites are done as follows, but of course you may substitute the second arguments for functions if you want to.
```C
T_SUITE(Binary operations,
TEST(OR,
T_ASSERT_NUM(1 | 0, 1);
);
TEST(XOR,
T_ASSERT_NUM(1 ^ 0, 1);
);
TEST(AND,
T_ASSERT_NUM(1 & 0, 0);
);
TEST(NOT,
T_ASSERT_NUM(!1, 0);
);
TEST(TWOs compliment,
T_ASSERT_NUM(~1, -2);
);
);
```
|
7c720eadc27d2936951f4ea843432afb9ef265cb
|
[
"Markdown",
"C",
"Makefile"
] | 12
|
Makefile
|
Kick1911/unitest
|
a5e71b06fd2ee9224e120aa85147ac333996d733
|
d2705c347e0f0128f6d436b190052311c0d5cca2
|
refs/heads/master
|
<repo_name>seiferdisast/kuepa-edu-tech<file_sep>/src/app/home/home.component.ts
import { Component, OnInit } from '@angular/core';
import { Customer, CustomerDetail } from '../customer';
import { CustomersService } from '../customers.service';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss'],
})
export class HomeComponent implements OnInit {
conexionAgendToDay: Customer[];
selectedAgenda: Customer;
selectedAgendaDetail: CustomerDetail;
constructor(private customerService: CustomersService) {
this.customerService
.getCustomers()
.then((customers) => (this.conexionAgendToDay = customers));
}
ngOnInit(): void {}
onClickAgenda(agenda: Customer) {
this.selectedAgenda = agenda;
this.customerService
.getCustomerById(agenda.account_id)
.then((agendaDetail) => (this.selectedAgendaDetail = agendaDetail));
console.log({ agenda });
}
}
<file_sep>/src/app/customers.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Customer, CustomerDetail } from './customer';
@Injectable({
providedIn: 'root',
})
export class CustomersService {
constructor(private http: HttpClient) {}
getCustomers(): Promise<Customer[]> {
return this.http
.get<Customer[]>('https://api.opendota.com/api/proPlayers')
.toPromise();
}
getCustomerById(accountId): Promise<CustomerDetail> {
return this.http
.get<CustomerDetail>('https://api.opendota.com/api/players/'+ accountId)
.toPromise();
}
}
<file_sep>/src/app/customer.ts
export interface Customer {
account_id: number;
steamid: string;
avatar: string;
avatarmedium: string;
avatarfull: string;
profileurl: string;
personaname: string;
last_login: Date;
full_history_time: Date;
cheese: number;
fh_unavailable: boolean;
loccountrycode: string;
name: string;
country_code: string;
fantasy_role: number;
team_id: number;
team_name: string;
team_tag: string;
is_locked: boolean;
is_pro: boolean;
locked_until: number;
}
export interface CustomerDetail {
tracked_until: string;
solo_competitive_rank: string;
competitive_rank: string;
rank_tier: number;
leaderboard_rank: number;
mmr_estimate: {
estimate: number;
stdDev: number;
n: number;
};
profile: {
account_id: number;
personaname: string;
name: string;
plus: boolean;
cheese: number;
steamid: string;
avatar: string;
avatarmedium: string;
avatarfull: string;
profileurl: string;
last_login: string;
loccountrycode: string;
is_contributor: false;
};
}
|
e1c17478d494d81d4c3c9b961829bcb1d701bf9f
|
[
"TypeScript"
] | 3
|
TypeScript
|
seiferdisast/kuepa-edu-tech
|
b0d4f7e52c54fed65c038e6f282f7484ebd54eb6
|
a1035566add388d9de37478678b048f2afe6ae88
|
refs/heads/master
|
<file_sep>
window.onload = function() {
let kb = document.getElementById("keyboard")
let txt = document.getElementById("xbox")
var chars = ['1', '2', '3', '/',
'4', '5', '6', 'x',
'7', '8', '9', '-',
'0', '.', '^', '+',
'(', ")", '←', 'AC',
]
let postfix = ""
let class2 = ""
for(let i=0; i<chars.length; i++) {
if(i>0 && (i+1)%4==0) {
postfix = '<br>'
class2 = "op"
}
else {
postfix = ""
class2 = "digit"
}
if(chars[i] == 'AC' || chars[i] == '←') {
class2 = "btnclear"
}
kb.innerHTML += `<input class="btn ${class2}" type="submit" id="button_${i}" onClick="addDigit('${chars[i]}')" value="${chars[i]}">${postfix}`;
}
txt.focus();
window.document.getElementsByTagName("body")[0].addEventListener("click", () => { txt.focus()})
window.document.getElementsByTagName("body")[0].addEventListener("keydown", () => { txt.focus()})
txt.addEventListener("input", calc )
//txt.addEventListener("blur", () => { txt.focus() }) //does not work. why?
}
function addDigit(digit){
let txt = document.getElementById("xbox")
let out = document.getElementById("outbox");
if (txt.value =='0' && digit != 'AC'){
txt.value = digit
}
else {
switch(digit){
case '←':
if (txt.value.length > 0) {
txt.value = txt.value.slice(0, txt.value.length-1)
}
calc()
break
case 'AC':
txt.value = ''
out.value = '0'
break
case '/':
case 'x':
case '*':
case '-':
txt.value += digit
calc()
break
default:
txt.value += digit
calc()
}
}
}
function calc() {
let expr = document.getElementById("xbox").value;
let out = document.getElementById("outbox");
expr = removeTrailingOperators(expr)
if (expr.includes("Invalid")) {
out.value = expr
}
else if(expr.length == 0) {
out.value = '0'
}
else {
let clean_expression = expr.replace(/x/g, "*")
clean_expression = clean_expression.replace(/\^/g, "**")
let n = Number(eval(clean_expression)).toPrecision(15).toString();
out.value = parseFloat(n)
}
}
function removeTrailingOperators(expr) {
let ops = /[/x+-.^]$/
let double_ops = /[/x+-.^][/x+-.^]$/
if(expr.length == 0){
return '0'
}
if(expr.match(/[.][0-9][.][0-9]/)){
return "Invalid Number!"
}
else if(expr.match(double_ops)){
return "Invalid Expression!"
}
//else if ((expr.match(/\./g) || []).length > 1){
// return "Invalid Number!"
// }
else if (expr[expr.length-1].match(ops)) {
console.log( removeTrailingOperators(expr.slice(0, expr.length-1)))
return removeTrailingOperators(expr.slice(0, expr.length-1))
}
else {
return expr
}
}
|
a9fd8e7877c07bb5466894d63945c6be2e506e73
|
[
"JavaScript"
] | 1
|
JavaScript
|
victordomingos/Learning_JavaScript
|
4a25c9a4503a82fbaf25f25f4337153c4a5b189a
|
ee5d16a36e3a9a5292dfb0c9a626fd59dab16d34
|
refs/heads/master
|
<file_sep>// ANCHOR Imports
import { useState, useEffect, useContext } from "react";
import PropTypes from "prop-types";
import { showModalAction } from "../../store/actions";
import { AppContext } from "../../store";
import ModalProduct from "../ModalProduct";
// ANCHOR Component
export default function CardProduct(props) {
const { product } = props;
const { dispatch } = useContext(AppContext);
const [price, setPrice] = useState(0);
// Formatando preço
function formatPrice(priceValue) {
const priceString = priceValue.toString();
const formatedPrice = `${priceString.slice(0, -2)},${priceString.slice(
-2
)}`;
setPrice(formatedPrice);
}
// Tornando o modal do componente visível
function showModal(e) {
e.preventDefault();
showModalAction(dispatch, product);
}
useEffect(() => {
formatPrice(product.price);
}, [product, price]);
// console.log(product);
// Component
return (
<div className="cardProduct">
<div
className="containerImage"
aria-hidden="true"
onClick={(e) => {
showModal(e);
}}
>
<img src={product.photo} alt={product.descriptionShort} />
<button type="button" className="btn buttonQuickView">
<div className="containerIcon">
<svg
xmlns="http://www.w3.org/2000/svg"
width="15.795"
height="15.795"
viewBox="0 0 15.795 15.795"
>
<g id="zoom-2" transform="translate(-0.087 -0.087)">
<line
id="Linha_9"
data-name="<NAME>"
x1="3.782"
y1="3.782"
transform="translate(11.393 11.393)"
fill="none"
stroke="#fff"
strokeLinecap="round"
strokeLinejoin="round"
strokeMiterlimit="10"
strokeWidth="1"
/>
<circle
id="Elipse_18"
data-name="Elipse 18"
cx="6"
cy="6"
r="6"
transform="translate(0.587 0.587)"
fill="none"
stroke="#fff"
strokeLinecap="round"
strokeLinejoin="round"
strokeMiterlimit="10"
strokeWidth="1"
/>
</g>
</svg>
</div>
<sub>Quick View</sub>
</button>
</div>
<div className="infoProduct">
<h2> {product.productName} </h2> <p> {product.descriptionShort} </p>
<p className="price"> R$ {price} </p>
</div>
<ModalProduct />
</div>
);
}
CardProduct.propTypes = {
product: PropTypes.objectOf(PropTypes.any),
};
CardProduct.defaultProps = {
product: {},
};
<file_sep>// ANCHOR Imports
// ANCHOR Component
export default function News() {
// Component
return (
<section className="news">
<div className="imageContainer">
<img
src="/images/pessoa_mexendo_em_uma_mesa_de_som.png"
alt="Pessoa mexendo em uma mesa de som"
/>
<img
src="/images/homem_segurando_uma_guitarra_lg.png"
alt="Pessoa mexendo em uma mesa de som"
/>
</div>
<div className="infoContainer container">
<div className="info">
<h3>NOVIDADES</h3>
<h2>
<strong>ÁUDIO</strong> <br /> PROFISSIONAL
</h2>
<button type="button" className="btn newBtn">
CONFIRA
</button>
</div>
<div className="info">
<h3>NOVIDADES</h3>
<h2>
<strong>INSTRUMENTOS</strong> <br /> MUSICAIS
</h2>
<button type="button" className="btn newBtn">
CONFIRA
</button>
</div>
</div>
</section>
);
}
<file_sep>// import { nameReducers } from "./name";
import { modalReducers } from "./modal";
export default function reducers(state, action) {
return modalReducers(state, action);
// return nameReducers(newState, action);
}
<file_sep>export function showModalAction(dispatch, payload) {
dispatch({ type: "SHOW_MODAL", payload });
}
export function closeModalAction(dispatch) {
dispatch({ type: "CLOSE_MODAL" });
}
<file_sep>// ANCHOR Imports
import ListInstruments from "./ListInstruments";
// ANCHOR Component
export default function InstrumentsMain() {
// Component
return (
<section className="InstrumentsMain">
<div className="container">
<div className="intro">
<h2>
INSTRUMENTOS <strong>DESTAQUE</strong>
</h2>
<p>
it is a long established fact that a reader will be distracted by
the readable
</p>
</div>
<div className="containerInstruments">
<ListInstruments />
</div>
</div>
</section>
);
}
<file_sep>// ANCHOR Imports
import PropTypes from "prop-types";
// ANCHOR Component
export default function Cart() {
// const { examepleProps } = props;
// Component
return (
<div className="cart">
<svg
id="_001-shopping-bag"
data-name="001-shopping-bag"
xmlns="http://www.w3.org/2000/svg"
width="21.76"
height="27.186"
viewBox="0 0 21.76 27.186"
>
<path
id="Caminho_1"
data-name="Caminho 1"
d="M70.554,23.5,69,5.971a.749.749,0,0,0-.745-.684h-3.2a5.371,5.371,0,0,0-10.741,0h-3.2a.745.745,0,0,0-.745.684L48.806,23.5c0,.022-.006.044-.006.067a3.874,3.874,0,0,0,4.081,3.619h13.6a3.874,3.874,0,0,0,4.081-3.619A.272.272,0,0,0,70.554,23.5ZM59.68,1.5a3.873,3.873,0,0,1,3.869,3.786H55.811A3.873,3.873,0,0,1,59.68,1.5Zm6.8,24.184h-13.6A2.4,2.4,0,0,1,50.3,23.6l1.49-16.806H54.3V9.073a.751.751,0,1,0,1.5,0V6.794h7.744V9.073a.751.751,0,0,0,1.5,0V6.794h2.513l1.5,16.806A2.4,2.4,0,0,1,66.479,25.685Z"
transform="translate(-48.8 0)"
fill="#fff"
/>
</svg>
<p>SEU CARRINHO</p>
<p>{0} item (s)</p>
</div>
);
}
Cart.propTypes = {
examepleProps: PropTypes.shape({
id: PropTypes.number,
examepleProps: PropTypes.string,
categories: PropTypes.instanceOf(Array),
}),
};
Cart.defaultProps = {
examepleProps: {},
};
<file_sep>import React from "react";
import { BrowserRouter as Router } from "react-router-dom";
import Route from "./Routes";
import Store from "./store";
import Header from "./components/Header";
import "./styles/SCSS/mainUseful.css";
export default function App() {
return (
<Store>
<Router>
<Header />
<main>
<Route />
</main>
</Router>
</Store>
);
}
<file_sep>// ANCHOR Imports
import React from "react";
import { Link } from "react-router-dom";
// ANCHOR Component
export default function Instrument() {
return (
<section className="instrumentsSection">
<div className="container">
<div className="instrumentCard">
<Link to="/">
<div className="containerImage">
<img
src="/images/homem_tocando_guitarra.png"
alt="Homem tocando guitarra"
/>
</div>
<h2>GUITARRAS</h2>
</Link>
</div>
<div className="instrumentCard">
<Link to="/">
<div className="containerImage">
<img
src="/images/microfone_perto_de_um_som.png"
alt="Micrfone perto de uma caixa de som"
/>
</div>
<h2>MICROFONES</h2>
</Link>
</div>
<div className="instrumentCard">
<Link to="/">
<div className="containerImage">
<img src="/images/mesa_de_som.png" alt="Mesa de som" />
</div>
<h2>MESA DE SOM</h2>
</Link>
</div>
<div className="instrumentCard">
<Link to="/">
<div className="containerImage">
<img
src="/images/maos_tocando_teclado.png"
alt="Mãos tocando teclado"
/>
</div>
<h2>TECLADOS</h2>
</Link>
</div>
<div className="instrumentCard">
<Link to="/">
<div className="containerImage">
<img src="/images/violao.png" alt="Violão deitado" />
</div>
<h2>VIOLAO</h2>
</Link>
</div>
<div className="instrumentCard">
<Link to="/">
<div className="containerImage">
<img src="/images/bateria.png" alt="Bateria vermelha" />
</div>
<h2>BATERIAS</h2>
</Link>
</div>
</div>
</section>
);
}
<file_sep>import { changeName } from "./name";
import { showModalAction, closeModalAction } from "./modal";
export { changeName, showModalAction, closeModalAction };
<file_sep>// import styled from "styled-components";
// // const primary = (props) => props.theme.colors.primary;
// // const primaryDark = (props) => props.theme.colors.primaryDark;
// export const Example = styled.div``;
<file_sep>import React from "react";
import PropTypes from "prop-types";
import reducer from "./reducers";
import dataJSON from "./data.json";
const initialState = {
cart: 0,
data: dataJSON,
modal: {
show: false,
data: [],
},
};
export const AppContext = React.createContext();
export default function Store({ children }) {
const [state, dispatch] = React.useReducer(reducer, initialState);
return (
<AppContext.Provider value={{ state, dispatch }}>
{children}
</AppContext.Provider>
);
}
Store.propTypes = {
children: PropTypes.node.isRequired,
};
<file_sep>export function addName(dispatch, name) {
dispatch({ type: "ADD_NAME", payload: name });
}
export function changeName(dispatch, name) {
dispatch({ type: "CHANGE_NAME", payload: name });
}
<file_sep>export function nameReducers(state, action) {
const firstNamePayload = action.payload.firstName;
const lastNamePayload = action.payload.newLastName;
switch (action.type) {
case "ADD_NAME":
return { ...state, name: `${state.name} ${action.payload}` };
case "CHANGE_NAME":
return {
...state,
firstName: firstNamePayload,
lastName: lastNamePayload,
};
default:
return state;
}
}
<file_sep>// ANCHOR Imports
// ANCHOR Hook
// Hook criado para consumir os dados da API dinamicamente
export default function UseApi() {
// Consumindo dados da API
return "";
}
<file_sep>// ANCHOR Imports
import Hero from "../../components/Hero";
import Instruments from "../../components/Instruments";
import News from "../../components/News";
import InstrumentsMain from "../../components/InstrumentsMain";
// ANCHOR Page
export default function Home() {
return (
<>
<Hero />
<Instruments />
<News />
<InstrumentsMain />
</>
);
}
<file_sep>export function modalReducers(state, action) {
const { payload } = action;
switch (action.type) {
case "SHOW_MODAL":
return { ...state, modal: { show: true, data: payload } };
case "CLOSE_MODAL":
return { ...state, modal: { show: false, data: [] } };
default:
return state;
}
}
|
f629088328d5cded865ca493962f95cc93377ab4
|
[
"JavaScript"
] | 16
|
JavaScript
|
brunopeople/ninja-som
|
8db3f1c9056c14964c3d5505562fb428ce81b7b1
|
cb122a473889e7ace22709c9e745c6d543cd93e2
|
refs/heads/master
|
<file_sep>using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace TourApp
{
public partial class FormTest : Form
{
private IServiceProvider _service;
public FormTest(IServiceProvider services)
{
_service = services;
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
TKDoanhThu_Form doanhthu_Form = _service.GetRequiredService<TKDoanhThu_Form>();
doanhthu_Form.Show();
}
}
}
<file_sep>using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TourApp.Const;
using TourApp.Context;
using TourApp.Entity;
using TourApp.Repository.IRepository;
namespace TourApp.Repository
{
public class DoanKhachRepository : IDoanKhachRepository
{
private TourContext _context;
public DoanKhachRepository(TourContext context)
{
_context = context;
}
public void Add(DoanKhach entity)
{
_context.DoanKhachs.Add(entity);
_context.SaveChanges();
}
public void Delete(DoanKhach entity)
{
entity.isDeleted = Status.Deleted;
_context.DoanKhachs.Update(entity);
_context.SaveChanges();
}
public IEnumerable<DoanKhach> getAll()
{
return _context.DoanKhachs.Where(dk => dk.isDeleted == Status.NotDeleted).Include(i => i.Tour).Include(i => i.CTDoans).ThenInclude(i=>i.HanhKhach)
.Include(i => i.NV_VTs).ThenInclude(i => i.NhanVien)
.Include(i => i.CTChitieus).ThenInclude(i => i.ChiTieu)
.Include(i => i.Gia)
.ToList();
}
public IEnumerable<DoanKhach> getAllDelete()
{
return _context.DoanKhachs.Where(dk => dk.isDeleted == Status.Deleted).Include(i => i.Tour).ToList();
}
public IEnumerable<DoanKhach> getWhere(string ID, string MaDoan, string TenDoan, string Chitiet, string Tinhtrang, string TourID, string MaTour, int isDeleted, string nameTour)
{
return _context.DoanKhachs.Include(i => i.Tour).Include(i => i.CTDoans).ThenInclude(i => i.HanhKhach)
.Include(i => i.NV_VTs).ThenInclude(i => i.NhanVien)
.Include(i => i.CTChitieus).ThenInclude(i => i.ChiTieu)
.Include(i => i.Gia)
.Where(dk => dk.isDeleted == isDeleted
&& dk.DoanId.ToString().Contains(ID)
&& dk.MaDoan.Contains(MaDoan)
&& dk.TenDoan.Contains(TenDoan)
&& dk.Chitiet.Contains(Chitiet)
&& dk.Status.Contains(Tinhtrang)
&& dk.TourId.ToString().Contains(TourID)
&& dk.Tour.MaTour.Contains(MaTour)
&& dk.Tour.Ten.Contains(nameTour))
.ToList();
}
public DoanKhach getById(int id, string maDK = "")
{
return _context.DoanKhachs.Where(dk => dk.DoanId == id || dk.MaDoan == maDK)
.Include(i => i.Tour).Include(i => i.Tour).Include(i => i.CTDoans).ThenInclude(i => i.HanhKhach)
.Include(i => i.NV_VTs).ThenInclude(i => i.NhanVien)
.Include(i => i.CTChitieus).ThenInclude(i => i.ChiTieu)
.Include(i => i.Gia)
.FirstOrDefault();
}
public void Update(DoanKhach entity)
{
_context.DoanKhachs.Update(entity);
_context.SaveChanges();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using TourApp.Entity;
using TourApp.Repository.IRepository;
namespace TourApp
{
public partial class DanhSachDoanKhach : Form
{
private readonly ITourRepository _tourRepository;
private Tour tour;
private int _id;
public DanhSachDoanKhach(ITourRepository tourRepository)
{
_tourRepository = tourRepository;
InitializeComponent();
}
public void getId(int id)
{
_id = id;
}
private void showthongtin()
{
tour = _tourRepository.getById(_id);
foreach (var doan in tour.DoanKhachs)
{
if (doan.isDeleted == 0)
{
ListViewItem item = new ListViewItem(new[] { doan.MaDoan, doan.TenDoan, doan.Chitiet });
doankhachlist.Items.Add(item);
}
}
}
protected override void OnLoad(EventArgs e)
{
showthongtin();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using TourApp.Entity;
using TourApp.Repository;
using TourApp.Repository.IRepository;
namespace TourApp
{
public partial class TK_NhanVienTour : Form
{
private readonly INhanVienRepository _nvRepo;
public TK_NhanVienTour(INhanVienRepository nvRepo)
{
InitializeComponent();
_nvRepo = nvRepo;
}
public void init()
{
//Xóa nền xám khi bị disable của listview
Bitmap bm = new Bitmap(lv.ClientSize.Width, lv.ClientSize.Height);
Graphics.FromImage(bm).Clear(lv.BackColor);
lv.BackgroundImage = bm;
readData();
}
//Lấy dữ liệu từ NhanVien và Đếm số lần đi tour của Nhân Viên
public void readData(string ID="", string MaNv="", string Ten="", string SDT="", int isDeleted=0)
{
lv.Items.Clear();
IEnumerable<NhanVien> nvs = _nvRepo.getWhere(ID,MaNv,Ten,SDT,isDeleted);
var dateStart = dateStartPicker.Value.Date;
var dateEnd = dateEndPicker.Value.Date;
foreach (NhanVien nv in nvs)
{
ListViewItem item = new ListViewItem(nv.MaNV);
item.SubItems.Add(nv.Ten);
//Đếm số lần đi tour
int count = nv.NV_VTs.Where(nv => (nv.DoanKhach.DateEnd.Date >= dateStart && nv.DoanKhach.DateEnd.Date <= dateEnd)).Count();
item.SubItems.Add(count.ToString()) ;
lv.Items.Add(item);
}
}
public void search()
{
var TenNV = txt_search.Text.ToLower();
readData("","",TenNV);
}
private Boolean validate()
{
var dateStart = dateStartPicker.Value.Date;
var dateEnd = dateEndPicker.Value.Date;
var flg = true;
if (dateEnd < dateStart)
{
flg = false;
}
if (!flg)
{
MessageBox.Show("Ngày tìm kiếm không hợp lệ", "Thông báo");
}
return flg;
}
private void TK_NhanVienTour_Load(object sender, EventArgs e)
{
init();
}
private void btn_Click(object sender, EventArgs e)
{
if (!validate()) return;
search();
}
}
}
<file_sep>using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TourApp.Const;
using TourApp.Context;
using TourApp.Entity;
using TourApp.Repository.IRepository;
namespace TourApp.Repository
{
public class HanhKhachRepository : IHanhKhachRepository
{
private TourContext _context;
public HanhKhachRepository(TourContext context)
{
_context = context;
}
public void Add(HanhKhach entity)
{
_context.HanhKhachs.Add(entity);
_context.SaveChanges();
}
public void Delete(HanhKhach entity)
{
entity.isDeleted = Status.Deleted;
_context.HanhKhachs.Update(entity);
_context.SaveChanges();
}
public IEnumerable<HanhKhach> getAll()
{
return _context.HanhKhachs.Where(hk => hk.isDeleted == Status.NotDeleted).ToList();
}
public IEnumerable<HanhKhach> getAllDelete()
{
return _context.HanhKhachs.Where(hk => hk.isDeleted == Status.Deleted).ToList();
}
public IEnumerable<HanhKhach> getWhere(string ID, string MaHK, string Ten,string SDT, string Email, string CMND, string Diachi,string Gioitinh, string Passport, int isDeleted)
{
return _context.HanhKhachs.Where(hk => hk.isDeleted == isDeleted
&& hk.KhachId.ToString().Contains(ID)
&& hk.MaKhach.Contains(MaHK)
&& hk.Ten.Contains(Ten)
&& hk.SDT.Contains(SDT)
&& hk.Email.Contains(Email)
&& hk.CMND.Contains(CMND)
&& hk.DiaChi.Contains(Diachi)
&& hk.GioiTinh.Contains(Gioitinh)
&& hk.Passport.Contains(Passport)
)
.ToList();
}
public HanhKhach getById(int id, string maHK = "")
{
return _context.HanhKhachs.Where(hk => hk.KhachId == id || hk.MaKhach == maHK).FirstOrDefault();
}
public void Update(HanhKhach entity)
{
_context.HanhKhachs.Update(entity);
_context.SaveChanges();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using TourApp.Entity;
namespace TourApp.Repository.IRepository
{
public interface IDiaDiemRepository : ICommonRepository<DiaDiem>
{
IEnumerable<DiaDiem> getWhere(string ID, string Ten);
DiaDiem getById(int DDId);
}
}
<file_sep>using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TourApp.Context;
using TourApp.Entity;
using TourApp.Repository.IRepository;
namespace TourApp.Repository
{
public class ChiTieuRepository : IChiTieuRepository
{
private TourContext _context;
public ChiTieuRepository(TourContext context)
{
_context = context;
}
public void Add(ChiTieu chiTieu)
{
_context.ChiTieus.Add(chiTieu);
_context.SaveChanges();
}
public void Delete(ChiTieu chiTieu)
{
_context.ChiTieus.Remove(chiTieu);
_context.SaveChanges();
}
public IEnumerable<ChiTieu> getAll()
{
return _context.ChiTieus.ToList();
}
public ChiTieu getById(int CTId)
{
return _context.ChiTieus.Where(ct => ct.CTId == CTId).Include(ct => ct.CTChitieus).ThenInclude(i => i.DoanKhach).FirstOrDefault();
}
public IEnumerable<ChiTieu> getWhere(string ID, string Ten)
{
return _context.ChiTieus.Include(ct => ct.CTChitieus)
.Where(c =>c.CTId.ToString().Contains(ID) && c.Ten.Contains(Ten))
.ToList();
}
public ChiTieu getByName(string name)
{
return _context.ChiTieus.Where(ct => ct.Ten == name).Include(ct => ct.CTChitieus).FirstOrDefault();
}
public void Update(ChiTieu chiTieu)
{
_context.ChiTieus.Update(chiTieu);
_context.SaveChanges();
}
}
}
<file_sep>using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Text;
using System.Windows.Forms;
using TourApp.Entity;
using TourApp.Seed;
namespace TourApp.Context
{
public class TourContext : DbContext
{
public TourContext() : base()
{
}
public DbSet<Tour> Tours { set; get; }
public DbSet<NhanVien> NhanViens { set; get; }
public DbSet<NV_VT> NV_VTs { set; get; }
public DbSet<CTTour> CTTours { set; get; }
public DbSet<Gia> Gias { set; get; }
public DbSet<DiaDiem> DiaDiems { set; get; }
public DbSet<HanhKhach> HanhKhachs { set; get; }
public DbSet<DoanKhach> DoanKhachs { set; get; }
public DbSet<CTDoan> CTDoans { set; get; }
public DbSet<CTChitieu> CTChiTieus { set; get; }
public DbSet<ChiTieu> ChiTieus { set; get; }
public DbSet<LoaiHinhDL> LoaiHinhDLs { set; get; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
optionsBuilder.UseSqlServer("Data Source=21AK22-COM\\SQLEXPRESS;Initial Catalog=TourDb2;User ID=sa;Password=<PASSWORD>");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<CTChitieu>().HasKey(c => new { c.CTId, c.DoanId });
modelBuilder.Entity<CTChitieu>()
.HasOne<ChiTieu>(c => c.ChiTieu)
.WithMany(c => c.CTChitieus)
.HasForeignKey(c => c.CTId);
modelBuilder.Entity<CTChitieu>()
.HasOne<DoanKhach>(c => c.DoanKhach)
.WithMany(c => c.CTChitieus)
.HasForeignKey(c => c.DoanId);
modelBuilder.Entity<CTDoan>().HasKey(c => new { c.DoanId, c.KhachId });
modelBuilder.Entity<CTDoan>()
.HasOne<DoanKhach>(c => c.DoanKhach)
.WithMany(c => c.CTDoans)
.HasForeignKey(c => c.DoanId);
modelBuilder.Entity<CTDoan>()
.HasOne<HanhKhach>(c => c.HanhKhach)
.WithMany(c => c.CTDoans)
.HasForeignKey(c => c.KhachId);
modelBuilder.Entity<CTTour>().HasKey(c => new { c.TourId, c.DDId });
modelBuilder.Entity<CTTour>()
.HasOne<Tour>(c => c.Tour)
.WithMany(c => c.CTTours)
.HasForeignKey(c => c.TourId);
modelBuilder.Entity<CTTour>()
.HasOne<DiaDiem>(c => c.DiaDiem)
.WithMany(c => c.CTTours)
.HasForeignKey(c => c.DDId);
modelBuilder.Entity<NV_VT>().HasKey(c => new { c.DoanId, c.NVId });
modelBuilder.Entity<NV_VT>()
.HasOne<DoanKhach>(c => c.DoanKhach)
.WithMany(c => c.NV_VTs)
.HasForeignKey(c => c.DoanId);
modelBuilder.Entity<NV_VT>()
.HasOne<NhanVien>(c => c.NhanVien)
.WithMany(c => c.NV_VTs)
.HasForeignKey(c => c.NVId);
//modelBuilder.Seed();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text;
namespace TourApp.UI
{
public abstract class Theme
{
public abstract Color MenuStripBG { get; }
public abstract Color MenuStripFG { get; }
public abstract Color PanelBG { get; }
public abstract Color PanelFG { get; }
public abstract Color TabControlBG { get; }
public abstract Color TabControlFG { get; }
public abstract Color TabPageBG { get; }
public abstract Color TabPageFG { get; }
public abstract Color DataGridviewBG { get; }
public abstract Color DataGridviewFG { get; }
public abstract Color DataGridviewGridColor { get; }
public abstract Color ButtonBG { get; }
public abstract Color ButtonFG { get; }
public abstract Color TextBoxBG { get; }
public abstract Color TextBoxFG { get; }
public abstract Color ComboBoxBG { get; }
public abstract Color ComboBoxFG { get; }
}
public class DarkTheme : Theme
{
public override Color PanelBG { get { return Color.DarkGray; } }
public override Color PanelFG { get { return Color.Green; } }
public override Color TabControlBG { get { return Color.Red; } }
public override Color TabControlFG { get { return Color.Purple; } }
public override Color TabPageBG { get { return Color.FromArgb(255, 30, 30, 30); } }
public override Color TabPageFG { get { return Color.White; } }
public override Color DataGridviewBG { get { return Color.FromArgb(255, 30, 30, 30); } }
public override Color DataGridviewFG { get { return Color.FromArgb(255, 37, 37, 38); } }
public override Color DataGridviewGridColor { get { return Color.Blue; } }
public override Color ButtonBG { get { return Color.White; } }
public override Color ButtonFG { get { return Color.White; } }
public override Color TextBoxBG { get { return Color.FromArgb(255, 37, 37, 38); } }
public override Color TextBoxFG { get { return Color.White; } }
public override Color MenuStripBG { get { return Color.DarkGray; } }
public override Color MenuStripFG { get { return Color.White; } }
public override Color ComboBoxBG { get { return Color.Black; } }
public override Color ComboBoxFG { get { return Color.White; } }
}
public class LightTheme : Theme
{
public override Color PanelBG { get { return Color.White; } }
public override Color PanelFG { get { return Color.Black; } }
public override Color TabControlBG { get { return Color.WhiteSmoke; } }
public override Color TabControlFG { get { return Color.Black; } }
public override Color TabPageBG { get { return Color.White; } }
public override Color TabPageFG { get { return Color.Black; } }
public override Color DataGridviewBG { get { return Color.White; } }
public override Color DataGridviewFG { get { return Color.Black; } }
public override Color DataGridviewGridColor { get { return Color.Gray; } }
public override Color ButtonBG { get { return Color.White; } }
public override Color ButtonFG { get { return Color.White; } }
public override Color TextBoxBG { get { return Color.White; } }
public override Color TextBoxFG { get { return Color.Black; } }
public override Color MenuStripBG { get { return Color.White; } }
public override Color MenuStripFG { get { return Color.Black; } }
public override Color ComboBoxBG { get { return Color.White; } }
public override Color ComboBoxFG { get { return Color.Black; } }
}
public class DefaultTheme : Theme
{
public override Color PanelBG { get { return Color.White; } }
public override Color PanelFG { get { return Color.Black; } }
public override Color TabControlBG { get { return Color.WhiteSmoke; } }
public override Color TabControlFG { get { return Color.Black; } }
public override Color TabPageBG { get { return Color.White; } }
public override Color TabPageFG { get { return Color.Black; } }
public override Color DataGridviewBG { get { return SystemColors.ControlDark; } }
public override Color DataGridviewFG { get { return Color.Black; } }
public override Color DataGridviewGridColor { get { return SystemColors.ControlDark; } }
public override Color ButtonBG { get { return Color.FromArgb(255, 240, 240, 240); } }
public override Color ButtonFG { get { return SystemColors.ControlText; } }
public override Color TextBoxBG { get { return Color.White; } }
public override Color TextBoxFG { get { return Color.Black; } }
public override Color MenuStripBG { get { return Color.White; } }
public override Color MenuStripFG { get { return Color.Black; } }
public override Color ComboBoxBG { get { return SystemColors.Window; } }
public override Color ComboBoxFG { get { return SystemColors.WindowText; } }
}
}
<file_sep>
using System;
using System.ComponentModel;
using System.Drawing;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using TourApp.Const;
using TourApp.Entity;
using TourApp.Repository.IRepository;
namespace TourApp
{
public partial class NhanVienAdd : Form
{
public int id = 0;
public INhanVienRepository _nhanvien;
public NhanVienAdd(INhanVienRepository nhanvien)
{
InitializeComponent();
_nhanvien = nhanvien;
}
public void setId(int id)
{
this.id = id;
}
public EditState editState { get; set; }
//TO FILL:validate
private Boolean validate()
{
//Nhap ID
if (txt_id.Text == "")
{
txt_id.ForeColor = Color.Red;
txt_id.Focus();
err_msg1.Text = ErrorMsg.err_blank;
err_msg1.Visible = true;
return false;
}
else
{
txt_id.ForeColor = Color.Black;
err_msg1.Visible = false;
}
//Ten
if (txt_name.Text == "")
{
txt_name.ForeColor = Color.Red;
txt_name.Focus();
err_msg2.Text = ErrorMsg.err_blank;
err_msg2.Visible = true;
return false;
}
else
{
txt_name.ForeColor = Color.Black;
err_msg2.Visible = false;
}
//SDT
if (txt_phone.Text == "")
{
txt_phone.ForeColor = Color.Red;
txt_phone.Focus();
err_msg4.Text = ErrorMsg.err_blank;
err_msg4.Visible = true;
return false;
}
else if (!Regex.IsMatch(txt_phone.Text, "^[0-9]{9,11}$"))
{
txt_phone.ForeColor = Color.Red;
txt_phone.Focus();
err_msg4.Text = ErrorMsg.err_phone;
err_msg4.Visible = true;
return false;
}
else
{
err_msg4.Visible = false;
txt_phone.ForeColor = Color.Black;
}
return true;
}
private void NhanVienAdd_Load(object sender, EventArgs e)
{
init();
}
//TO FILL:init
private void init()
{
switch (editState)
{
case EditState.View:
{
NhanVien nv = _nhanvien.getById(id);
txt_id.Text = nv.MaNV;
txt_phone.Text = nv.SDT.ToString();
txt_name.Text = nv.Ten;
title.Text = "CHI TIẾT NHÂN VIÊN";
txt_name.ReadOnly = true;
txt_id.ReadOnly = true;
txt_phone.ReadOnly = true;
btn.Enabled = false;
break;
}
case EditState.Create:
{
break;
}
case EditState.Edit:
{
NhanVien nv = _nhanvien.getById(id);
txt_id.Text = nv.MaNV;
txt_phone.Text = nv.SDT.ToString();
txt_name.Text = nv.Ten;
title.Text = "SỬA NHÂN VIÊN";
break;
}
}
}
//TO FILL:button click
private void btn_Click(object sender, EventArgs e)
{
if (!validate())
{
return;
}
if (id != 0)
{
NhanVien nv = _nhanvien.getById(id);
nv.MaNV = txt_id.Text;
nv.Ten = txt_name.Text;
nv.SDT = txt_phone.Text;
_nhanvien.Update(nv);
MessageBox.Show("Sửa thành công nhân viên có ID: " + nv.NVId, "Nhân viên");
txt_id.Focus();
}
else
{
NhanVien nv = new NhanVien();
nv.MaNV = txt_id.Text;
nv.Ten = txt_name.Text;
nv.SDT = txt_phone.Text;
_nhanvien.Add(nv);
MessageBox.Show("Đã thêm thành công", "<NAME>");
txt_id.Text = "";
txt_phone.Text = "";
txt_name.Text = "";
txt_id.Focus();
}
}
private void Control_KeyUp(object sender, PreviewKeyDownEventArgs e)
{
if ((e.KeyCode == Keys.Enter) || (e.KeyCode == Keys.Return))
{
this.SelectNextControl((Control)sender, true, true, true, true);
}
}
//text validating
private void txt_Validating(object sender, CancelEventArgs e)
{
if (this.ActiveControl.Equals(sender))
return;
string name = ((TextBox)sender).Name;
switch (name)
{
case "txt_id":
if (txt_id.Text == "")
{
txt_id.ForeColor = Color.Red;
txt_id.Focus();
err_msg1.Text = ErrorMsg.err_blank;
err_msg1.Visible = true;
e.Cancel = true;
}
else
{
txt_id.ForeColor = Color.Black;
err_msg1.Visible = false;
}
break;
case "txt_name":
if (txt_name.Text == "")
{
txt_name.ForeColor = Color.Red;
txt_name.Focus();
err_msg2.Text = ErrorMsg.err_blank;
err_msg2.Visible = true;
e.Cancel = true;
}
else
{
txt_name.ForeColor = Color.Black;
err_msg2.Visible = false;
}
break;
case "txt_phone":
if (txt_phone.Text == "")
{
txt_phone.ForeColor = Color.Red;
txt_phone.Focus();
err_msg4.Text = ErrorMsg.err_blank;
err_msg4.Visible = true;
e.Cancel = true;
}
else if (!Regex.IsMatch(txt_phone.Text, "^[0-9]{9,11}$"))
{
txt_phone.ForeColor = Color.Red;
txt_phone.Focus();
err_msg4.Text = ErrorMsg.err_phone;
err_msg4.Visible = true;
e.Cancel = true;
}
else
{
err_msg4.Visible = false;
txt_phone.ForeColor = Color.Black;
}
break;
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text;
namespace TourApp.Entity
{
public class HanhKhach
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public int KhachId { set; get; }
public string MaKhach { set; get; }
public string Ten { set; get; }
public string SDT { set; get; }
public string Email { set; get; }
public string CMND { set; get; }
public string DiaChi { set; get; }
public string GioiTinh { set; get; }
public string Passport { set; get; }
public int isDeleted { set; get; }
public ICollection<CTDoan> CTDoans { set; get; }
}
}
<file_sep>using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TourApp.Context;
using TourApp.Entity;
using TourApp.Repository.IRepository;
namespace TourApp.Repository
{
public class LoaiHinhDuLichRepository : ILoaiHinhDuLichRepository
{
private TourContext _context;
public LoaiHinhDuLichRepository(TourContext context)
{
_context = context;
}
public void Add(LoaiHinhDL lhdl)
{
_context.LoaiHinhDLs.Add(lhdl);
_context.SaveChanges();
}
public void Delete(LoaiHinhDL lhdl)
{
_context.LoaiHinhDLs.Remove(lhdl);
_context.SaveChanges();
}
public IEnumerable<LoaiHinhDL> getAll()
{
return _context.LoaiHinhDLs.ToList();
}
public LoaiHinhDL getById(int lhdlId)
{
return _context.LoaiHinhDLs.Find(lhdlId);
}
public IEnumerable<LoaiHinhDL> getWhere(string ID,string Ten, string Mota)
{
return _context.LoaiHinhDLs.Where(i => i.LHDLId.ToString().Contains(ID)
&& i.Ten.Contains(Ten)
&& i.moTa.Contains(Mota)
).ToList();
}
public void Update(LoaiHinhDL lhdl)
{
_context.LoaiHinhDLs.Update(lhdl);
_context.SaveChanges();
}
}
}
<file_sep>using SQLitePCL;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using TourApp.Const;
using TourApp.Entity;
using TourApp.Repository.IRepository;
namespace TourApp
{
public partial class HanhKhach_Form:Form
{
public int id = 0;
public IHanhKhachRepository _hanhKhach;
public HanhKhach_Form(IHanhKhachRepository hanhKhach)
{
InitializeComponent();
_hanhKhach = hanhKhach;
}
public void setId(int id)
{
this.id = id;
}
public EditState editState { get; set; }
private Boolean validate()
{
if(txt_id.Text == "")
{
txt_id.ForeColor = Color.Red;
txt_id.Focus();
err_msg1.Text = ErrorMsg.err_blank;
err_msg1.Visible = true;
return false;
}
else
{
txt_id.ForeColor = Color.Black;
err_msg1.Visible = false;
}
if (txt_name.Text == "")
{
txt_name.ForeColor = Color.Red;
txt_name.Focus();
err_msg2.Text = ErrorMsg.err_blank;
err_msg2.Visible = true;
return false;
}
else
{
txt_name.ForeColor = Color.Black;
err_msg2.Visible = false;
}
if (txt_email.Text !="" && !Regex.IsMatch(txt_email.Text, "^\\w+@+[a-z]+\\.+[a-z]+$"))
{
txt_email.ForeColor = Color.Red;
txt_email.Focus();
err_msg3.Text = ErrorMsg.err_email;
err_msg3.Visible = true;
return false;
}
else
{
err_msg3.Visible = false;
txt_email.ForeColor = Color.Black;
}
if (txt_phone.Text == "")
{
txt_phone.ForeColor = Color.Red;
txt_phone.Focus();
err_msg4.Text = ErrorMsg.err_blank;
err_msg4.Visible = true;
return false;
}
else if (!Regex.IsMatch(txt_phone.Text, "^[0-9]{9,11}$"))
{
txt_phone.ForeColor = Color.Red;
txt_phone.Focus();
err_msg4.Text = ErrorMsg.err_phone;
err_msg4.Visible = true;
return false;
}
else
{
err_msg4.Visible = false;
txt_phone.ForeColor = Color.Black;
}
if (txt_cmnd.Text != "" && !Regex.IsMatch(txt_cmnd.Text, "^[0-9]{1,}$"))
{
txt_cmnd.ForeColor = Color.Red;
txt_cmnd.Focus();
err_msg5.Text = ErrorMsg.err_number;
err_msg5.Visible = true;
return false;
}
else
{
err_msg5.Visible = false;
txt_cmnd.ForeColor = Color.Black;
}
if (txt_diachi.Text == "" )
{
txt_diachi.ForeColor = Color.Red;
txt_diachi.Focus();
err_msg6.Text = ErrorMsg.err_blank;
err_msg6.Visible = true;
return false;
}
else
{
err_msg6.Visible = false;
txt_diachi.ForeColor = Color.Black;
}
return true;
}
private void HanhKhachAdd_Load(object sender, EventArgs e)
{
init();
}
private void init()
{
switch (editState)
{
case EditState.View:
{
HanhKhach hk = _hanhKhach.getById(id);
txt_id.Text = hk.MaKhach;
txt_email.Text = hk.Email;
txt_phone.Text = hk.SDT.ToString();
txt_name.Text = hk.Ten;
txt_cmnd.Text = hk.CMND;
txt_diachi.Text = hk.DiaChi;
if (hk.GioiTinh == "Nam")
{
Radio_GT.Checked = true;
}
else Radio_GT1.Checked = true;
txt_passport.Text = hk.Passport;
title.Text = "CHI TIẾT HÀNH KHÁCH";
txt_name.ReadOnly = true;
txt_email.ReadOnly = true;
txt_id.ReadOnly = true;
txt_phone.ReadOnly = true;
txt_diachi.ReadOnly = true;
txt_cmnd.ReadOnly = true;
txt_passport.ReadOnly = true;
Radio_GT.Enabled = false;
Radio_GT1.Enabled = false;
btn.Enabled = false;
break;
}
case EditState.Create:
{
break;
}
case EditState.Edit:
{
HanhKhach hk = _hanhKhach.getById(id);
txt_id.Text = hk.MaKhach;
txt_email.Text = hk.Email;
txt_phone.Text = hk.SDT.ToString();
txt_name.Text = hk.Ten;
txt_cmnd.Text = hk.CMND;
txt_diachi.Text = hk.DiaChi;
if (hk.GioiTinh == "Nam")
{
Radio_GT.Checked = true;
}
else Radio_GT1.Checked = true;
txt_passport.Text = hk.Passport;
title.Text = "SỬA HÀNH KHÁCH";
break;
}
}
}
private void btn_Click(object sender, EventArgs e)
{
if(!validate())
{
return;
}
if(id != 0)
{
HanhKhach hk = _hanhKhach.getById(id);
hk.MaKhach = txt_id.Text;
hk.Ten = txt_name.Text;
hk.Email = txt_email.Text;
hk.SDT = txt_phone.Text;
hk.CMND = txt_cmnd.Text;
hk.DiaChi = txt_diachi.Text;
hk.Passport = txt_passport.Text;
if (Radio_GT.Checked == true)
{
hk.GioiTinh = Radio_GT.Text;
}
else hk.GioiTinh = Radio_GT1.Text;
_hanhKhach.Update(hk);
MessageBox.Show("Sửa thành công Hành Khách có ID: " + hk.KhachId, "Hành Khách");
txt_id.Focus();
}
else
{
HanhKhach hk = new HanhKhach();
hk.MaKhach = txt_id.Text;
hk.Ten = txt_name.Text;
hk.Email = txt_email.Text;
hk.SDT = txt_phone.Text;
hk.CMND = txt_cmnd.Text;
hk.DiaChi = txt_diachi.Text;
hk.Passport = txt_passport.Text;
if (Radio_GT.Checked == true)
{
hk.GioiTinh = Radio_GT.Text;
}
else hk.GioiTinh = Radio_GT1.Text;
_hanhKhach.Add(hk);
MessageBox.Show("Đã thêm thành công", "Hành Khách");
txt_id.Text = "";
txt_email.Text = "";
txt_phone.Text = "";
txt_name.Text = "";
txt_cmnd.Text = "";
txt_diachi.Text = "";
txt_passport.Text = "";
Radio_GT.Checked = true;
txt_id.Focus();
}
}
private void Control_KeyUp(object sender, PreviewKeyDownEventArgs e)
{
if ((e.KeyCode == Keys.Enter) || (e.KeyCode == Keys.Return))
{
this.SelectNextControl((Control)sender, true, true, true, true);
}
}
private void txt_Validating(object sender, CancelEventArgs e)
{
if (this.ActiveControl.Equals(sender))
return;
string name = ((TextBox)sender).Name;
switch (name)
{
case "txt_id":
if (txt_id.Text == "")
{
txt_id.ForeColor = Color.Red;
txt_id.Focus();
err_msg1.Text = ErrorMsg.err_blank;
err_msg1.Visible = true;
e.Cancel = true;
}
else
{
txt_id.ForeColor = Color.Black;
err_msg1.Visible = false;
}
break;
case "txt_name":
if (txt_name.Text == "")
{
txt_name.ForeColor = Color.Red;
txt_name.Focus();
err_msg2.Text = ErrorMsg.err_blank;
err_msg2.Visible = true;
e.Cancel = true;
}
else
{
txt_name.ForeColor = Color.Black;
err_msg2.Visible = false;
}
break;
case "txt_email":
if (txt_email.Text != "" && !Regex.IsMatch(txt_email.Text, "^\\w+@+[a-z]+\\.+[a-z]+$"))
{
txt_email.ForeColor = Color.Red;
txt_email.Focus();
err_msg3.Text = ErrorMsg.err_email;
err_msg3.Visible = true;
e.Cancel = true;
}
else
{
err_msg3.Visible = false;
txt_email.ForeColor = Color.Black;
}
break;
case "txt_phone":
if (txt_phone.Text == "")
{
txt_phone.ForeColor = Color.Red;
txt_phone.Focus();
err_msg4.Text = ErrorMsg.err_blank;
err_msg4.Visible = true;
e.Cancel = true;
}
else if (!Regex.IsMatch(txt_phone.Text, "^[0-9]{9,11}$"))
{
txt_phone.ForeColor = Color.Red;
txt_phone.Focus();
err_msg4.Text = ErrorMsg.err_phone ;
err_msg4.Visible = true;
e.Cancel = true;
}
else
{
err_msg4.Visible = false;
txt_phone.ForeColor = Color.Black;
}
break;
case "txt_cmnd":
if (txt_cmnd.Text != "" && !Regex.IsMatch(txt_cmnd.Text, "^[0-9]{1,}$"))
{
txt_cmnd.ForeColor = Color.Red;
txt_cmnd.Focus();
err_msg5.Text = ErrorMsg.err_number;
err_msg5.Visible = true;
e.Cancel = true;
}
else
{
err_msg5.Visible = false;
txt_cmnd.ForeColor = Color.Black;
}
break;
case "txt_diachi":
if (txt_diachi.Text == "")
{
txt_diachi.ForeColor = Color.Red;
txt_diachi.Focus();
err_msg6.Text = ErrorMsg.err_blank;
err_msg6.Visible = true;
e.Cancel = true;
}
else
{
err_msg6.Visible = false;
txt_diachi.ForeColor = Color.Black;
}
break;
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text;
namespace TourApp.Entity
{
public class DiaDiem
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public int DDId { set; get; }
[Required]
public String TenDD { set; get; }
public int isDeleted { set; get; }
public ICollection<CTTour> CTTours { set; get; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text;
namespace TourApp.Entity
{
public class Tour
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public int TourId { set; get; }
[Required]
public String MaTour { set; get; }
[Required]
public String Ten { set; get; }
public ICollection<CTTour> CTTours { set; get; }
public ICollection<Gia> Gias { set; get; }
public ICollection<DoanKhach> DoanKhachs { set; get; }
[Required]
public int LHDLId { set; get; }
public LoaiHinhDL LHDL { set; get; }
public int isDeleted { set; get; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace TourApp.Const
{
public enum EditState
{
Create,
Edit,
View
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using TourApp.Entity;
namespace TourApp.Repository.IRepository
{
public interface IHanhKhachRepository : ICommonRepository<HanhKhach>
{
IEnumerable<HanhKhach> getWhere(string ID, string MaHK, string Ten, string SDT, string Email, string CMND, string Diachi, string Gioitinh, string Passport, int isDeleted);
IEnumerable<HanhKhach> getAllDelete();
HanhKhach getById(int id, string maHK = "");
}
}
<file_sep>using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TourApp.Context;
using TourApp.Entity;
using TourApp.Repository.IRepository;
namespace TourApp.Repository
{
public class CTTourRepository : ICTTourRepository
{
private TourContext _context;
public CTTourRepository(TourContext context)
{
_context = context;
}
public void Add(CTTour entity)
{
_context.CTTours.Add(entity);
_context.SaveChanges();
}
public void Delete(CTTour entity)
{
_context.CTTours.Remove(entity);
_context.SaveChanges();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using TourApp.Const;
using TourApp.Entity;
using TourApp.Repository.IRepository;
namespace TourApp
{
public partial class ThemChiTieu : Form
{
private readonly IChiTieuRepository _chiTieuRepository;
public int _id = -1;
public EditState editState {get; set;}
public ThemChiTieu(IChiTieuRepository chiTieuRepository)
{
_chiTieuRepository = chiTieuRepository;
InitializeComponent();
}
public void setId(int id)
{
_id = id;
}
private bool check()
{
bool error = false;
if (CTname.Text == "")
{
CTnameer.Text = ErrorMsg.err_blank;
CTnameer.Visible = true;
CTname.Focus();
error = true;
}
else
{
CTnameer.Visible = false;
}
return error;
}
private void Submitbt_Click(object sender, EventArgs e)
{
}
private void init ()
{
switch(editState)
{
case EditState.View:
{
ChiTieu ct = _chiTieuRepository.getById(_id);
CTname.Text = ct.Ten;
CTname.Enabled = false;
Submitbt.Enabled = false;
break;
}
case EditState.Edit:
{
ChiTieu ct = _chiTieuRepository.getById(_id);
CTname.Text = ct.Ten;
break;
}
case EditState.Create:
{
break;
}
}
}
protected override void OnLoad(EventArgs e)
{
init();
}
private void Submitbt_Click_1(object sender, EventArgs e)
{
if (check())
{
return;
}
if (_id != -1)
{
ChiTieu ct = _chiTieuRepository.getById(_id);
ct.Ten = CTname.Text;
_chiTieuRepository.Update(ct);
MessageBox.Show("Sửa thành công Chi tiêu");
Program.Form.TabRefresh(ListTab.Chitieu);
}
else
{
ChiTieu ct = new ChiTieu();
ct.Ten = CTname.Text;
_chiTieuRepository.Add(ct);
MessageBox.Show("Thêm thành công Chi tiêu");
Program.Form.TabRefresh(ListTab.Chitieu);
this.Close();
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
using TourApp.Entity;
namespace TourApp.Repository.IRepository
{
public interface ILoaiHinhDuLichRepository : ICommonRepository<LoaiHinhDL>
{
IEnumerable<LoaiHinhDL> getWhere(string ID, string Ten, string Mota);
LoaiHinhDL getById(int lhdlId);
}
}
<file_sep>using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.DirectoryServices;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using TourApp.Context;
using TourApp.Repository;
using TourApp.Repository.IRepository;
namespace TourApp
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
public static List Form;
public static FormTest Form1;
[STAThread]
static void Main()
{
Application.SetHighDpiMode(HighDpiMode.SystemAware);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
var services = new ServiceCollection();
ConfigureServices(services);
using(ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Form = serviceProvider.GetRequiredService<List>();
Form1 = serviceProvider.GetRequiredService<FormTest>();
Application.Run(Form);
}
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddDbContext<TourContext>();
services.AddTransient<NhanVienAdd>();
services.AddTransient<FormTest>();
services.AddTransient<ThongTinTour>();
services.AddTransient<ThemTour>();
services.AddTransient<SuaTour>();
services.AddTransient<List>();
services.AddTransient<ThemGia>();
services.AddTransient<ThemChiTieu>();
services.AddTransient<ThemDiadiem>();
services.AddTransient<ThemLHDuLich>();
services.AddTransient<DanhSachDoanKhach>();
services.AddTransient<HanhKhach_Form>();
services.AddTransient<DoanKhach_Form>();
services.AddTransient<SearchForm>();
services.AddTransient<NhanVienAdd>();
services.AddTransient<TKChiPhi_Form>();
services.AddTransient<TKDoanhThu_Form>();
services.AddTransient<TKTinhHinhHoatDong>();
services.AddTransient<TK_NhanVienTour>();
services.AddScoped<IChiTieuRepository, ChiTieuRepository>();
services.AddScoped<ITourRepository, TourRepository>();
services.AddScoped<IDiaDiemRepository, DiaDiemRepository>();
services.AddScoped<IGiaRepository, GiaRepository>();
services.AddScoped<ICTTourRepository, CTTourRepository>();
services.AddScoped<IHanhKhachRepository, HanhKhachRepository>();
services.AddScoped<IDoanKhachRepository, DoanKhachRepository>();
services.AddScoped<INhanVienRepository, NhanVienRepository>();
services.AddScoped<ILoaiHinhDuLichRepository, LoaiHinhDuLichRepository>();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using TourApp.Const;
using TourApp.Entity;
using TourApp.Repository.IRepository;
namespace TourApp
{
public partial class ThemTour : Form
{
private readonly ITourRepository _tourRepository;
private readonly IDiaDiemRepository _diadiemRepository;
private readonly ICTTourRepository _cTTourRepository;
private readonly IGiaRepository _giaRepository;
private readonly ILoaiHinhDuLichRepository _lhdlRepo;
public ThemTour(ITourRepository tourRepository,IDiaDiemRepository diaDiemRepository,ICTTourRepository cTTourRepository,IGiaRepository giaRepository, ILoaiHinhDuLichRepository lhdlRepo)
{
_tourRepository = tourRepository;
_diadiemRepository = diaDiemRepository;
_cTTourRepository = cTTourRepository;
_giaRepository = giaRepository;
_lhdlRepo = lhdlRepo;
InitializeComponent();
}
private void showThongtin()
{
IEnumerable<DiaDiem> listdd = _diadiemRepository.getAll();
/*Dia Diem Tour*/
foreach (var DD in listdd)
{
ListViewItem diaDiem = new ListViewItem(new[] { DD.DDId.ToString(), DD.TenDD });
diadiem.Items.Add(diaDiem);
}
/* Loại hình */
var lhdl_list = _lhdlRepo.getAll();
loaihinhcbb.DataSource = lhdl_list;
loaihinhcbb.DisplayMember = "Ten";
loaihinhcbb.ValueMember = "LHDLId";
}
private bool check()
{
if (matourtb.Text == null)
return false;
if (tentourtb.Text == null)
return false;
if (diadiem.CheckedItems == null)
return false;
if (mucgia.Value <= 0)
return false;
if (tungay.Value > denngay.Value)
return false;
return true;
}
private void button1_Click(object sender, EventArgs e)
{
if (!check())
{
MessageBox.Show("Thông tin thiếu hoặc không hợp lệ !");
}
else
{
Tour newtour = new Tour();
newtour.CTTours = new List<CTTour>();
newtour.Gias = new List<Gia>();
Gia newgia = new Gia();
newtour.MaTour = matourtb.Text;
newtour.Ten = tentourtb.Text;
LoaiHinhDL item = new LoaiHinhDL();
item = (LoaiHinhDL)loaihinhcbb.SelectedItem;
newtour.LHDL = item;
foreach (ListViewItem dd in diadiem.CheckedItems)
{
CTTour newcttour = new CTTour();
newcttour.DDId = Convert.ToInt32(dd.SubItems[0].Text);
newcttour.TourId = newtour.TourId;
//_cTTourRepository.Add(newcttour);
newtour.CTTours.Add(newcttour);
}
newgia.GiaTri = (int)mucgia.Value;
newgia.TGBD = tungay.Value;
newgia.TGKT = denngay.Value;
newgia.TourId = newtour.TourId;
newtour.Gias.Add(newgia);
_tourRepository.Add(newtour);
// _giaRepository.Add(newgia);
MessageBox.Show("Thêm thành công!");
Program.Form.TabRefresh(ListTab.Tour);
}
}
protected override void OnLoad(EventArgs e)
{
showThongtin();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using TourApp.Entity;
using TourApp.Repository.IRepository;
using TourApp.Const;
using Microsoft.Extensions.DependencyInjection;
using System.Runtime.Serialization.Formatters;
using System.Linq;
namespace TourApp
{
public partial class DoanKhach_Form : Form
{
public int id = 0;
private readonly ITourRepository _tourRepository;
private readonly IDoanKhachRepository _doanRepo;
private readonly IServiceProvider _service;
private readonly INhanVienRepository _nvRepo;
private readonly IHanhKhachRepository _hkRepo;
private readonly IChiTieuRepository _ctRepo;
public EditState formType;
public DoanKhach_Form(ITourRepository tourRepository, IServiceProvider service, IDoanKhachRepository doanRepo,
INhanVienRepository nvRepo, IHanhKhachRepository hkRepo, IChiTieuRepository ctRepo)
{
InitializeComponent();
_tourRepository = tourRepository;
_service = service;
_doanRepo = doanRepo;
_nvRepo = nvRepo;
_hkRepo = hkRepo;
_ctRepo = ctRepo;
}
public Boolean validate()
{
if(mad.Text == "")
{
mad.ForeColor = Color.Red;
mad.Focus();
errormsg0.Text = ErrorMsg.err_blank;
errormsg0.Visible = true;
return false;
}
else
{
errormsg0.Visible = false;
mad.ForeColor = Color.Black;
}
if (tend.Text == "")
{
tend.ForeColor = Color.Red;
tend.Focus();
errormsg0.Text = ErrorMsg.err_blank;
errormsg0.Visible = true;
return false;
}
else
{
errormsg0.Visible = false;
tend.ForeColor = Color.Black;
}
if (DateTime.Compare(datestart.Value, dateend.Value) > 0)
{
errormsg0.Text = ErrorMsg.err_minMaxDate;
errormsg0.Visible = true;
return false;
}
else
{
errormsg0.Visible = false;
}
if (data_hk.Rows.Count <1)
{
errormsg1.Visible = true;
return false;
}
else
{
errormsg1.Visible = false;
}
if (data_nv.Rows.Count < 1)
{
errormsg2.Visible = true;
return false;
}
else
{
errormsg2.Visible = false;
}
if (data_cp.Rows.Count < 1)
{
errormsg3.Visible = true;
return false;
}
else
{
errormsg3.Visible = false;
}
return true;
}
private void init()
{
if (formType != EditState.View)
{
IEnumerable<Tour> Tours = _tourRepository.getAll();
foreach (Tour tourm in Tours)
{
tourd.Items.Add(tourm.Ten);
}
}
datestart.Value = DateTime.Now.Date;
dateend.Value = DateTime.Now.Date;
switch (formType)
{
case EditState.Create:
tourd.SelectedIndex = 0;
break;
case EditState.Edit:
//Init Data to DoanForm
DoanKhach dk_init = _doanRepo.getById(id);
mad.Text = dk_init.MaDoan;
tend.Text = dk_init.TenDoan;
tourd.SelectedItem = dk_init.Tour.Ten;
statusd.Text = dk_init.Chitiet;
datestart.Value = dk_init.DateStart;
dateend.Value = dk_init.DateEnd;
if (dk_init.DateStart <= DateTime.Now.Date)
{
mad.ReadOnly = true;
tend.ReadOnly = true;
statusd.ReadOnly = true;
datestart.Enabled = false;
dateend.Enabled = false;
Save.Enabled = false;
cp_btn.Enabled = false;
nv_btn.Enabled = false;
hk_btn.Enabled = false;
tourd.Enabled = false;
}
//HanhKhach
foreach (var hk in dk_init.CTDoans)
{
data_hk.Rows.Add(hk.HanhKhach.MaKhach, hk.HanhKhach.Ten, hk.HanhKhach.SDT);
}
//NhanVien
foreach (var nv in dk_init.NV_VTs)
{
data_nv.Rows.Add(nv.NhanVien.MaNV, nv.NhanVien.Ten,nv.ViTri);
}
//ChiTieu
foreach (var ct in dk_init.CTChitieus)
{
data_cp.Rows.Add(ct.ChiTieu.Ten, ct.TienCT);
}
break;
case EditState.View:
DoanKhach dk_init1 = _doanRepo.getById(id);
mad.Text = dk_init1.MaDoan;
tend.Text = dk_init1.TenDoan;
tourd.Items.Add(dk_init1.Tour.Ten);
tourd.SelectedIndex = 0;
statusd.Text = dk_init1.Chitiet;
datestart.Value = dk_init1.DateStart;
dateend.Value = dk_init1.DateEnd;
//HanhKhach
foreach (var hk in dk_init1.CTDoans)
{
data_hk.Rows.Add(hk.HanhKhach.MaKhach, hk.HanhKhach.Ten, hk.HanhKhach.SDT);
}
//NhanVien
foreach (var nv in dk_init1.NV_VTs)
{
data_nv.Rows.Add(nv.NhanVien.MaNV, nv.NhanVien.Ten, nv.ViTri);
}
//ChiTieu
foreach (var ct in dk_init1.CTChitieus)
{
data_cp.Rows.Add(ct.ChiTieu.Ten, ct.TienCT);
}
mad.ReadOnly = true;
tend.ReadOnly = true;
statusd.ReadOnly = true;
datestart.Enabled = false;
dateend.Enabled = false;
Save.Enabled = false;
break;
}
}
private void label3_Click(object sender, EventArgs e)
{
}
private void button4_Click(object sender, EventArgs e)
{
if (formType == EditState.View)
{
return;
}
if (!validate())
{
return;
}
save();
MessageBox.Show("Lưu thành công", "Thông báo");
}
private void DoanKhach_Form_Load(object sender, EventArgs e)
{
init();
}
private void select(string btn_click)
{
var name = btn_click;
SearchForm s_form;
switch (name)
{
case "hk_btn":
s_form = _service.GetRequiredService<SearchForm>();
s_form.setForm(FormName.HKFORMNAME);
s_form.ShowDialog();
var hkList = s_form.listHKRT;
data_hk.Rows.Clear();
if(hkList != null )
{
foreach (var hk in hkList)
{
data_hk.Rows.Add(hk.MaKhach, hk.Ten, hk.SDT);
}
}
break;
case "nv_btn":
s_form = _service.GetRequiredService<SearchForm>();
s_form.setForm(FormName.NVFORMNAME);
s_form.ShowDialog();
var nvList = s_form.listNVRT;
var flg1 = false;
if ( nvList != null && nvList.Count>0 )
{
foreach (DataGridViewRow row in data_nv.Rows)
{
foreach (DataGridViewCell cell in row.Cells)
{
if (cell.GetType() == typeof(DataGridViewButtonCell))
{
continue;
}
string value = cell.Value.ToString();
if (value == nvList[0])
{
flg1 = true;
break;
}
if (flg1) break;
}
}
if (!flg1)
{
data_nv.Rows.Add(nvList[0], nvList[1], nvList[2]);
}
}
break;
case "ct_btn":
s_form = _service.GetRequiredService<SearchForm>();
s_form.setForm(FormName.CTFORMNAME);
s_form.ShowDialog();
var ctList = s_form.listCTRT;
var flg = false;
if (ctList != null && ctList.Count>0)
{
foreach (DataGridViewRow row in data_cp.Rows)
{
foreach (DataGridViewCell cell in row.Cells)
{
if(cell.GetType() == typeof(DataGridViewButtonCell))
{
continue;
}
string value = cell.Value.ToString();
if (value == ctList[0])
{
flg = true;
break;
}
if (flg) break;
}
}
if (!flg)
{
data_cp.Rows.Add(ctList[0], ctList[1]);
}
}
break;
}
}
private void cp_btn_Click(object sender, EventArgs e)
{
if(formType == EditState.View)
{
return;
}
select("ct_btn");
}
private void hk_btn_Click(object sender, EventArgs e)
{
if (formType == EditState.View)
{
return;
}
select("hk_btn");
}
private void nv_btn_Click(object sender, EventArgs e)
{
if (formType == EditState.View)
{
return;
}
select("nv_btn");
}
private void save()
{
//init Create Type
DoanKhach doan = new DoanKhach();
Tour tour1 = _tourRepository.getByName(tourd.SelectedItem.ToString());
//init Edit Type
if (formType == EditState.Edit)
{
doan = _doanRepo.getById(id);
if(tour1.TourId != doan.TourId)
{
doan.Gia = tour1.Gias.LastOrDefault();
}
}
//Add value to each of column doan
doan.MaDoan = mad.Text;
doan.TenDoan = tend.Text;
doan.Tour = tour1;
doan.Chitiet = statusd.Text;
doan.DateStart = datestart.Value.Date;
doan.DateEnd = dateend.Value.Date;
//NhanVien
List<NV_VT> doan_nvs = new List<NV_VT>();
foreach (DataGridViewRow row in data_nv.Rows)
{
NV_VT doan_nv = new NV_VT();
NhanVien nhanvien = _nvRepo.getById(0,row.Cells[0].Value.ToString());
doan_nv.NhanVien = nhanvien;
doan_nv.DoanKhach = doan;
doan_nv.ViTri = row.Cells[2].Value.ToString();
doan_nvs.Add(doan_nv);
}
doan.NV_VTs = doan_nvs;
//HanhKhach
List<CTDoan> cTDoans = new List<CTDoan>();
foreach (DataGridViewRow row in data_hk.Rows)
{
CTDoan cTDoan = new CTDoan();
HanhKhach hk = _hkRepo.getById(0, row.Cells[0].Value.ToString());
cTDoan.HanhKhach = hk;
cTDoan.DoanKhach = doan;
cTDoans.Add(cTDoan);
}
doan.CTDoans = cTDoans;
//ChiTieu
List<CTChitieu> cTChiTieus = new List<CTChitieu>();
foreach (DataGridViewRow row in data_cp.Rows)
{
CTChitieu cTChiTieu = new CTChitieu();
ChiTieu ct = _ctRepo.getByName(row.Cells[0].Value.ToString());
cTChiTieu.ChiTieu = ct;
cTChiTieu.TienCT = row.Cells[1].Value.ToString();
cTChiTieu.DoanKhach = doan;
cTChiTieus.Add(cTChiTieu);
}
doan.CTChitieus = cTChiTieus;
if (formType == EditState.Edit)
{
_doanRepo.Update(doan);
}
else
{
doan.Gia = doan.Tour.Gias.LastOrDefault();
doan.DateCreated = DateTime.Now;
_doanRepo.Add(doan);
}
}
private void data_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (formType == EditState.View)
{
return;
}
DataGridView datagrid = (DataGridView)sender;
if(datagrid.Name == "data_hk" && e.ColumnIndex == data_hk.Columns["DeleteHK"].Index && e.RowIndex >= 0)
{
data_hk.Rows.RemoveAt(e.RowIndex);
return;
}
if (datagrid.Name == "data_cp" && e.ColumnIndex == data_cp.Columns["DeleteCP"].Index && e.RowIndex >= 0)
{
data_cp.Rows.RemoveAt(e.RowIndex);
return;
}
if (datagrid.Name == "data_nv" && e.ColumnIndex == data_nv.Columns["DeleteNV"].Index && e.RowIndex >= 0)
{
data_nv.Rows.RemoveAt(e.RowIndex);
return;
}
}
}
}
<file_sep>using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using TourApp.Entity;
namespace TourApp.Seed
{
public static class Seeder
{
public static void Seed(this ModelBuilder modelBuilder)
{
modelBuilder.Entity<DiaDiem>().HasData(
new DiaDiem
{
DDId = 1,
TenDD = "Đà Nẵng",
},
new DiaDiem
{
DDId = 2,
TenDD = "TP. Hồ Chí Minh",
}
);
modelBuilder.Entity<LoaiHinhDL>().HasData(
new LoaiHinhDL
{
LHDLId = 1,
Ten = "Loại Hình 1",
moTa = "ABCXYZ",
}
);
modelBuilder.Entity<Tour>().HasData(
new Tour
{
TourId = 1,
MaTour = "T100001",
Ten = "Tour1",
LHDLId = 1,
}
);
modelBuilder.Entity<Gia>().HasData(
new Gia
{
GiaId = 1,
GiaTri = 100000,
TourId = 1,
TGBD = new DateTime()
}
);
modelBuilder.Entity<CTTour>().HasData(
new CTTour
{
TourId = 1,
DDId = 1,
},
new CTTour
{
TourId = 1,
DDId = 2,
}
);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using TourApp.Entity;
namespace TourApp.Repository.IRepository
{
public interface ICTTourRepository
{
void Add(CTTour entity);
void Delete(CTTour entity);
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using TourApp.Entity;
namespace TourApp.Repository.IRepository
{
public interface ITourRepository : ICommonRepository<Tour>
{
IEnumerable<Tour> getWhere(string Ten, string LHDL, string ID, string MaTour, DateTime fromDate, DateTime toDate, int fromPrice, int toPrice, int isDeleted=0);
Tour getByName(string Ten, int isDeleted = 0);
IEnumerable<Tour> getAllDelete();
Tour getById(int TourId, String MaTour = "");
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace TourApp.Const
{
public class FormName
{
public const string HKFORMNAME = "HanhKhach_Form";
public const string NVFORMNAME = "NhanVien_Form";
public const string CTFORMNAME = "ChiTieu_Form";
}
}
<file_sep>using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using TourApp.Entity;
using TourApp.Repository.IRepository;
namespace TourApp
{
public partial class ThongTinTour : Form
{
private readonly ITourRepository _tourRepository;
private readonly IServiceProvider _serviceProvider;
private Tour Tour;
private int _id;
public ThongTinTour(ITourRepository tourRepository,IServiceProvider serviceProvider)
{
_tourRepository = tourRepository;
_serviceProvider = serviceProvider;
InitializeComponent();
}
public void getId(int id)
{
_id = id;
}
/*Hiển thị thông tin khi vào form thông tin tour*/
private void showThongtin()
{
Tour = _tourRepository.getById(_id, "");
/*Thong tin Tour*/
mtour_txt.Text = Tour.MaTour;
tentour_txt.Text = Tour.Ten;
loaihinhtour_txt.Text = Tour.LHDL.Ten;
/*Dia Diem Tour*/
foreach(var DD in Tour.CTTours)
{
ListViewItem diaDiem = new ListViewItem(new[] { DD.DiaDiem.DDId.ToString(), DD.DiaDiem.TenDD });
listDD.Items.Add(diaDiem);
}
/*Gia Tour*/
var info = System.Globalization.CultureInfo.GetCultureInfo("vi-VN");
foreach (var Gia in Tour.Gias)
{
var giaTien = String.Format(info, "{0:n}", Gia.GiaTri.ToString());
ListViewItem gia = new ListViewItem(new[] { giaTien, Gia.TGBD.ToString("dd/MM/yyyy HH:mm:ss"), Gia.TGKT.ToString("dd/MM/yyyy HH:mm:ss") });
listGia.Items.Insert(0, gia);
}
listGia.Items[0].ForeColor = Color.DarkGreen;
}
private void ThongTinTour_Load(object sender, EventArgs e)
{
showThongtin();
}
private void listGia_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void dsdoankhach_Click(object sender, EventArgs e)
{
if (Tour.DoanKhachs == null)
MessageBox.Show("Không có đoàn khách nào");
else
{
DanhSachDoanKhach form = _serviceProvider.GetRequiredService<DanhSachDoanKhach>();
form.getId(_id);
var main = this.Location;
form.Location = new Point((main.X + 10), (main.Y + 10));
form.Show();
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using TourApp.Entity;
using TourApp.Repository.IRepository;
namespace TourApp
{
public partial class TKDoanhThu_Form : Form
{
private readonly ITourRepository _tourRepo;
private readonly IDoanKhachRepository _doanRepo;
private DateTime preDate;
public TKDoanhThu_Form(ITourRepository tourRepo, IDoanKhachRepository doanRepo)
{
InitializeComponent();
_tourRepo = tourRepo;
_doanRepo = doanRepo;
}
private void label3_Click(object sender, EventArgs e)
{
}
private void init()
{
select_radio();
datestart.Value = DateTime.Now.Date;
dateend.Value = DateTime.Now.Date;
//Xóa nền xám khi bị disable của listview
Bitmap bm = new Bitmap(lv_doanhthu1.ClientSize.Width, lv_doanhthu1.ClientSize.Height);
Graphics.FromImage(bm).Clear(lv_doanhthu1.BackColor);
lv_doanhthu1.BackgroundImage = bm;
}
// Select các dữ liệu của tour
private void tour_fill()
{
lv.Items.Clear();
IEnumerable<Tour> tours = _tourRepo.getAll();
foreach(Tour tour in tours)
{
ListViewItem item = new ListViewItem(tour.MaTour);
item.SubItems.Add(tour.Ten);
item.SubItems.Add(tour.LHDL.Ten);
lv.Items.Add(item);
}
}
// Select các dữ liệu của doan
private void doan_fill()
{
lv.Items.Clear();
IEnumerable<DoanKhach> doans = _doanRepo.getAll();
foreach (DoanKhach doan in doans)
{
ListViewItem item = new ListViewItem(doan.MaDoan);
item.SubItems.Add(doan.TenDoan);
lv.Items.Add(item);
}
}
//Chọn radio thay đổi dữ liệu
private void select_radio()
{
select_init_lv();
lv_doanhthu1.Items.Clear();
if (radio_tour.Checked == true)
{
tour_fill();
search_panel.Visible = true;
}
else
{
doan_fill();
search_panel.Visible = false;
}
}
//Tạo các tên cột cho listview
private void select_init_lv()
{
lv.Columns.Clear();
if (radio_tour.Checked == true)
{
lv.Columns.Add("ma", "Mã Tour").Width = 70;
lv.Columns.Add("ten", "Tên Tour").Width = 100;
lv.Columns.Add("loaihinh", "Loại").Width = 100;
}
else
{
lv.Columns.Add("ma", "Mã Đoàn").Width = 130;
lv.Columns.Add("ten", "Tên Đoàn").Width = 130;
}
}
//validate
private Boolean validate()
{
var dateStart = datestart.Value.Date;
var dateEnd = dateend.Value.Date;
var flg = true;
if (dateEnd < dateStart)
{
flg = false;
}
if(!flg)
{
MessageBox.Show("Ngày tìm kiếm không hợp lệ", "Thông báo");
}
return flg;
}
//Khi click vào các item sẽ hiển thị ra list các loại doanh thu và tổng doanh thu
private void ReadData()
{
lv_doanhthu1.Items.Clear();
if (lv.SelectedItems.Count == 0)
return;
var id = lv.SelectedItems[0].Text;
var dateStart = datestart.Value.Date;
var dateEnd = dateend.Value.Date;
var total = 0;
CultureInfo cul = CultureInfo.GetCultureInfo("vi-VN");
if (radio_tour.Checked == true)
{
var tour = _tourRepo.getById(0, id);
//DoanKhach filter
var doans = tour.DoanKhachs.Where(d => d.DateCreated.Date >= dateStart && d.DateCreated.Date <= dateEnd).ToList();
//In du lieu chi phi cua Doan
int income = 0;
if (doans != null && doans.Count > 0)
{
var count = 0;
foreach (var doan in doans)
{
var total_doan = 0;
var hanhkhach_count = (doan.CTDoans != null && doan.CTDoans.Count() > 0) ? doan.CTDoans.Count : 0 ;
var group1 = new ListViewGroup("doan" + count);
count++;
group1.Header = doan.TenDoan + " (" + doan.DateStart.Date.ToString("yyyy/MM/dd") + " - " + doan.DateEnd.Date.ToString("yyyy/MM/dd") + ") (" + hanhkhach_count + " hành khách )";
lv_doanhthu1.Groups.Add(group1);
ListViewItem item1 = new ListViewItem { Text = "Giá Tour (" + doan.Gia.TGBD.Date.ToString("yyyy/MM/dd") + " - " + doan.Gia.TGKT.Date.ToString("yyyy/MM/dd") + ")", Group = group1 };
var giaFormat1 = doan.Gia.GiaTri.ToString("#,###.##",cul).Replace(".", ",");
total_doan = total_doan + doan.Gia.GiaTri;
item1.SubItems.Add(giaFormat1 + " đ");
lv_doanhthu1.Items.Add(item1);
int income_item = 0;
int chiphi_item = 0;
foreach (var chitieu in doan.CTChitieus)
{
int chiphi = int.Parse(chitieu.TienCT);
chiphi_item += chiphi;
}
chiphi_item *= hanhkhach_count;
//Tổng tiền của đoàn * số lượng hành khách
total_doan = total_doan * hanhkhach_count;
total = total + total_doan;
ListViewItem item_doan = new ListViewItem { Text = "Tổng tiền thu được của đoàn", Group = group1 };
var giaFormat2 = total_doan.ToString("#,###.##", cul).Replace(".", ",");
item_doan.SubItems.Add(giaFormat2 + " đ");
lv_doanhthu1.Items.Add(item_doan);
// lợi nhuận 1 đoàn
income_item = total_doan - chiphi_item;
ListViewItem item = new ListViewItem { Text = "Lợi nhuận", Group = group1 };
var giaFormat = income_item.ToString("#,###.##", cul).Replace(".", ",");
item.SubItems.Add(giaFormat + " đ");
lv_doanhthu1.Items.Add(item);
income += income_item;
}
}
//In tong tien
ListViewGroup g1 = new ListViewGroup("tong");
g1.Header = "Tổng doanh thu - Lợi nhuận";
lv_doanhthu1.Groups.Add(g1);
ListViewItem totalItem = new ListViewItem { Text = "Tổng Tiền" , Group = g1 };
var giaTotalFormat = total.ToString("#,###.##", cul).Replace(".", ",");
totalItem.SubItems.Add(giaTotalFormat + " đ");
lv_doanhthu1.Items.Add(totalItem);
ListViewItem totalIncome = new ListViewItem { Text = "Tổng lợi nhuận", Group = g1 };
var incomeFormat = income.ToString("#,###.##", cul).Replace(".", ",");
totalIncome.SubItems.Add(incomeFormat + " đ");
lv_doanhthu1.Items.Add(totalIncome);
}
else
{
var doan = _doanRepo.getById(0, id);
var group1 = new ListViewGroup("doan");
group1.Header = doan.TenDoan + " (" + doan.DateStart.Date.ToString("yyyy/MM/dd") + " - " + doan.DateEnd.Date.ToString("yyyy/MM/dd") + ") (" + doan.CTDoans.Count() + " hành khách )";
lv_doanhthu1.Groups.Add(group1);
ListViewItem item1 = new ListViewItem { Text = "Giá Tour (" + doan.Gia.TGBD.Date.ToString("yyyy/MM/dd") + " - " + doan.Gia.TGKT.Date.ToString("yyyy/MM/dd") + ")", Group = group1 };
var giaFormat1 = doan.Gia.GiaTri.ToString("#,###.##", cul).Replace(".", ",");
total = total + doan.Gia.GiaTri;
item1.SubItems.Add(giaFormat1 + " đ");
lv_doanhthu1.Items.Add(item1);
//foreach (CTChitieu chitieu in doan.CTChitieus)
//{
// ListViewItem item = new ListViewItem { Text = chitieu.ChiTieu.Ten, Group = group1 };
// int chiphi = int.Parse(chitieu.TienCT);
// total = total + chiphi;
// var giaFormat = chiphi.ToString("#,###.##", cul).Replace(".", ",");
// item.SubItems.Add(giaFormat + " đ");
// lv_doanhthu1.Items.Add(item);
//}
//Tổng tiền của đoàn * số lượng hành khách
total = total * doan.CTDoans.Count();
ListViewItem item_doan = new ListViewItem { Text = "Tổng tiền thu được của đoàn", Group = group1 };
var giaFormat2 = total.ToString("#,###.##", cul).Replace(".", ",");
item_doan.SubItems.Add(giaFormat2 + " đ");
lv_doanhthu1.Items.Add(item_doan);
}
}
private void TKDoanhThu_Form_Load(object sender, EventArgs e)
{
init();
}
private void radio_CheckedChanged(object sender, EventArgs e)
{
select_radio();
}
private void lv_SelectedIndexChanged(object sender, EventArgs e)
{
ReadData();
}
private void date_ValueChanged(object sender, EventArgs e)
{
var oldValue = preDate;
preDate = ((DateTimePicker)sender).Value;
lv.SelectedItems.Clear();
if(!validate())
{
((DateTimePicker)sender).Value = oldValue;
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace TourApp.Const
{
public static class ErrorMsg
{
public const string err_blank = "Không cho phép để trống";
public const string err_phone = "Số điện thoại không hợp lệ";
public const string err_email = "Email không hợp lệ";
public const string err_minMaxDate = "Ngày kết thúc phải lớn hơn ngày bắt đầu";
public const string err_number = "Xin hãy nhập số";
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace TourApp.Repository.IRepository
{
public interface ICommonRepository<T> where T : new()
{
IEnumerable<T> getAll();
void Add(T entity);
void Update(T entity);
void Delete(T entity);
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using TourApp.Const;
using TourApp.Entity;
using TourApp.Repository.IRepository;
namespace TourApp
{
public partial class ThemLHDuLich : Form
{
private readonly ILoaiHinhDuLichRepository _loaiHinhDuLichRepository;
public int _id = -1;
public EditState editState { get; set; }
public ThemLHDuLich(ILoaiHinhDuLichRepository loaiHinhDuLichRepository)
{
_loaiHinhDuLichRepository = loaiHinhDuLichRepository;
InitializeComponent();
}
public void setId(int id)
{
_id = id;
}
private bool check()
{
bool error = false;
if (LHname.Text == "")
{
errorlabel.Text = ErrorMsg.err_blank;
errorlabel.Visible = true;
LHname.Focus();
error = true;
}
else
{
errorlabel.Visible = false;
}
return error;
}
private void init()
{
switch (editState)
{
case EditState.View:
{
LoaiHinhDL lh = _loaiHinhDuLichRepository.getById(_id);
LHname.Text = lh.Ten;
Mota.Text = lh.moTa;
LHname.Enabled = false;
Mota.Enabled = false;
Savebtt.Enabled = false;
break;
}
case EditState.Edit:
{
LoaiHinhDL lh = _loaiHinhDuLichRepository.getById(_id);
LHname.Text = lh.Ten;
Mota.Text = lh.moTa;
break;
}
case EditState.Create:
{
break;
}
}
}
protected override void OnLoad(EventArgs e)
{
init();
}
private void button1_Click(object sender, EventArgs e)
{
if (check())
{
return;
}
if (_id != -1)
{
LoaiHinhDL lh = _loaiHinhDuLichRepository.getById(_id);
lh.Ten = LHname.Text;
lh.moTa = Mota.Text;
_loaiHinhDuLichRepository.Update(lh);
MessageBox.Show("Sửa thành công Loại hình du lịch");
Program.Form.TabRefresh(ListTab.LoaiHinhDuLich);
}
else
{
LoaiHinhDL lh = new LoaiHinhDL();
lh.Ten = LHname.Text;
lh.moTa = Mota.Text;
_loaiHinhDuLichRepository.Add(lh);
MessageBox.Show("Thêm thành công Loại hình du lịch");
Program.Form.TabRefresh(ListTab.LoaiHinhDuLich);
this.Close();
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using TourApp.Entity;
namespace TourApp.Repository.IRepository
{
public interface IChiTieuRepository : ICommonRepository<ChiTieu>
{
IEnumerable<ChiTieu> getWhere(string ID,string Ten);
ChiTieu getByName(String Ten);
ChiTieu getById(int CTId);
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using TourApp.Entity;
namespace TourApp.Repository.IRepository
{
public interface IDoanKhachRepository : ICommonRepository<DoanKhach>
{
IEnumerable<DoanKhach> getWhere(string ID, string MaDoan, string TenDoan, string Chitiet, string Tinhtrang, string TourID, string MaTour, int isDeleted, string nameTour = "");
IEnumerable<DoanKhach> getAllDelete();
DoanKhach getById(int id, string maHK = "");
}
}
<file_sep>
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Drawing;
using System.Linq;
using System.Linq.Expressions;
using System.Windows.Forms;
using TourApp.Const;
using TourApp.Entity;
using TourApp.Repository.IRepository;
using TourApp.UI;
namespace TourApp
{
public partial class List : Form
{
private readonly ITourRepository _tourRepo;
private readonly INhanVienRepository _nhanvienRepo;
private readonly IChiTieuRepository _chitieuRepo;
private readonly IDoanKhachRepository _doankhachRepo;
private readonly IHanhKhachRepository _hanhkhachRepo;
private readonly IDiaDiemRepository _diadiemRepo;
private readonly ILoaiHinhDuLichRepository _lhdlRepo;
private readonly IServiceProvider _serviceProvider;
public List(
ITourRepository tourRepo,
INhanVienRepository nhanvienRepo,
IChiTieuRepository chitieuRepo,
IDoanKhachRepository doankhachRepo,
IHanhKhachRepository hanhkhachRepo,
IDiaDiemRepository diadiemRepo,
ILoaiHinhDuLichRepository lhdlRepo,
IServiceProvider serviceProvider
)
{
InitializeComponent();
_tourRepo = tourRepo;
_nhanvienRepo = nhanvienRepo;
_chitieuRepo = chitieuRepo;
_doankhachRepo = doankhachRepo;
_hanhkhachRepo = hanhkhachRepo;
_diadiemRepo = diadiemRepo;
_lhdlRepo = lhdlRepo;
_serviceProvider = serviceProvider;
tabControl.SelectedTab = tabTour;
}
private void Form1_Load(object sender, EventArgs e)
{
TabRefresh(ListTab.Tour);
TabRefresh(ListTab.Nhanvien);
TabRefresh(ListTab.Chitieu);
TabRefresh(ListTab.Doan);
TabRefresh(ListTab.HanhKhach);
TabRefresh(ListTab.Diadiem);
TabRefresh(ListTab.LoaiHinhDuLich);
ChangeTheme(new DefaultTheme(), this.Controls);
}
public void TabRefresh(ListTab tab)
{
switch (tab)
{
case ListTab.Tour:
{
tabTour_FromDate.Value = tabTour_FromDate.MinDate;
tabTour_ToDate.Value = tabTour_ToDate.MaxDate;
tabTour_ToPrice.Value = tabTour_ToPrice.Maximum;
tabTour_SearchOption.SelectedIndex = 0;
searchBox.Text = "";
isDeleted_ChB.Checked = false;
Search();
break;
}
case ListTab.Nhanvien:
{
tabNV_SearchBox.Text = "";
tabNV_CB.Checked = false;
tabNV_SearchOption.SelectedIndex = 2;
tabNV_Search();
break;
}
case ListTab.Chitieu:
{
tabCT_SearchBox.Text = "";
tabCT_SearchOption.SelectedIndex = 1;
tabCT_Search();
break;
}
case ListTab.Doan:
{
tabDoan_SearchBox.Text = "";
tabDoan_CB.Checked = false;
tabDoan_SearchOption.SelectedIndex = 2;
tabDoan_Search();
break;
}
case ListTab.HanhKhach:
{
tabHanhKhach_SearchBox.Text = "";
tabHanhKhach_CB.Checked = false;
tabHanhKhach_SearchOption.SelectedIndex = 2;
tabHanhKhach_Search();
break;
}
case ListTab.Diadiem:
{
tabDD_SearchBox.Text = "";
tabDD_SearchOption.SelectedIndex = 1;
tabDD_Search();
break;
}
case ListTab.LoaiHinhDuLich:
{
tabLHDL_SearchBox.Text = "";
tabLHDL_SearchOption.SelectedIndex = 1;
tabLHDL_Search();
break;
}
}
}
#region Setting menu
//change theme
private void ChangeThemeMenu_DropDownItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
//get the parent item
ToolStripMenuItem ownerItem = e.ClickedItem.OwnerItem as ToolStripMenuItem;
if (ownerItem != null)
{
//uncheck all item
foreach (ToolStripMenuItem item in ownerItem.DropDownItems)
{
item.Checked = false;
}
}
//it will check the clicked item automatically
//change theme
if (e.ClickedItem == DarkStripMenuItem) ChangeTheme(new DarkTheme(), this.Controls);
else if (e.ClickedItem == LightStripMenuItem) ChangeTheme(new LightTheme(), this.Controls);
else ChangeTheme(new DefaultTheme(), this.Controls);
}
private void ChangeTheme(Theme theme, Control.ControlCollection container)
{
foreach (Control component in container)
{
switch (component)
{
case MenuStrip _:
(component as MenuStrip).BackColor = theme.MenuStripBG;
(component as MenuStrip).ForeColor = theme.MenuStripFG;
ChangeTheme(theme, component.Controls);
break;
case TabControl _:
(component as TabControl).BackColor = theme.TabControlBG;
(component as TabControl).ForeColor = theme.TabControlFG;
ChangeTheme(theme, component.Controls);
break;
case TabPage _:
(component as TabPage).BackColor = theme.TabPageBG;
(component as TabPage).ForeColor = theme.TabPageFG;
ChangeTheme(theme, component.Controls);
break;
case DataGridView _:
(component as DataGridView).BackgroundColor = theme.DataGridviewBG;
(component as DataGridView).ForeColor = theme.DataGridviewFG;
(component as DataGridView).GridColor = theme.DataGridviewGridColor;
ChangeTheme(theme, component.Controls);
break;
case TextBox _:
(component as TextBox).BackColor = theme.TextBoxBG;
(component as TextBox).ForeColor = theme.TextBoxFG;
ChangeTheme(theme, component.Controls);
break;
case Button _:
(component as Button).BackColor = theme.ButtonBG;
(component as Button).ForeColor = theme.ButtonFG;
ChangeTheme(theme, component.Controls);
break;
case ComboBox _:
(component as ComboBox).BackColor = theme.ComboBoxBG;
(component as ComboBox).ForeColor = theme.ComboBoxFG;
ChangeTheme(theme, component.Controls);
break;
}
}
}
//export button pressed
private void FileMenu_DropDownItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
var saveDialog = new SaveFileDialog
{
Filter = "Excel file (*.xlsx)|*.xlsx",
FileName = "export.xlsx",
Title = "Export data to excel",
CheckFileExists = false
};
if (saveDialog.ShowDialog() != DialogResult.OK) return;
DataGridView data = tabControl.SelectedTab.Controls.OfType<DataGridView>().First();
exportExcel(data, saveDialog.FileName);
saveDialog.Dispose();
}
//export excel
private void exportExcel(DataGridView grid, string filepath)
{
// Create a spreadsheet document by supplying the filepath.
// By default, AutoSave = true, Editable = true, and Type = xlsx.
var spreadsheetDocument = DocumentFormat.OpenXml.Packaging.SpreadsheetDocument.
Create(filepath, DocumentFormat.OpenXml.SpreadsheetDocumentType.Workbook);
// Add a WorkbookPart to the document.
var workbookpart = spreadsheetDocument.AddWorkbookPart();
workbookpart.Workbook = new DocumentFormat.OpenXml.Spreadsheet.Workbook();
// Add a WorksheetPart to the WorkbookPart.
var worksheetPart = workbookpart.AddNewPart<DocumentFormat.OpenXml.Packaging.WorksheetPart>();
var sheetData = new DocumentFormat.OpenXml.Spreadsheet.SheetData();
worksheetPart.Worksheet = new DocumentFormat.OpenXml.Spreadsheet.Worksheet(sheetData);
// Add Sheets to the Workbook.
var sheets = spreadsheetDocument.WorkbookPart.Workbook.
AppendChild(new DocumentFormat.OpenXml.Spreadsheet.Sheets());
// Append a new worksheet and associate it with the workbook.
var sheet = new DocumentFormat.OpenXml.Spreadsheet.Sheet()
{
Id = spreadsheetDocument.WorkbookPart.
GetIdOfPart(worksheetPart),
SheetId = 1,
Name = "mySheet"
};
sheets.Append(sheet);
var row_header = new DocumentFormat.OpenXml.Spreadsheet.Row() { RowIndex = 1 };
for(var j=0;j<grid.ColumnCount;j++)
{
if (!(grid.Columns[j] is DataGridViewTextBoxColumn)) continue;
var cell = new DocumentFormat.OpenXml.Spreadsheet.Cell()
{
CellValue = new DocumentFormat.OpenXml.Spreadsheet.CellValue(grid.Columns[j].HeaderText),
DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.String
};
row_header.Append(cell);
}
sheetData.Append(row_header);
for (var i = 0; i < grid.RowCount; i++)
{
var row = new DocumentFormat.OpenXml.Spreadsheet.Row();
for (var j = 0; j < grid.ColumnCount; j++)
{
var grid_cell = grid.Rows[i].Cells[j];
if (grid_cell.Value == null) continue;
var cell = new DocumentFormat.OpenXml.Spreadsheet.Cell()
{
CellValue = new DocumentFormat.OpenXml.Spreadsheet.CellValue(grid_cell.Value.ToString()),
DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.String
};
row.Append(cell);
}
sheetData.Append(row);
}
workbookpart.Workbook.Save();
// Close the document.
spreadsheetDocument.Close();
spreadsheetDocument.Dispose();
}
//statistic - Thống kê
private void TKChiPhiMenu_Clicked(object sender, EventArgs e)
{
TKChiPhi_Form form = _serviceProvider.GetRequiredService<TKChiPhi_Form>();
var main = this.Location;
form.Location = new Point((main.X + 10), (main.Y + 10));
form.Show();
}
private void TKDoanhThuMenu_Clicked(object sender, EventArgs e)
{
TKDoanhThu_Form form = _serviceProvider.GetRequiredService<TKDoanhThu_Form>();
var main = this.Location;
form.Location = new Point((main.X + 10), (main.Y + 10));
form.Show();
}
private void TKTinhHinhHoatDong_Clicked(object sender, EventArgs e)
{
TKTinhHinhHoatDong form = _serviceProvider.GetRequiredService<TKTinhHinhHoatDong>();
var main = this.Location;
form.Location = new Point((main.X + 10), (main.Y + 10));
form.Show();
}
private void TKSoLanDiTour_Clicked(object sender, EventArgs e)
{
TK_NhanVienTour form = _serviceProvider.GetRequiredService<TK_NhanVienTour>();
var main = this.Location;
form.Location = new Point((main.X + 10), (main.Y + 10));
form.Show();
}
#endregion
#region Tour
private void tourGridView_CellPainting_1(object sender, DataGridViewCellPaintingEventArgs e)
{
if (e.RowIndex < 0)
return;
//I supposed your button column is at index 0
if (e.ColumnIndex == 4)
{
e.Paint(e.CellBounds, DataGridViewPaintParts.All);
var img = Properties.Resources.view;
var w = e.CellBounds.Width-2;
var h = e.CellBounds.Height-2;
var x = e.CellBounds.Left + (e.CellBounds.Width - w) / 2;
var y = e.CellBounds.Top + (e.CellBounds.Height - h) / 2;
e.Graphics.DrawImage(img, new Rectangle(x, y, w, h));
e.Handled = true;
}
if (e.ColumnIndex == 5)
{
e.Paint(e.CellBounds, DataGridViewPaintParts.All);
var img = Properties.Resources.edit;
var w = e.CellBounds.Width - 2;
var h = e.CellBounds.Height - 2;
var x = e.CellBounds.Left + (e.CellBounds.Width - w) / 2;
var y = e.CellBounds.Top + (e.CellBounds.Height - h) / 2;
e.Graphics.DrawImage(img, new Rectangle(x, y, w, h));
e.Handled = true;
}
if (e.ColumnIndex == 6)
{
e.Paint(e.CellBounds, DataGridViewPaintParts.All);
var img = Properties.Resources.delete;
var w = e.CellBounds.Width - 2;
var h = e.CellBounds.Height - 2;
var x = e.CellBounds.Left + (e.CellBounds.Width - w) / 2;
var y = e.CellBounds.Top + (e.CellBounds.Height - h) / 2;
e.Graphics.DrawImage(img, new Rectangle(x, y, w, h));
e.Handled = true;
}
}
private void button2_Click(object sender, EventArgs e)
{
ThemTour form = _serviceProvider.GetRequiredService<ThemTour>();
var main = this.Location;
form.Location = new Point((main.X + 10), (main.Y + 10));
form.Show();
}
private void tourGridView_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex == -1) return;
var grid = (DataGridView)sender;
var name = grid.Columns[e.ColumnIndex].Name;
var value = grid.Rows[e.RowIndex].Cells["TourIdCol"].Value.ToString();
switch (name)
{
case "ViewCol":
ThongTinTour form = _serviceProvider.GetRequiredService<ThongTinTour>();
form.getId(int.Parse(value));
var main = this.Location;
form.Location = new Point((main.X + 10), (main.Y + 10));
form.Show();
break;
case "EditCol":
SuaTour form2 = _serviceProvider.GetRequiredService<SuaTour>();
form2.getId(int.Parse(value));
var main2 = this.Location;
form2.Location = new Point((main2.X + 10), (main2.Y + 10));
form2.Show();
break;
case "DeleteCol":
var tour = _tourRepo.getById(int.Parse(value));
var messageResult = MessageBox.Show("Bạn có chắc muốn xóa "+ tour.Ten, "Warning", MessageBoxButtons.YesNo);
if (messageResult != DialogResult.Yes) return;
_tourRepo.Delete(tour);
Search();
break;
}
}
private void tourGridView_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex == -1) return;
var grid = (DataGridView)sender;
var name = grid.Columns[e.ColumnIndex].Name;
if (name == "EditCol" || name == "ViewCol" || name == "DeleteCol") return;
var value = grid.Rows[e.RowIndex].Cells["TourIdCol"].Value.ToString();
ThongTinTour form = _serviceProvider.GetRequiredService<ThongTinTour>();
form.getId(int.Parse(value));
var main = this.Location;
form.Location = new Point((main.X + 10), (main.Y + 10));
form.Show();
}
private void button1_Click(object sender, EventArgs e)
{
Search();
}
private void Search()
{
string searchTen, searchLHDL, searchID, searchMaTour;
searchTen = searchLHDL = searchID = searchMaTour = "";
switch (tabTour_SearchOption.SelectedIndex)
{
case 0:
searchTen = searchBox.Text;
break;
case 1:
searchMaTour = searchBox.Text;
break;
case 2:
searchID = searchBox.Text;
break;
case 3:
searchLHDL = searchBox.Text;
break;
}
tourGridView.Rows.Clear();
var data = _tourRepo.getWhere(searchTen,searchLHDL,searchID,searchMaTour,
tabTour_FromDate.Value,tabTour_ToDate.Value,
(int)tabTour_FromPrice.Value,(int) tabTour_ToPrice.Value,
isDeleted_ChB.Checked ? 1 : 0);
foreach (Tour item in data)
{
tourGridView.Rows.Add(item.TourId, item.MaTour, item.Ten, item.LHDL.Ten);
}
}
private void btnRefresh_Click(object sender, EventArgs e)
{
TabRefresh(ListTab.Tour);
}
private void searchBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter) Search();
}
private void isDeleted_CheckedChanged(object sender, EventArgs e)
{
Search();
if (isDeleted_ChB.Checked)
{
tourGridView.Columns["EditCol"].Visible = false;
tourGridView.Columns["DeleteCol"].Visible = false;
}
else
{
tourGridView.Columns["EditCol"].Visible = true;
tourGridView.Columns["DeleteCol"].Visible = true;
}
}
#endregion
#region Nhan vien
private void NVGridView_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
if (e.RowIndex < 0)
return;
//I supposed your button column is at index 0
if (e.ColumnIndex == 5)
{
e.Paint(e.CellBounds, DataGridViewPaintParts.All);
var img = Properties.Resources.view;
var w = e.CellBounds.Width - 2;
var h = e.CellBounds.Height - 2;
var x = e.CellBounds.Left + (e.CellBounds.Width - w) / 2;
var y = e.CellBounds.Top + (e.CellBounds.Height - h) / 2;
e.Graphics.DrawImage(img, new Rectangle(x, y, w, h));
e.Handled = true;
}
if (e.ColumnIndex == 6)
{
e.Paint(e.CellBounds, DataGridViewPaintParts.All);
var img = Properties.Resources.edit;
var w = e.CellBounds.Width - 2;
var h = e.CellBounds.Height - 2;
var x = e.CellBounds.Left + (e.CellBounds.Width - w) / 2;
var y = e.CellBounds.Top + (e.CellBounds.Height - h) / 2;
e.Graphics.DrawImage(img, new Rectangle(x, y, w, h));
e.Handled = true;
}
if (e.ColumnIndex == 7)
{
e.Paint(e.CellBounds, DataGridViewPaintParts.All);
var img = Properties.Resources.delete;
var w = e.CellBounds.Width - 2;
var h = e.CellBounds.Height - 2;
var x = e.CellBounds.Left + (e.CellBounds.Width - w) / 2;
var y = e.CellBounds.Top + (e.CellBounds.Height - h) / 2;
e.Graphics.DrawImage(img, new Rectangle(x, y, w, h));
e.Handled = true;
}
}
private void NVGridView_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex == -1) return;
var grid = (DataGridView)sender;
var name = grid.Columns[e.ColumnIndex].Name;
var value = grid.Rows[e.RowIndex].Cells["tabNV_IDCol"].Value.ToString();
switch (name)
{
case "tabNV_ViewCol":
NhanVienAdd form = _serviceProvider.GetRequiredService<NhanVienAdd>();
form.id = int.Parse(value);
form.editState = EditState.View;
var main = this.Location;
form.Location = new Point((main.X + 10), (main.Y + 10));
form.Show();
break;
case "tabNV_EditCol":
NhanVienAdd form1 = _serviceProvider.GetRequiredService<NhanVienAdd>();
form1.id = int.Parse(value);
form1.editState = EditState.Edit;
var main1 = this.Location;
form1.Location = new Point((main1.X + 10), (main1.Y + 10));
form1.Show();
break;
case "tabNV_DeleteCol":
var nhanvien = _nhanvienRepo.getById(int.Parse(value));
var messageResult = MessageBox.Show("Bạn có chắc muốn xóa " + nhanvien.Ten, "Warning", MessageBoxButtons.YesNo);
if (messageResult != DialogResult.Yes) return;
_nhanvienRepo.Delete(nhanvien);
tabNV_Search();
break;
}
}
//add
private void tabNV_SearchBtn_Click(object sender, EventArgs e)
{
tabNV_Search();
}
private void tabNV_AddBtn_Click(object sender, EventArgs e)
{
NhanVienAdd form = _serviceProvider.GetRequiredService<NhanVienAdd>();
var main = this.Location;
form.Location = new Point((main.X + 10), (main.Y + 10));
form.editState = EditState.Create;
form.Show();
}
private void tabNV_RefreshBtn_Click(object sender, EventArgs e)
{
TabRefresh(ListTab.Nhanvien);
}
private void NVGridView_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex == -1) return;
var grid = (DataGridView)sender;
var name = grid.Columns[e.ColumnIndex].Name;
if (name == "tabNV_EditCol" || name == "tabNV_ViewCol" || name == "tabNV_DeleteCol") return;
var value = grid.Rows[e.RowIndex].Cells["tabNV_IDCol"].Value.ToString();
//ThongTinTour form = _serviceProvider.GetRequiredService<ThongTinTour>();
//form.getId(int.Parse(value));
//var main = this.Location;
//form.Location = new Point((main.X + 10), (main.Y + 10));
//form.Show();
}
private void tabNV_Search()
{
string ID_str, MaNV_str, Ten_str, SDT_str;
ID_str = MaNV_str = Ten_str = SDT_str = "";
switch (tabNV_SearchOption.SelectedIndex)
{
case 0:
ID_str = tabNV_SearchBox.Text;
break;
case 1:
MaNV_str = tabNV_SearchBox.Text;
break;
case 2:
Ten_str = tabNV_SearchBox.Text;
break;
case 3:
SDT_str = tabNV_SearchBox.Text;
break;
}
NVGridView.Rows.Clear();
var data = _nhanvienRepo.getWhere(ID_str,MaNV_str,Ten_str,SDT_str,tabNV_CB.Checked ? 1 : 0);
foreach (NhanVien item in data)
{
NVGridView.Rows.Add(item.NVId, item.MaNV, item.Ten, item.SDT);
}
}
private void tabNV_SearchBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter) tabNV_Search();
}
private void tabNV_CB_CheckedChanged(object sender, EventArgs e)
{
tabNV_Search();
if (tabNV_CB.Checked)
{
NVGridView.Columns["tabNV_EditCol"].Visible = false;
NVGridView.Columns["tabNV_DeleteCol"].Visible = false;
}
else
{
NVGridView.Columns["tabNV_EditCol"].Visible = true;
NVGridView.Columns["tabNV_DeleteCol"].Visible = true;
}
}
#endregion
#region Chỉ tiêu
private void ChiTieuGridView_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
if (e.RowIndex < 0)
return;
//I supposed your button column is at index 0
if (e.ColumnIndex == 3)
{
e.Paint(e.CellBounds, DataGridViewPaintParts.All);
var img = Properties.Resources.view;
var w = e.CellBounds.Width - 2;
var h = e.CellBounds.Height - 2;
var x = e.CellBounds.Left + (e.CellBounds.Width - w) / 2;
var y = e.CellBounds.Top + (e.CellBounds.Height - h) / 2;
e.Graphics.DrawImage(img, new Rectangle(x, y, w, h));
e.Handled = true;
}
if (e.ColumnIndex == 4)
{
e.Paint(e.CellBounds, DataGridViewPaintParts.All);
var img = Properties.Resources.edit;
var w = e.CellBounds.Width - 2;
var h = e.CellBounds.Height - 2;
var x = e.CellBounds.Left + (e.CellBounds.Width - w) / 2;
var y = e.CellBounds.Top + (e.CellBounds.Height - h) / 2;
e.Graphics.DrawImage(img, new Rectangle(x, y, w, h));
e.Handled = true;
}
if (e.ColumnIndex == 5)
{
e.Paint(e.CellBounds, DataGridViewPaintParts.All);
var img = Properties.Resources.delete;
var w = e.CellBounds.Width - 2;
var h = e.CellBounds.Height - 2;
var x = e.CellBounds.Left + (e.CellBounds.Width - w) / 2;
var y = e.CellBounds.Top + (e.CellBounds.Height - h) / 2;
e.Graphics.DrawImage(img, new Rectangle(x, y, w, h));
e.Handled = true;
}
}
private void tabCT_Search()
{
string id_str, ten_str;
id_str = ten_str = "";
switch (tabCT_SearchOption.SelectedIndex)
{
case 0:
id_str = tabCT_SearchBox.Text;
break;
case 1:
ten_str = tabCT_SearchBox.Text; ;
break;
}
ChiTieuGridView.Rows.Clear();
var data = _chitieuRepo.getWhere(id_str,ten_str);
foreach (ChiTieu item in data)
{
ChiTieuGridView.Rows.Add(item.CTId, item.Ten);
}
}
private void tabCT_SearchBtn_Click(object sender, EventArgs e)
{
tabCT_Search();
}
private void tabCT_SearchBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter) tabCT_Search();
}
private void tabCT_RefreshBtn_Click(object sender, EventArgs e)
{
TabRefresh(ListTab.Chitieu);
}
private void tabCT_AddBtn_Click(object sender, EventArgs e)
{
ThemChiTieu form = _serviceProvider.GetRequiredService<ThemChiTieu>();
var main = this.Location;
form.Location = new Point((main.X + 10), (main.Y + 10));
form.Show();
}
private void ChiTieuGridView_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex == -1) return;
var grid = (DataGridView)sender;
var name = grid.Columns[e.ColumnIndex].Name;
var value = grid.Rows[e.RowIndex].Cells["tabCT_IDCol"].Value.ToString();
switch (name)
{
case "tabCT_ViewCol":
ThemChiTieu form = _serviceProvider.GetRequiredService<ThemChiTieu>();
form.setId(int.Parse(value));
form.editState = EditState.View;
var main = this.Location;
form.Location = new Point((main.X + 10), (main.Y + 10));
form.Show();
break;
case "tabCT_EditCol":
ThemChiTieu form1 = _serviceProvider.GetRequiredService<ThemChiTieu>();
form1.setId(int.Parse(value));
form1.editState = EditState.Edit;
var main1 = this.Location;
form1.Location = new Point((main1.X + 10), (main1.Y + 10));
form1.Show();
break;
case "tabCT_DeleteCol":
var chitieu = _chitieuRepo.getById(int.Parse(value));
var messageResult = MessageBox.Show("Bạn có chắc muốn xóa " + chitieu.Ten, "Warning", MessageBoxButtons.YesNo);
if (messageResult != DialogResult.Yes) return;
_chitieuRepo.Delete(chitieu);
tabCT_Search();
break;
}
}
private void ChiTieuGridView_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex == -1) return;
var grid = (DataGridView)sender;
var name = grid.Columns[e.ColumnIndex].Name;
if (name == "tabCT_EditCol" || name == "tabCT_ViewCol" || name == "tabCT_DeleteCol") return;
var value = grid.Rows[e.RowIndex].Cells["tabCT_IDCol"].Value.ToString();
ThemChiTieu form = _serviceProvider.GetRequiredService<ThemChiTieu>();
form.setId(int.Parse(value));
form.editState = EditState.View;
var main = this.Location;
form.Location = new Point((main.X + 10), (main.Y + 10));
form.Show();
}
#endregion
#region Đoàn
private void tabDoan_Search()
{
string ID_str, MaDoan_str, TenDoan_str, Chitiet_str, Tinhtrang_str, TourID_str, MaTour_str;
ID_str = MaDoan_str = TenDoan_str = Chitiet_str = Tinhtrang_str = TourID_str = MaTour_str = "";
switch (tabDoan_SearchOption.SelectedIndex)
{
case 0:
ID_str = tabDoan_SearchBox.Text;
break;
case 1:
MaDoan_str = tabDoan_SearchBox.Text;
break;
case 2:
TenDoan_str = tabDoan_SearchBox.Text;
break;
case 3:
Chitiet_str = tabDoan_SearchBox.Text;
break;
case 4:
TourID_str = tabDoan_SearchBox.Text;
break;
case 5:
MaTour_str = tabDoan_SearchBox.Text;
break;
}
DoanGridView.Rows.Clear();
var data = _doankhachRepo.getWhere(ID_str, MaDoan_str, TenDoan_str, Chitiet_str, Tinhtrang_str, TourID_str, MaTour_str, tabDoan_CB.Checked ? 1 : 0);
foreach (DoanKhach item in data)
{
DoanGridView.Rows.Add(item.DoanId, item.MaDoan, item.TenDoan, item.Chitiet, item.TourId, item.Tour.MaTour);
}
}
private void tabDoan_SearchBtn_Click(object sender, EventArgs e)
{
tabDoan_Search();
}
private void tabDoan_SearchBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter) tabDoan_Search();
}
private void tabDoan_CB_CheckedChanged(object sender, EventArgs e)
{
tabDoan_Search();
if (tabDoan_CB.Checked)
{
DoanGridView.Columns["tabDoan_EditCol"].Visible = false;
DoanGridView.Columns["tabDoan_DeleteCol"].Visible = false;
}
else
{
DoanGridView.Columns["tabDoan_EditCol"].Visible = true;
DoanGridView.Columns["tabDoan_DeleteCol"].Visible = true;
}
}
private void tabDoan_RefreshBtn_Click(object sender, EventArgs e)
{
TabRefresh(ListTab.Doan);
}
private void tabDoan_AddBtn_Click(object sender, EventArgs e)
{
DoanKhach_Form form = _serviceProvider.GetRequiredService<DoanKhach_Form>();
var main = this.Location;
form.Location = new Point((main.X + 10), (main.Y + 10));
form.Show();
}
private void doanGridview_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
if (e.RowIndex < 0)
return;
//I supposed your button column is at index 0
if (e.ColumnIndex == 6)
{
e.Paint(e.CellBounds, DataGridViewPaintParts.All);
var img = Properties.Resources.view;
var w = e.CellBounds.Width - 2;
var h = e.CellBounds.Height - 2;
var x = e.CellBounds.Left + (e.CellBounds.Width - w) / 2;
var y = e.CellBounds.Top + (e.CellBounds.Height - h) / 2;
e.Graphics.DrawImage(img, new Rectangle(x, y, w, h));
e.Handled = true;
}
if (e.ColumnIndex == 7)
{
e.Paint(e.CellBounds, DataGridViewPaintParts.All);
var img = Properties.Resources.edit;
var w = e.CellBounds.Width - 2;
var h = e.CellBounds.Height - 2;
var x = e.CellBounds.Left + (e.CellBounds.Width - w) / 2;
var y = e.CellBounds.Top + (e.CellBounds.Height - h) / 2;
e.Graphics.DrawImage(img, new Rectangle(x, y, w, h));
e.Handled = true;
}
if (e.ColumnIndex == 8)
{
e.Paint(e.CellBounds, DataGridViewPaintParts.All);
var img = Properties.Resources.delete;
var w = e.CellBounds.Width - 2;
var h = e.CellBounds.Height - 2;
var x = e.CellBounds.Left + (e.CellBounds.Width - w) / 2;
var y = e.CellBounds.Top + (e.CellBounds.Height - h) / 2;
e.Graphics.DrawImage(img, new Rectangle(x, y, w, h));
e.Handled = true;
}
}
private void doanGridview_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex == -1) return;
var grid = (DataGridView)sender;
var name = grid.Columns[e.ColumnIndex].Name;
var value = grid.Rows[e.RowIndex].Cells["tabDoan_IDCol"].Value.ToString();
switch (name)
{
case "tabDoan_ViewCol":
DoanKhach_Form form1 = _serviceProvider.GetRequiredService<DoanKhach_Form>();
form1.formType = EditState.View;
form1.id = int.Parse(value);
var main1 = this.Location;
form1.Location = new Point((main1.X + 10), (main1.Y + 10));
form1.Show();
break;
case "tabDoan_EditCol":
DoanKhach_Form form = _serviceProvider.GetRequiredService<DoanKhach_Form>();
form.id = int.Parse(value);
form.formType = EditState.Edit;
var main = this.Location;
form.Location = new Point((main.X + 10), (main.Y + 10));
form.Show();
break;
case "tabDoan_DeleteCol":
var doan = _doankhachRepo.getById(int.Parse(value));
var messageResult = MessageBox.Show("Bạn có chắc muốn xóa " + doan.TenDoan, "Warning", MessageBoxButtons.YesNo);
if (messageResult != DialogResult.Yes) return;
_doankhachRepo.Delete(doan);
tabDoan_Search();
break;
}
}
private void doanGridview_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex == -1) return;
var grid = (DataGridView)sender;
var name = grid.Columns[e.ColumnIndex].Name;
if (name == "tabDoan_EditCol" || name == "tabDoan_ViewCol" || name == "tabDoan_DeleteCol") return;
var value = grid.Rows[e.RowIndex].Cells["tabDoan_IDCol"].Value.ToString();
DoanKhach_Form form = _serviceProvider.GetRequiredService<DoanKhach_Form>();
form.formType = EditState.View;
form.id = int.Parse(value);
var main = this.Location;
form.Location = new Point((main.X + 10), (main.Y + 10));
form.Show();
}
#endregion
#region Hành khách
private void tabHanhKhach_Search()
{
string KhachId_str, MaKhach_str, Ten_str, SDT_str, Email_str, CMND_str, DiaChi_str, GioiTinh_str, Passport_str;
KhachId_str = MaKhach_str = Ten_str = SDT_str = Email_str = CMND_str = DiaChi_str = GioiTinh_str = Passport_str = "";
switch (tabHanhKhach_SearchOption.SelectedIndex)
{
case 0:
KhachId_str = tabHanhKhach_SearchBox.Text;
break;
case 1:
MaKhach_str = tabHanhKhach_SearchBox.Text;
break;
case 2:
Ten_str = tabHanhKhach_SearchBox.Text;
break;
case 3:
SDT_str = tabHanhKhach_SearchBox.Text;
break;
case 4:
Email_str = tabHanhKhach_SearchBox.Text;
break;
case 5:
CMND_str = tabHanhKhach_SearchBox.Text;
break;
case 6:
DiaChi_str = tabHanhKhach_SearchBox.Text;
break;
case 7:
GioiTinh_str = tabHanhKhach_SearchBox.Text;
break;
case 8:
Passport_str = tabHanhKhach_SearchBox.Text;
break;
}
HanhKhachGridView.Rows.Clear();
var data = _hanhkhachRepo.getWhere(KhachId_str, MaKhach_str, Ten_str, SDT_str, Email_str, CMND_str, DiaChi_str, GioiTinh_str, Passport_str, tabHanhKhach_CB.Checked ? 1 : 0);
foreach (HanhKhach item in data)
{
HanhKhachGridView.Rows.Add(item.KhachId, item.MaKhach, item.Ten, item.SDT, item.Email, item.CMND, item.DiaChi, item.GioiTinh, item.Passport);
}
}
private void tabHanhKhach_SearchBtn_Click(object sender, EventArgs e)
{
tabHanhKhach_Search();
}
private void tabHanhKhach_SearchBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter) tabHanhKhach_Search();
}
private void tabHanhKhach_RefreshBtn_Click(object sender, EventArgs e)
{
TabRefresh(ListTab.HanhKhach);
}
private void tabHanhKhach_AddBtn_Click(object sender, EventArgs e)
{
HanhKhach_Form form = _serviceProvider.GetRequiredService<HanhKhach_Form>();
form.editState = EditState.Create;
var main = this.Location;
form.Location = new Point((main.X + 10), (main.Y + 10));
form.Show();
}
private void tabHanhKhach_CB_CheckedChanged(object sender, EventArgs e)
{
tabHanhKhach_Search();
if (tabHanhKhach_CB.Checked)
{
HanhKhachGridView.Columns["tabHanhKhach_EditCol"].Visible = false;
HanhKhachGridView.Columns["tabHanhKhach_DeleteCol"].Visible = false;
}
else
{
HanhKhachGridView.Columns["tabHanhKhach_EditCol"].Visible = true;
HanhKhachGridView.Columns["tabHanhKhach_DeleteCol"].Visible = true;
}
}
private void HanhKhachGridView_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
if (e.RowIndex < 0)
return;
//I supposed your button column is at index 0
if (e.ColumnIndex == 9)
{
e.Paint(e.CellBounds, DataGridViewPaintParts.All);
var img = Properties.Resources.view;
var w = e.CellBounds.Width - 2;
var h = e.CellBounds.Height - 2;
var x = e.CellBounds.Left + (e.CellBounds.Width - w) / 2;
var y = e.CellBounds.Top + (e.CellBounds.Height - h) / 2;
e.Graphics.DrawImage(img, new Rectangle(x, y, w, h));
e.Handled = true;
}
if (e.ColumnIndex == 10)
{
e.Paint(e.CellBounds, DataGridViewPaintParts.All);
var img = Properties.Resources.edit;
var w = e.CellBounds.Width - 2;
var h = e.CellBounds.Height - 2;
var x = e.CellBounds.Left + (e.CellBounds.Width - w) / 2;
var y = e.CellBounds.Top + (e.CellBounds.Height - h) / 2;
e.Graphics.DrawImage(img, new Rectangle(x, y, w, h));
e.Handled = true;
}
if (e.ColumnIndex == 11)
{
e.Paint(e.CellBounds, DataGridViewPaintParts.All);
var img = Properties.Resources.delete;
var w = e.CellBounds.Width - 2;
var h = e.CellBounds.Height - 2;
var x = e.CellBounds.Left + (e.CellBounds.Width - w) / 2;
var y = e.CellBounds.Top + (e.CellBounds.Height - h) / 2;
e.Graphics.DrawImage(img, new Rectangle(x, y, w, h));
e.Handled = true;
}
}
private void HanhKhachGridView_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex == -1) return;
var grid = (DataGridView)sender;
var name = grid.Columns[e.ColumnIndex].Name;
var value = grid.Rows[e.RowIndex].Cells["tabHanhKhach_IDCol"].Value.ToString();
switch (name)
{
case "tabHanhKhach_ViewCol":
{
HanhKhach_Form form = _serviceProvider.GetRequiredService<HanhKhach_Form>();
form.editState = EditState.View;
form.setId(int.Parse(value));
var main = this.Location;
form.Location = new Point((main.X + 10), (main.Y + 10));
form.Show();
break;
}
case "tabHanhKhach_EditCol":
{
HanhKhach_Form form = _serviceProvider.GetRequiredService<HanhKhach_Form>();
form.editState = EditState.Edit;
form.setId(int.Parse(value));
var main = this.Location;
form.Location = new Point((main.X + 10), (main.Y + 10));
form.Show();
break;
}
case "tabHanhKhach_DeleteCol":
{
var khach = _hanhkhachRepo.getById(int.Parse(value));
var messageResult = MessageBox.Show("Bạn có chắc muốn xóa " + khach.Ten, "Warning", MessageBoxButtons.YesNo);
if (messageResult != DialogResult.Yes) return;
_hanhkhachRepo.Delete(khach);
tabHanhKhach_Search();
break;
}
}
}
private void HanhKhachGridView_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex == -1) return;
var grid = (DataGridView)sender;
var name = grid.Columns[e.ColumnIndex].Name;
if (name == "tabHanhKhach_EditCol" || name == "tabHanhKhach_ViewCol" || name == "tabHanhKhach_DeleteCol") return;
var value = grid.Rows[e.RowIndex].Cells["tabHanhKhach_IDCol"].Value.ToString();
HanhKhach_Form form = _serviceProvider.GetRequiredService<HanhKhach_Form>();
form.editState = EditState.View;
form.setId(int.Parse(value));
var main = this.Location;
form.Location = new Point((main.X + 10), (main.Y + 10));
form.Show();
}
#endregion
#region Địa điểm
private void tabDD_Search()
{
string ID_str, Ten_str;
ID_str = Ten_str = "";
switch(tabDD_SearchOption.SelectedIndex)
{
case 0:
ID_str = tabDD_SearchBox.Text;
break;
case 1:
Ten_str = tabDD_SearchBox.Text;
break;
}
DiaDiemGridView.Rows.Clear();
var data = _diadiemRepo.getWhere(ID_str,Ten_str);
foreach (DiaDiem item in data)
{
DiaDiemGridView.Rows.Add(item.DDId, item.TenDD);
}
}
private void tabDD_SearchBtn_Click(object sender, EventArgs e)
{
tabDD_Search();
}
private void tabDD_SearchBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter) tabDD_Search();
}
private void tabDD_RefreshBtn_Click(object sender, EventArgs e)
{
TabRefresh(ListTab.Diadiem);
}
private void tabDD_AddBtn_Click(object sender, EventArgs e)
{
ThemDiadiem form = _serviceProvider.GetRequiredService<ThemDiadiem>();
form.editState = EditState.Create;
var main = this.Location;
form.Location = new Point((main.X + 10), (main.Y + 10));
form.Show();
}
private void DiaDiemGridView_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
if (e.RowIndex < 0)
return;
//I supposed your button column is at index 0
if (e.ColumnIndex == 3)
{
e.Paint(e.CellBounds, DataGridViewPaintParts.All);
var img = Properties.Resources.view;
var w = e.CellBounds.Width - 2;
var h = e.CellBounds.Height - 2;
var x = e.CellBounds.Left + (e.CellBounds.Width - w) / 2;
var y = e.CellBounds.Top + (e.CellBounds.Height - h) / 2;
e.Graphics.DrawImage(img, new Rectangle(x, y, w, h));
e.Handled = true;
}
if (e.ColumnIndex == 4)
{
e.Paint(e.CellBounds, DataGridViewPaintParts.All);
var img = Properties.Resources.edit;
var w = e.CellBounds.Width - 2;
var h = e.CellBounds.Height - 2;
var x = e.CellBounds.Left + (e.CellBounds.Width - w) / 2;
var y = e.CellBounds.Top + (e.CellBounds.Height - h) / 2;
e.Graphics.DrawImage(img, new Rectangle(x, y, w, h));
e.Handled = true;
}
if (e.ColumnIndex == 5)
{
e.Paint(e.CellBounds, DataGridViewPaintParts.All);
var img = Properties.Resources.delete;
var w = e.CellBounds.Width - 2;
var h = e.CellBounds.Height - 2;
var x = e.CellBounds.Left + (e.CellBounds.Width - w) / 2;
var y = e.CellBounds.Top + (e.CellBounds.Height - h) / 2;
e.Graphics.DrawImage(img, new Rectangle(x, y, w, h));
e.Handled = true;
}
}
private void DiaDiemGridView_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex == -1) return;
var grid = (DataGridView)sender;
var name = grid.Columns[e.ColumnIndex].Name;
var value = grid.Rows[e.RowIndex].Cells["tabDD_IDCol"].Value.ToString();
switch (name)
{
case "tabDD_ViewCol":
{
ThemDiadiem form = _serviceProvider.GetRequiredService<ThemDiadiem>();
form.editState = EditState.View;
form.setId(int.Parse(value));
var main = this.Location;
form.Location = new Point((main.X + 10), (main.Y + 10));
form.Show();
break;
}
case "tabDD_EditCol":
{
ThemDiadiem form = _serviceProvider.GetRequiredService<ThemDiadiem>();
form.editState = EditState.Edit;
form.setId(int.Parse(value));
var main = this.Location;
form.Location = new Point((main.X + 10), (main.Y + 10));
form.Show();
break;
}
case "tabDD_DeleteCol":
{
var item = _diadiemRepo.getById(int.Parse(value));
var messageResult = MessageBox.Show("Bạn có chắc muốn xóa " + item.TenDD, "Warning", MessageBoxButtons.YesNo);
if (messageResult != DialogResult.Yes) return;
_diadiemRepo.Delete(item);
tabDD_Search();
break;
}
}
}
private void DiaDiemGridView_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex == -1) return;
var grid = (DataGridView)sender;
var name = grid.Columns[e.ColumnIndex].Name;
if (name == "tabDD_EditCol" || name == "tabDD_ViewCol" || name == "tabDD_DeleteCol") return;
var value = grid.Rows[e.RowIndex].Cells["tabDD_IDCol"].Value.ToString();
ThemDiadiem form = _serviceProvider.GetRequiredService<ThemDiadiem>();
form.editState = EditState.View;
form.setId(int.Parse(value));
var main = this.Location;
form.Location = new Point((main.X + 10), (main.Y + 10));
form.Show();
}
#endregion
#region Loại hình du lịch
private void tabLHDL_Search()
{
string ID_str, Ten_str, Mota_str;
ID_str = Ten_str = Mota_str ="";
switch (tabLHDL_SearchOption.SelectedIndex)
{
case 0:
ID_str = tabLHDL_SearchBox.Text;
break;
case 1:
Ten_str = tabLHDL_SearchBox.Text;
break;
case 2:
Mota_str = tabLHDL_SearchBox.Text;
break;
}
LHDLGridView.Rows.Clear();
var data = _lhdlRepo.getWhere(ID_str, Ten_str,Mota_str);
foreach (LoaiHinhDL item in data)
{
LHDLGridView.Rows.Add(item.LHDLId, item.Ten,item.moTa);
}
}
private void tabLHDL_SearchBtn_Click(object sender, EventArgs e)
{
tabLHDL_Search();
}
private void tabLHDL_SearchBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter) tabLHDL_Search();
}
private void tabLHDL_RefreshBtn_Click(object sender, EventArgs e)
{
TabRefresh(ListTab.LoaiHinhDuLich);
}
private void tabLHDL_AddBtn_Click(object sender, EventArgs e)
{
ThemLHDuLich form = _serviceProvider.GetRequiredService<ThemLHDuLich>();
form.editState = EditState.Create;
var main = this.Location;
form.Location = new Point((main.X + 10), (main.Y + 10));
form.Show();
}
private void LHDLGridView_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
if (e.RowIndex < 0)
return;
//I supposed your button column is at index 0
if (e.ColumnIndex == 4)
{
e.Paint(e.CellBounds, DataGridViewPaintParts.All);
var img = Properties.Resources.view;
var w = e.CellBounds.Width - 2;
var h = e.CellBounds.Height - 2;
var x = e.CellBounds.Left + (e.CellBounds.Width - w) / 2;
var y = e.CellBounds.Top + (e.CellBounds.Height - h) / 2;
e.Graphics.DrawImage(img, new Rectangle(x, y, w, h));
e.Handled = true;
}
if (e.ColumnIndex == 5)
{
e.Paint(e.CellBounds, DataGridViewPaintParts.All);
var img = Properties.Resources.edit;
var w = e.CellBounds.Width - 2;
var h = e.CellBounds.Height - 2;
var x = e.CellBounds.Left + (e.CellBounds.Width - w) / 2;
var y = e.CellBounds.Top + (e.CellBounds.Height - h) / 2;
e.Graphics.DrawImage(img, new Rectangle(x, y, w, h));
e.Handled = true;
}
if (e.ColumnIndex == 6)
{
e.Paint(e.CellBounds, DataGridViewPaintParts.All);
var img = Properties.Resources.delete;
var w = e.CellBounds.Width - 2;
var h = e.CellBounds.Height - 2;
var x = e.CellBounds.Left + (e.CellBounds.Width - w) / 2;
var y = e.CellBounds.Top + (e.CellBounds.Height - h) / 2;
e.Graphics.DrawImage(img, new Rectangle(x, y, w, h));
e.Handled = true;
}
}
private void LHDLGridView_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex == -1) return;
var grid = (DataGridView)sender;
var name = grid.Columns[e.ColumnIndex].Name;
var value = grid.Rows[e.RowIndex].Cells["tabLHDL_IDCol"].Value.ToString();
switch (name)
{
case "tabLHDL_ViewCol":
{
ThemLHDuLich form = _serviceProvider.GetRequiredService<ThemLHDuLich>();
form.editState = EditState.View;
form.setId(int.Parse(value));
var main = this.Location;
form.Location = new Point((main.X + 10), (main.Y + 10));
form.Show();
break;
}
case "tabLHDL_EditCol":
{
ThemLHDuLich form = _serviceProvider.GetRequiredService<ThemLHDuLich>();
form.editState = EditState.Edit;
form.setId(int.Parse(value));
var main = this.Location;
form.Location = new Point((main.X + 10), (main.Y + 10));
form.Show();
break;
}
case "tabLHDL_DeleteCol":
{
var item = _lhdlRepo.getById(int.Parse(value));
var messageResult = MessageBox.Show("Bạn có chắc muốn xóa " + item.Ten, "Warning", MessageBoxButtons.YesNo);
if (messageResult != DialogResult.Yes) return;
_lhdlRepo.Delete(item);
tabLHDL_Search();
break;
}
}
}
private void LHDLGridView_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex == -1) return;
var grid = (DataGridView)sender;
var name = grid.Columns[e.ColumnIndex].Name;
if (name == "tabLHDL_EditCol" || name == "tabLHDL_ViewCol" || name == "tabLHDL_DeleteCol") return;
var value = grid.Rows[e.RowIndex].Cells["tabLHDL_IDCol"].Value.ToString();
ThemLHDuLich form = _serviceProvider.GetRequiredService<ThemLHDuLich>();
form.editState = EditState.View;
form.setId(int.Parse(value));
var main = this.Location;
form.Location = new Point((main.X + 10), (main.Y + 10));
form.Show();
}
#endregion
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text;
namespace TourApp.Entity
{
public class ChiTieu
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public int CTId { set; get; }
public String Ten { set; get; }
public ICollection<CTChitieu> CTChitieus { set; get; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text;
namespace TourApp.Entity
{
public class NhanVien
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public int NVId { set; get; }
public String MaNV { set; get; }
public String Ten { set; get; }
public String SDT { set; get; }
public int isDeleted { set; get; }
public ICollection<NV_VT> NV_VTs { set; get; }
}
}
<file_sep>using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TourApp.Const;
using TourApp.Context;
using TourApp.Entity;
using TourApp.Repository.IRepository;
namespace TourApp.Repository
{
public class NhanVienRepository : INhanVienRepository
{
private TourContext _context;
public NhanVienRepository(TourContext context)
{
_context = context;
}
public void Add(NhanVien entity)
{
_context.NhanViens.Add(entity);
_context.SaveChanges();
}
public void Delete(NhanVien entity)
{
entity.isDeleted = Status.Deleted;
_context.NhanViens.Update(entity);
_context.SaveChanges();
}
public IEnumerable<NhanVien> getAll()
{
return _context.NhanViens.Where(t => t.isDeleted == Status.NotDeleted).Include(nv => nv.NV_VTs) .ThenInclude(d => d.DoanKhach).ToList();
}
public IEnumerable<NhanVien> getAllDelete()
{
return _context.NhanViens.Include(nv => nv.NV_VTs).ThenInclude(d => d.DoanKhach).ToList();
}
public NhanVien getById(int NVId = 1, string MaNV = "abc")
{
return _context.NhanViens.Where(t => t.NVId == NVId || t.MaNV == MaNV)
.Include(nv => nv.NV_VTs)
.ThenInclude(d => d.DoanKhach)
.FirstOrDefault();
}
public IEnumerable<NhanVien> getWhere(string ID, string MaNv, string Ten, string SDT, int isDeleted)
{
return _context.NhanViens.Where(t => t.isDeleted == isDeleted)
.Where(t => t.NVId.ToString().Contains(ID))
.Where(t => t.MaNV.Contains(MaNv))
.Where(t => t.Ten.Contains(Ten))
.Where(t => t.SDT.Contains(SDT))
.Include(nv => nv.NV_VTs)
.ThenInclude(d => d.DoanKhach)
.ToList();
}
public void Update(NhanVien entity)
{
_context.NhanViens.Update(entity);
_context.SaveChanges();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;
namespace TourApp.Entity
{
public class CTTour
{
public int TourId { set; get; }
public Tour Tour { set; get; }
public int DDId { set; get; }
public DiaDiem DiaDiem { set; get; }
public String ThongTin { set; get; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace TourApp.Entity
{
public class CTChitieu
{
public int CTId { set; get; }
public virtual ChiTieu ChiTieu { set; get; }
public int DoanId { set; get; }
public virtual DoanKhach DoanKhach { set; get; }
public string TienCT { set; get; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text;
namespace TourApp.Entity
{
public class Gia
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public int GiaId { set; get; }
[Required]
public int GiaTri { set; get; }
[Required]
public DateTime TGBD { set; get; }
[Required]
public DateTime TGKT { set; get; }
[Required]
public int TourId { set; get; }
public Tour Tour { set; get; }
public ICollection<DoanKhach> DoanKhachs { set; get; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace TourApp.Entity
{
public class NV_VT
{
public int DoanId { set; get; }
public DoanKhach DoanKhach { set; get; }
public int NVId { set; get; }
public NhanVien NhanVien { set; get; }
public String ViTri { set; get; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Text;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using TourApp.Entity;
using TourApp.Repository.IRepository;
namespace TourApp
{
public partial class TKTinhHinhHoatDong : Form
{
private readonly ITourRepository _tourRepo;
public TKTinhHinhHoatDong(
ITourRepository tourRepo
)
{
_tourRepo = tourRepo;
InitializeComponent();
}
private void TKTinhHinhHoatDong_Load(object sender, EventArgs e)
{
Init();
}
private void Init()
{
var tours = _tourRepo.getAll();
foreach(Tour tour in tours)
{
string sodoan = tour.DoanKhachs.Count.ToString();
string doanhso = moneyFormat(tour.DoanKhachs.Sum(i => i.Gia.GiaTri + i.CTChitieus.Sum(ct => int.Parse(ct.TienCT))));
var item = new ListViewItem(new string[] {tour.MaTour,tour.Ten, doanhso, sodoan});
listView.Items.Add(item);
}
}
private string moneyFormat(int value)
{
CultureInfo cultureInfo = CultureInfo.GetCultureInfo("vi-VN");
return (value.ToString("#,###.##", cultureInfo).Replace(".", ",") + " VNĐ");
}
}
}
<file_sep>using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TourApp.Context;
using TourApp.Entity;
using TourApp.Repository.IRepository;
namespace TourApp.Repository
{
public class DiaDiemRepository : IDiaDiemRepository
{
private TourContext _context;
public DiaDiemRepository(TourContext context)
{
_context = context;
}
public void Add(DiaDiem entity)
{
_context.DiaDiems.Add(entity);
_context.SaveChanges();
}
public void Delete(DiaDiem entity)
{
_context.DiaDiems.Remove(entity);
_context.SaveChanges();
}
public IEnumerable<DiaDiem> getAll()
{
return _context.DiaDiems.Include(t => t.CTTours).ThenInclude(t => t.Tour).ToList();
}
public DiaDiem getById(int DDId)
{
return _context.DiaDiems.Where(dd => dd.DDId == DDId)
.Include(t => t.CTTours)
.ThenInclude(t => t.Tour)
.FirstOrDefault();
}
public IEnumerable<DiaDiem> getWhere(string ID,string Ten)
{
return _context.DiaDiems.Include(t => t.CTTours)
.ThenInclude(t => t.Tour)
.Where(dd => dd.TenDD.Contains(Ten)
&& dd.DDId.ToString().Contains(ID)
)
.ToList();
}
public void Update(DiaDiem entity)
{
_context.DiaDiems.Update(entity);
_context.SaveChanges();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using TourApp.Entity;
namespace TourApp.Repository.IRepository
{
public interface IGiaRepository : ICommonRepository<Gia>
{
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using TourApp.Entity;
using TourApp.Repository.IRepository;
namespace TourApp
{
public partial class TKChiPhi_Form : Form
{
private enum pageOption
{
Tour,
Chitieu
}
private pageOption current;
private readonly ITourRepository _tourRepo;
private readonly IChiTieuRepository _chitieuRepo;
private CultureInfo cultureInfo = CultureInfo.GetCultureInfo("vi-VN");
public TKChiPhi_Form(ITourRepository tourRepo,
IChiTieuRepository chitieuRepo
)
{
_tourRepo = tourRepo;
_chitieuRepo = chitieuRepo;
InitializeComponent();
}
private void TKChiPhi_Form_Load(object sender, EventArgs e)
{
Init();
}
private void Init()
{
tourRadioBtn.Tag = pageOption.Tour;
ChitieuRadioBtn.Tag = pageOption.Chitieu;
fromDate.Value = fromDate.MinDate;
toDate.Value = toDate.MaxDate;
ChangePageOption(pageOption.Tour);
}
private void ChangePageOption(pageOption option)
{
current = option;
switch (option)
{
case pageOption.Tour:
{
SelectLabel.Text = "Chọn Tour";
var list = _tourRepo.getAll();
selectCbb.DataSource = list;
selectCbb.DisplayMember = "Ten";
selectCbb.ValueMember = "TourId";
break;
}
case pageOption.Chitieu:
{
SelectLabel.Text = "Chọn loại chi tiêu";
var list = _chitieuRepo.getAll();
selectCbb.DataSource = list;
selectCbb.DisplayMember = "Ten";
selectCbb.ValueMember = "CTId";
break;
}
}
}
private void selectCbb_Format(object sender, ListControlConvertEventArgs e)
{
switch (current)
{
case pageOption.Tour:
{
var item = (Tour)e.ListItem;
e.Value = item.MaTour + " - " + item.Ten;
break;
}
case pageOption.Chitieu:
{
var item = (ChiTieu)e.ListItem;
e.Value = item.Ten;
break;
}
}
}
private void radioButton_CheckedChanged(object sender, EventArgs e)
{
var radioBtn = groupRadio.Controls.OfType<RadioButton>().FirstOrDefault(i => i.Checked);
ChangePageOption((pageOption)radioBtn.Tag);
}
private void clearListView(ListView lv)
{
while (lv.Items.Count > 0)
lv.Items.RemoveAt(0);
}
private string moneyFormat(int value)
{
return (value.ToString("#,###.##", cultureInfo).Replace(".", ",")+" VNĐ");
}
private string dateTimeFormat(DateTime date)
{
return date.Date.ToString("dd/MM/yyyy");
}
private void thongkeBtn_Click(object sender, EventArgs e)
{
if (selectCbb.SelectedValue == null) return;
clearListView(listView);
switch (current)
{
case pageOption.Tour:
ThongKeTour();
break;
case pageOption.Chitieu:
ThongKeChiTieu();
break;
}
}
private void ThongKeTour()
{
var tour = _tourRepo.getById((int)selectCbb.SelectedValue);
var doans = tour.DoanKhachs.Where(i => DateTime.Compare(i.DateCreated, fromDate.Value) >= 0
&& DateTime.Compare(i.DateCreated, toDate.Value) <= 0);
int total = 0;
foreach (DoanKhach doan in doans)
{
ListViewGroup group = new ListViewGroup();
group.Header = doan.MaDoan + " - " + doan.TenDoan
+ " (" + dateTimeFormat(doan.DateStart) + " - " + dateTimeFormat(doan.DateEnd) + ")";
listView.Groups.Add(group);
//giá tour
//ListViewItem item = new ListViewItem
//{
// Text = "Giá tour",
// Group = group,
// ForeColor = Color.DarkGreen
//};
//item.SubItems.Add(moneyFormat(doan.Gia.GiaTri));
//listView.Items.Add(item);
ListViewItem item;
int itemTotal = 0;
foreach (CTChitieu ctchitieu in doan.CTChitieus)
{
item = new ListViewItem
{
Text = ctchitieu.ChiTieu.Ten,
Group = group
};
var tienCT = int.Parse(ctchitieu.TienCT);
item.SubItems.Add(moneyFormat(tienCT));
listView.Items.Add(item);
itemTotal += tienCT;
}
item = new ListViewItem
{
Text = "Tổng cộng",
Group = group,
Font = new Font(listView.Font, FontStyle.Bold)
};
item.Position = new Point(item.Position.X, item.Position.Y + 5);
item.SubItems.Add(moneyFormat(itemTotal));
listView.Items.Add(item);
total += itemTotal;
}
ListViewGroup groupTotal = new ListViewGroup();
groupTotal.Header = "";
listView.Groups.Insert(0, groupTotal);
var totalFinal = new ListViewItem
{
Text = "Tổng cộng",
Group = groupTotal,
Font = new Font(listView.Font, FontStyle.Bold)
};
totalFinal.SubItems.Add(moneyFormat(total));
listView.Items.Add(totalFinal);
}
private void ThongKeChiTieu()
{
var chitieu = _chitieuRepo.getById((int)selectCbb.SelectedValue);
var ctchitieus = chitieu.CTChitieus.Where(i => DateTime.Compare(i.DoanKhach.DateCreated, fromDate.Value) >= 0
&& DateTime.Compare(i.DoanKhach.DateCreated, toDate.Value) <= 0);
ListViewGroup group = new ListViewGroup();
group.Header = chitieu.Ten;
listView.Groups.Add(group);
int itemTotal = 0;
foreach (CTChitieu ctchitieu in ctchitieus)
{
var doan = ctchitieu.DoanKhach;
var item = new ListViewItem
{
Text = "Ngày tạo: " + dateTimeFormat(doan.DateCreated),
Group = group,
ForeColor = Color.DarkGreen
};
listView.Items.Add(item);
item = new ListViewItem
{
Text = " (" + dateTimeFormat(doan.DateStart) + " - " + dateTimeFormat(doan.DateEnd) + ")",
Group = group,
ForeColor = Color.DarkGray
};
listView.Items.Add(item);
item = new ListViewItem
{
Text = doan.MaDoan + " - " + doan.TenDoan,
Group = group
};
var tienCT = int.Parse(ctchitieu.TienCT);
item.SubItems.Add(moneyFormat(tienCT));
listView.Items.Add(item);
itemTotal += tienCT;
}
ListViewGroup groupTotal = new ListViewGroup();
groupTotal.Header = "";
listView.Groups.Insert(0,groupTotal);
var total = new ListViewItem
{
Text = "Tổng cộng",
Font = new Font(listView.Font, FontStyle.Bold),
Group = groupTotal
};
total.SubItems.Add(moneyFormat(itemTotal));
listView.Items.Add(total);
}
}
}
<file_sep>using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Text;
namespace TourApp.Const
{
public static class Status
{
public const int Deleted = 1;
public const int NotDeleted = 0;
}
}
<file_sep>using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TourApp.Const;
using TourApp.Context;
using TourApp.Entity;
using TourApp.Repository.IRepository;
namespace TourApp.Repository
{
public class TourRepository : ITourRepository
{
private TourContext _context;
public TourRepository(TourContext context)
{
_context = context;
}
public void Add(Tour entity)
{
_context.Tours.Add(entity);
_context.SaveChanges();
}
public void Delete(Tour entity)
{
entity.isDeleted = Status.Deleted;
_context.Tours.Update(entity);
_context.SaveChanges();
}
public IEnumerable<Tour> getAll()
{
return _context.Tours.Where(t => t.isDeleted == Status.NotDeleted)
.Include(t => t.Gias).Include(t => t.LHDL).Include(t => t.CTTours).ThenInclude(dd => dd.DiaDiem)
.Include(t => t.DoanKhachs)
.ThenInclude(dk => dk.CTChitieus)
.ThenInclude(ct => ct.ChiTieu)
.Include(t => t.DoanKhachs)
.ThenInclude(dk => dk.CTDoans)
.ToList();
}
public IEnumerable<Tour> getAllDelete()
{
return _context.Tours.Include(t => t.Gias).Include(t => t.LHDL).Include(t => t.CTTours).ThenInclude(dd => dd.DiaDiem).ToList();
}
public Tour getById(int TourId = 1, string MaTour = "abc")
{
return _context.Tours.Where(t => t.TourId == TourId || t.MaTour == MaTour)
.Include(t => t.LHDL)
.Include(t => t.Gias)
.Include(t => t.CTTours)
.ThenInclude(dd => dd.DiaDiem)
.Include(t => t.DoanKhachs)
.ThenInclude(dk => dk.CTChitieus)
.ThenInclude(ct => ct.ChiTieu)
.Include(t => t.DoanKhachs)
.ThenInclude(dk => dk.CTDoans)
.FirstOrDefault();
}
public IEnumerable<Tour> getWhere(string Ten,string LHDL, string ID, string MaTour,DateTime fromDate, DateTime toDate , int fromPrice, int toPrice, int isDeleted)
{
var result = _context.Tours.Include(t => t.Gias)
.Include(t => t.LHDL)
.Include(t => t.CTTours)
.ThenInclude(dd => dd.DiaDiem)
.Include(t => t.DoanKhachs)
.ThenInclude(dk => dk.CTChitieus)
.ThenInclude(ct => ct.ChiTieu)
.Include(t => t.DoanKhachs)
.ThenInclude(dk => dk.CTDoans)
.Where(t => t.Ten.Contains(Ten))
.Where(t => t.LHDL.Ten.Contains(LHDL))
.Where(t => t.MaTour.Contains(MaTour))
.Where(t => t.TourId.ToString().Contains(ID))
.Where(t => t.Gias.Where(i => (
DateTime.Compare(i.TGBD, fromDate) >= 0
&& DateTime.Compare(i.TGKT, toDate) <= 0
&& i.GiaTri >= fromPrice
&& i.GiaTri <= toPrice
))
.Count() > 0)
.Where(t => t.isDeleted == isDeleted)
.ToList();
return result;
}
public Tour getByName(string Ten, int isDeleted)
{
var result = _context.Tours.Include(t => t.Gias)
.Include(t => t.LHDL)
.Include(t => t.CTTours)
.ThenInclude(dd => dd.DiaDiem)
.Include(t => t.DoanKhachs)
.ThenInclude(dk => dk.CTChitieus)
.ThenInclude(ct => ct.ChiTieu)
.Include(t => t.DoanKhachs)
.ThenInclude(dk => dk.CTDoans)
.Where(t => t.Ten == Ten)
.Where(t => t.isDeleted == isDeleted)
.FirstOrDefault();
return result;
}
public void Update(Tour entity)
{
_context.Tours.Update(entity);
_context.SaveChanges();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Text;
namespace TourApp.Entity
{
public class DoanKhach
{
public DoanKhach()
{
this.CTDoans = new List<CTDoan>();
}
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public int DoanId { set; get; }
public String MaDoan { set; get; }
public String TenDoan { set; get; }
[AllowNull]
public String Chitiet { set; get; }
public String Status { set; get; }
public DateTime DateStart { set; get; }
public DateTime DateEnd { set; get; }
public int GiaId { set; get; }
public Gia Gia { set;get; }
public int? TourId { set; get; }
public Tour Tour { set; get; }
public int isDeleted { set; get; }
public DateTime DateCreated { set; get; }
public ICollection<CTDoan> CTDoans { set; get; }
public ICollection<NV_VT> NV_VTs { set; get; }
public ICollection<CTChitieu> CTChitieus { set; get; }
}
}
<file_sep>using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using TourApp.Const;
using TourApp.Entity;
using TourApp.Repository.IRepository;
namespace TourApp
{
public partial class SuaTour : Form
{
private readonly ITourRepository _tourRepository;
private readonly IDiaDiemRepository _diadiemRepository;
private readonly IServiceProvider _serviceProvider;
private readonly ILoaiHinhDuLichRepository _lhdlRepo;
private Tour Tour;
private int _id;
public SuaTour(ITourRepository tourRepository, IDiaDiemRepository diaDiemRepository, IServiceProvider serviceProvider, ILoaiHinhDuLichRepository lhdlRepo)
{
_tourRepository = tourRepository;
_diadiemRepository = diaDiemRepository;
_serviceProvider = serviceProvider;
_lhdlRepo = lhdlRepo;
InitializeComponent();
}
public void getId(int id)
{
_id = id;
}
private void showThongtin()
{
IEnumerable<DiaDiem> listdd = _diadiemRepository.getAll();
/*Dia Diem Tour*/
foreach (var DD in listdd)
{
ListViewItem diaDiem = new ListViewItem(new[] { DD.DDId.ToString(), DD.TenDD });
diadiemlist.Items.Add(diaDiem);
}
/* Loại hình */
var lhdl_list = _lhdlRepo.getAll();
loaicbb.DataSource = lhdl_list;
loaicbb.DisplayMember = "Ten";
loaicbb.ValueMember = "LHDLId";
Tour = _tourRepository.getById(_id, "");
/*Thong tin Tour*/
matourtb.Text = Tour.MaTour;
tentourtb.Text = Tour.Ten;
foreach (LoaiHinhDL loai in loaicbb.Items)
{
if (loai.LHDLId == Tour.LHDL.LHDLId)
{
loaicbb.SelectedItem = loai;
}
}
/*Dia Diem Tour*/
foreach (var DD in Tour.CTTours)
{
ListViewItem diaDiem = new ListViewItem(new[] { DD.DiaDiem.DDId.ToString(), DD.DiaDiem.TenDD });
foreach (ListViewItem dd in diadiemlist.Items)
{
if (dd.Text == diaDiem.Text)
{
dd.Checked = true;
}
}
}
/*Gia Tour*/
var info = System.Globalization.CultureInfo.GetCultureInfo("vi-VN");
foreach (var Gia in Tour.Gias)
{
var giaTien = String.Format(info, "{0:n}", Gia.GiaTri.ToString());
ListViewItem gia = new ListViewItem(new[] { giaTien, Gia.TGBD.ToString("dd/MM/yyyy HH:mm:ss"), Gia.TGKT.ToString("dd/MM/yyyy HH:mm:ss") });
gialist.Items.Insert(0,gia);
}
gialist.Items[0].ForeColor = Color.DarkGreen;
}
public void RefreshGia()
{
gialist.Items.Clear();
Tour = _tourRepository.getById(_id, "");
var info = System.Globalization.CultureInfo.GetCultureInfo("vi-VN");
foreach (var Gia in Tour.Gias)
{
var giaTien = String.Format(info, "{0:n}", Gia.GiaTri.ToString());
ListViewItem gia = new ListViewItem(new[] { giaTien, Gia.TGBD.ToString("dd/MM/yyyy HH:mm:ss"), Gia.TGKT.ToString("dd/MM/yyyy HH:mm:ss") });
gialist.Items.Add(gia);
}
}
protected override void OnLoad(EventArgs e)
{
showThongtin();
}
private bool check()
{
if (matourtb.Text == null)
return false;
if (tentourtb.Text == null)
return false;
if (diadiemlist.CheckedItems == null)
return false;
return true;
}
private void button2_Click(object sender, EventArgs e)
{
if (!check())
{
MessageBox.Show("Thông tin thiếu hoặc không hợp lệ !");
}
else
{
Tour = _tourRepository.getById(_id, "");
Tour.MaTour = matourtb.Text;
Tour.Ten = tentourtb.Text;
LoaiHinhDL item = new LoaiHinhDL();
item = (LoaiHinhDL)loaicbb.SelectedItem;
Tour.LHDLId = item.LHDLId;
Tour.CTTours.Clear();
foreach (ListViewItem dd in diadiemlist.CheckedItems)
{
CTTour newcttour = new CTTour();
newcttour.DDId = Convert.ToInt32(dd.SubItems[0].Text);
newcttour.TourId = Tour.TourId;
//_cTTourRepository.Add(newcttour);
Tour.CTTours.Add(newcttour);
}
_tourRepository.Update(Tour);
MessageBox.Show("Cập nhật thành công!");
Program.Form.TabRefresh(ListTab.Tour);
}
}
private void button1_Click(object sender, EventArgs e)
{
ThemGia form = _serviceProvider.GetRequiredService<ThemGia>();
form.getId(_id);
var main = this.Location;
form.Location = new Point((main.X + 10), (main.Y + 10));
form.ShowDialog();
this.RefreshGia();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text;
namespace TourApp.Entity
{
public class LoaiHinhDL
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public int LHDLId { set; get; }
[Required]
public String Ten { set; get; }
public String moTa { set; get; }
public ICollection<Tour> Tours { set; get; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using TourApp.Entity;
using TourApp.Repository.IRepository;
using TourApp.Const;
using System.CodeDom;
using DocumentFormat.OpenXml.Office2010.PowerPoint;
using DocumentFormat.OpenXml.Wordprocessing;
using System.Text.RegularExpressions;
namespace TourApp
{
// Trong Form này có 2 cái listview để hiển thị ( dùng cái nào thì ẩn cái còn lại )
// lv_search là listview với checkbox là chọn được nhiều cái
// lv_radio là listview với checkbox mỗi lần chỉ chọn 1 cái
//lbl là lbl của txt_option
//txt_option là các value cần thêm nếu có không thì mặc định là visible = false
public partial class SearchForm : Form
{
private string txt_search;
private string Form_Search;
private readonly IHanhKhachRepository _hkRepo;
private readonly IChiTieuRepository _ctRepo;
private readonly INhanVienRepository _nvRepo;
public List<HanhKhach> listHKRT;
public List<String> listCTRT;
public List<String> listNVRT;
public SearchForm(IHanhKhachRepository hkRepo, IChiTieuRepository ctRepo, INhanVienRepository nvRepo)
{
InitializeComponent();
_hkRepo = hkRepo;
_ctRepo = ctRepo;
_nvRepo = nvRepo;
}
public void setForm(string FSearch)
{
Form_Search = FSearch;
}
private void label1_Click(object sender, EventArgs e)
{
}
public void init()
{
lv_radio.Location = new Point(12, 16);
lv_radio.Size = new Size(300,260);
var id = lv_radio.Columns.Add("ID");
id.Text = "ID";
var maso = lv_radio.Columns.Add("Maso");
maso.Text = "Mã Số";
maso.Width = 70;
var ten = lv_radio.Columns.Add("Ten");
ten.Text = "Tên";
ten.Width = 110;
switch (Form_Search)
{
case FormName.NVFORMNAME:
title.Text = "CHỌN NHÂN VIÊN";
lv_radio.Visible = true;
lv_search.Visible = false;
lbl.Text = "Vị trí";
lbl.Visible = true;
txt_option.Visible = true;
break;
case FormName.HKFORMNAME:
title.Text = "CHỌN HÀNH KHÁCH";
lv_search.Visible = true;
lv_radio.Visible = false;
break;
case FormName.CTFORMNAME:
title.Text = "CHỌN CHI TIÊU";
lv_radio.Visible = true;
lbl.Text = "Giá";
lbl.Visible = true;
txt_option.Visible = true;
lv_search.Visible = false;
lv_radio.Columns.RemoveAt(1);
break;
}
Search();
}
private bool validate()
{
if(Form_Search == FormName.CTFORMNAME)
{
if (Regex.IsMatch(txt_option.Text, "^[0-9]{1,}$") == false)
{
errorlbl.Text = "Xin nhập số và không để trống";
errorlbl.Visible = true;
return false;
}
else errorlbl.Visible = false;
}
if (Form_Search == FormName.NVFORMNAME)
{
if (txt_option.Text == "")
{
errorlbl.Text = "Xin nhập vị trí của nhân viên";
errorlbl.Visible = true;
return false;
}
else errorlbl.Visible = false;
}
return true;
}
private void SearchForm_Load(object sender, EventArgs e)
{
init();
}
private void btn_search_Click(object sender, EventArgs e)
{
Search();
}
private void Search()
{
lv_search.Items.Clear();
lv_radio.Items.Clear();
txt_search = text_search.Text;
switch (Form_Search)
{
case "NhanVien_Form":
IEnumerable<NhanVien> list3 = _nvRepo.getWhere("", "", txt_search, "", 0);
foreach (NhanVien nv in list3)
{
ListViewItem newList = new ListViewItem(new[] { nv.NVId.ToString(), nv.MaNV, nv.Ten });
lv_radio.Items.Add(newList);
}
break;
case "HanhKhach_Form":
IEnumerable<HanhKhach> list1 = _hkRepo.getWhere("", "", txt_search, "", "", "", "", "", "", 0);
foreach (HanhKhach hk in list1)
{
ListViewItem newList = new ListViewItem(new[] { hk.KhachId.ToString(), hk.MaKhach, hk.Ten });
lv_search.Items.Add(newList);
}
break;
case "ChiTieu_Form":
IEnumerable<ChiTieu> list2 = _ctRepo.getWhere("", txt_search);
foreach (ChiTieu ct in list2)
{
ListViewItem newList = new ListViewItem(new[] { ct.CTId.ToString(), ct.Ten });
lv_radio.Items.Add(newList);
}
break;
}
}
private void btn_select_Click(object sender, EventArgs e)
{
if(!validate())
{
return;
}
switch (Form_Search)
{
case "NhanVien_Form":
listNVRT = listNV();
break;
case "HanhKhach_Form":
listHKRT = listHK();
break;
case "ChiTieu_Form":
listCTRT = listCT();
break;
}
Close();
}
private List<HanhKhach> listHK()
{
List<HanhKhach> listRT = new List<HanhKhach>();
for (int i = 0; i < lv_search.Items.Count; i++)
{
if (lv_search.Items[i].Checked == true)
{
HanhKhach hk = _hkRepo.getById(int.Parse(lv_search.Items[i].Text));
listRT.Add(hk);
}
}
return listRT;
}
private List<String> listCT()
{
List<String> listRT = new List<String>();
var count = 0;
for (int i = 0; i < lv_radio.Items.Count; i++)
{
if (lv_radio.Items[i].Checked == true)
{
count++;
ChiTieu ct = _ctRepo.getById(int.Parse(lv_radio.Items[i].Text));
listRT.Add(ct.Ten);
listRT.Add(txt_option.Text);
}
}
if (count <= 0)
{
listRT.Clear();
}
return listRT;
}
private List<String> listNV()
{
List<String> listRT = new List<String>();
var count = 0;
for (int i = 0; i < lv_radio.Items.Count; i++)
{
if (lv_radio.Items[i].Checked == true)
{
count++;
NhanVien nv = _nvRepo.getById(int.Parse(lv_radio.Items[i].Text));
listRT.Add(nv.MaNV);
listRT.Add(nv.Ten);
listRT.Add(txt_option.Text);
}
}
if (count <= 0)
{
listRT.Clear();
}
return listRT;
}
private void lv_radio_ItemCheck(object sender, ItemCheckEventArgs e)
{
var listView = sender as ListView;
if(listView != null && e.NewValue == CheckState.Checked)
{
foreach (ListViewItem checkedItem in listView.CheckedItems)
{
checkedItem.Checked = false;
}
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
using TourApp.Const;
using TourApp.Entity;
namespace TourApp.Repository.IRepository
{
public interface INhanVienRepository : ICommonRepository<NhanVien>
{
IEnumerable<NhanVien> getWhere(string ID, string MaNv, string Ten, string SDT, int isDeleted);
IEnumerable<NhanVien> getAllDelete();
NhanVien getById(int NVId, String MaNV = "");
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace TourApp.Const
{
public enum ListTab
{
Tour,
Nhanvien,
Diadiem,
Doan,
Chitieu,
HanhKhach,
LoaiHinhDuLich
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using TourApp.Entity;
using TourApp.Repository.IRepository;
namespace TourApp
{
public partial class ThemGia : Form
{
private readonly ITourRepository _tourRepository;
private Tour Tour;
private int _id;
public ThemGia(ITourRepository tourRepository)
{
_tourRepository = tourRepository;
InitializeComponent();
}
private bool check()
{
if (mucgia.Value <= 0)
return false;
if (tungay.Value > denngay.Value)
return false;
return true;
}
private void button1_Click(object sender, EventArgs e)
{
if (!check())
{
MessageBox.Show("Thông tin thiếu hoặc không hợp lệ !");
}
else
{
Tour = _tourRepository.getById(_id, "");
Gia newgia = new Gia();
newgia.GiaTri = (int)mucgia.Value;
newgia.TGBD = tungay.Value;
newgia.TGKT = denngay.Value;
Tour.Gias.Add(newgia);
MessageBox.Show("Thêm thành công!");
this.Close();
}
}
public void getId(int id)
{
_id = id;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using TourApp.Const;
using TourApp.Entity;
using TourApp.Repository.IRepository;
namespace TourApp
{
public partial class ThemDiadiem : Form
{
private readonly IDiaDiemRepository _diaDiemRepository;
public int _id = -1;
public EditState editState { get; set; }
public ThemDiadiem(IDiaDiemRepository diaDiemRepository)
{
_diaDiemRepository = diaDiemRepository;
InitializeComponent();
}
public void setId(int id)
{
_id = id;
}
private bool check()
{
bool error = false;
if (diadiemname.Text == "")
{
errorlabel.Text = ErrorMsg.err_blank;
errorlabel.Visible = true;
diadiemname.Focus();
error = true;
}
else
{
errorlabel.Visible = false;
}
return error;
}
private void init()
{
switch (editState)
{
case EditState.View:
{
DiaDiem dd = _diaDiemRepository.getById(_id);
diadiemname.Text = dd.TenDD;
diadiemname.Enabled = false;
savebtt.Enabled = false;
break;
}
case EditState.Edit:
{
DiaDiem dd = _diaDiemRepository.getById(_id);
diadiemname.Text = dd.TenDD;
break;
}
case EditState.Create:
{
break;
}
}
}
protected override void OnLoad(EventArgs e)
{
init();
}
private void savebtt_Click(object sender, EventArgs e)
{
if (check())
{
return;
}
if (_id != -1)
{
DiaDiem dd = _diaDiemRepository.getById(_id);
dd.TenDD = diadiemname.Text;
_diaDiemRepository.Update(dd);
MessageBox.Show("Sửa thành công địa điểm");
Program.Form.TabRefresh(ListTab.Diadiem);
}
else
{
DiaDiem dd = new DiaDiem();
dd.TenDD = diadiemname.Text;
_diaDiemRepository.Add(dd);
MessageBox.Show("Thêm thành công địa điểm");
Program.Form.TabRefresh(ListTab.Diadiem);
this.Close();
}
}
}
}
<file_sep>using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TourApp.Context;
using TourApp.Entity;
using TourApp.Repository.IRepository;
namespace TourApp.Repository
{
public class GiaRepository : IGiaRepository
{
private TourContext _context;
public GiaRepository(TourContext context)
{
_context = context;
}
public void Add(Gia gia)
{
_context.Gias.Add(gia);
_context.SaveChanges();
}
public void Delete(Gia gia)
{
_context.Gias.Remove(gia);
_context.SaveChanges();
}
public IEnumerable<Gia> getAll()
{
return _context.Gias.ToList();
}
public Gia getById(int GiaId)
{
return _context.Gias.Find(GiaId);
}
public void Update(Gia gia)
{
_context.Gias.Update(gia);
_context.SaveChanges();
}
}
}
|
34c73386b8b8f23bb15d88664f41be94da667c87
|
[
"C#"
] | 57
|
C#
|
kairyou123/BTTour
|
97c2401b85b200bd5cf9e302c3599e3a6d163e07
|
49c901e2765eefb9ee33185d7146765b84d1d8b2
|
refs/heads/master
|
<repo_name>neeraj-lad/microblog<file_sep>/flask/run.py
#!/home/student/virtualenvs/microblog/bin/python
from app import app
app.run(debug=True)
<file_sep>/README.md
# microblog
Attempt to create a microblog using <NAME>'s Flask mega [tutorial](http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world)
|
08b7ea99d156967a242c96720c7128afbbc19487
|
[
"Markdown",
"Python"
] | 2
|
Python
|
neeraj-lad/microblog
|
1fefdc67947dbbc541d2d5830d33365c3fbc88f5
|
9d76114d75c0c695e8b2e42f2041be8d63f813e1
|
refs/heads/master
|
<file_sep>var searchData=
[
['debughud',['DebugHUD',['../classIrrGame_1_1DebugHUD.html',1,'IrrGame']]]
];
<file_sep>var searchData=
[
['hud',['HUD',['../classIrrGame_1_1HUD.html#ab1955924a1a1bd1dae4a7470c1392623',1,'IrrGame::HUD']]]
];
<file_sep>/**
* @file
* @author
* @brief
*/
#include "GameTime.h"
#include <iostream>
namespace IrrGame
{
GameTime::GameTime()
{
deltaTime = 0;
elapsedTime = 0;
prevTime = 0;
}
GameTime::GameTime(ITimer* timer) : GameTime()
{
this->timer = timer;
}
GameTime::~GameTime()
{
}
void GameTime::Update()
{
u32 curTime = timer->getTime();
deltaTime = curTime - prevTime;
elapsedTime += deltaTime;
prevTime = curTime;
}
u32 GameTime::ElapsedTime() const
{
return elapsedTime;
}
u32 GameTime::DeltaTime() const
{
return deltaTime;
}
}<file_sep>var searchData=
[
['keyboardstate',['KeyboardState',['../classIrrGame_1_1KeyboardState.html',1,'IrrGame']]],
['keystate',['KeyState',['../namespaceIrrGame.html#a0cd2211b782c02b155849fc9304c4d29',1,'IrrGame']]]
];
<file_sep>var searchData=
[
['world',['World',['../classIrrGame_1_1World.html#af663c17fe7389fad19e26360f848d95c',1,'IrrGame::World']]],
['write',['Write',['../classIrrGame_1_1FileStream.html#a3b65ff555bdad7ee74c5b1c2935df1f6',1,'IrrGame::FileStream']]],
['writechar',['WriteChar',['../classIrrGame_1_1FileStream.html#aa03671834de94c26d8b1b7ad833ec089',1,'IrrGame::FileStream']]],
['writeline',['WriteLine',['../classIrrGame_1_1FileStream.html#a31e988a04b7d9c9895ef5807f27ad1eb',1,'IrrGame::FileStream']]]
];
<file_sep>var searchData=
[
['idevice',['iDevice',['../classIrrGame_1_1Game.html#acd46effafcbb197e01507cf58d25913a',1,'IrrGame::Game']]],
['iguienv',['iGUIEnv',['../classIrrGame_1_1Game.html#ab75f0fa135fd2d73618f086b5398fdf6',1,'IrrGame::Game']]],
['ivideodriver',['iVideoDriver',['../classIrrGame_1_1Game.html#a7cc7a3213707175e1998c6b45e0a3dd3',1,'IrrGame::Game']]]
];
<file_sep>var searchData=
[
['gamestate',['GameState',['../namespaceIrrGame.html#afb6a2153afcdd0094369f1354c3d6809',1,'IrrGame']]]
];
<file_sep>var searchData=
[
['game',['Game',['../classIrrGame_1_1Game.html',1,'IrrGame']]],
['gametime',['GameTime',['../classIrrGame_1_1GameTime.html',1,'IrrGame']]]
];
<file_sep>var searchData=
[
['irrgame',['IrrGame',['../namespaceIrrGame.html',1,'']]]
];
<file_sep>var searchData=
[
['close',['Close',['../classIrrGame_1_1FileStream.html#a837ae63a6ce0d26f4b3184e5ae488f99',1,'IrrGame::FileStream']]]
];
<file_sep>/**
* @file
* @author
* @brief
*/
#ifndef TIMER_H
#define TIMER_H
#include <irrlicht.h>
#include "GameTime.h"
using namespace irr;
namespace IrrGame
{
class Timer
{
public:
Timer();
Timer(GameTime* gameTime);
virtual ~Timer();
/** Start the timer. */
void Start();
/** Stop the timer. */
void Stop();
/** Returns whether or not the timer is currently running. */
bool IsRunning() const;
/** Get the milliseconds stored by the timer. */
u32 GetTime() const;
private:
GameTime* gameTime; /*!< Pointer to game time. */
u32 startTime; /*!< Time the timer was started. */
bool isRunning; /*!< Whether or not the timer is running. */
};
}
#endif // TIMER_H<file_sep>var searchData=
[
['open',['Open',['../classIrrGame_1_1FileStream.html#a4043d3f780e33f74fd39adc7c3bffd4a',1,'IrrGame::FileStream']]]
];
<file_sep>var searchData=
[
['down',['Down',['../namespaceIrrGame.html#a0cd2211b782c02b155849fc9304c4d29a08a38277b0309070706f6652eeae9a53',1,'IrrGame']]]
];
<file_sep>var searchData=
[
['tarray3d',['TArray3D',['../classIrrGame_1_1TArray3D.html',1,'IrrGame']]],
['timer',['Timer',['../classIrrGame_1_1Timer.html',1,'IrrGame']]]
];
<file_sep>/**
* @file Array3D.h
* @author <NAME>
* @brief Declares and defines a template class for managing a 3D array of objects.
* @see Array3D
*/
#ifndef ARRAY3D_H
#define ARRAY3D_H
namespace IrrGame
{
/** A template class for managing a 3D array of objects. */
template<class T>
class TArray3D
{
public:
TArray3D();
TArray3D(const u32& width, const u32& height, const u32& depth);
TArray3D(const TArray3D& param);
const TArray3D& operator=(const TArray3D& param);
T* operator()(const u32& x, const u32& y, const u32& z);
virtual ~TArray3D();
private:
u32 width, height, depth;
T*** array;
/** Allocates memory for the data. */
void Allocate();
/** Frees all data from memory. */
void Free();
/** Copies data from one array into this array. */
void Copy(const TArray3D& param);
};
template<class T>
TArray3D<T>::TArray3D()
{
this->width = 0;
this->height = 0;
this->depth = 0;
array = nullptr;
}
template<class T>
TArray3D<T>::TArray3D(const u32& width, const u32& height, const u32& depth)
{
this->width = width;
this->height = height;
this->depth = depth;
Allocate();
}
template<class T>
TArray3D<T>::TArray3D(const TArray3D& param)
{
this->width = param.width;
this->height = param.height;
this->depth = param.depth;
Allocate();
Copy(param);
}
template<class T>
const TArray3D<T>& TArray3D<T>::operator=(const TArray3D& param)
{
if(this == ¶m)
return *this;
else
{
this->width = param.width;
this->height = param.height;
this->depth = param.depth;
Free();
Allocate();
Copy(param);
}
}
template<class T>
T* TArray3D<T>::operator()(const u32& x, const u32& y, const u32& z)
{
return &array[x][y][z];
}
template<class T>
TArray3D<T>::~TArray3D()
{
Free();
}
template<class T>
void TArray3D<T>::Allocate()
{
array = new T**[width];
for(u32 x = 0; x < width; x++)
{
array[x] = new T*[height];
for(u32 y = 0; y < height; y++)
array[x][y] = new T[depth];
}
}
template<class T>
void TArray3D<T>::Free()
{
if(array)
{
for(u32 x = 0; x < width; x++)
{
for(u32 y = 0; y < height; y++)
delete [] array[x][y];
delete [] array[x];
}
delete [] array;
}
}
template<class T>
void TArray3D<T>::Copy(const TArray3D& param)
{
for(u32 x = 0; x < width; x++)
{
array[x][0][0] = param.array[x][0][0];
for(u32 y = 0; y < height; y++)
{
array[x][y][0] = param.array[x][y][0];
for(u32 z = 0; z < depth; z++)
array[x][y][z] = param.array[x][y][z];
}
}
}
}
#endif // ARRAY3D_H
<file_sep>var searchData=
[
['world',['World',['../classIrrGame_1_1World.html',1,'IrrGame']]]
];
<file_sep>var searchData=
[
['uncopyable',['Uncopyable',['../classIrrGame_1_1Uncopyable.html',1,'IrrGame']]]
];
<file_sep>/**
* @file Config.cpp
* @author <NAME>
* @brief Configuration class, holds information about general game configurations. Reads and writes these parameters.
*/
#include "Config.h"
namespace IrrGame
{
Config::Config() : cfgFName("config")
{
// Initialize the stream
stream = FileStream("data/" + cfgFName + ".cfg");
// Read window bounds
this->windowBounds = Rectangle(0,0,std::stoi(ReadParam(WIDTH)),std::stoi(ReadParam(HEIGHT)));
// Read window caption
std::string caption = ReadParam(CAPTION);
std::wstring ws;
ws.assign(caption.begin(), caption.end());
this->windowCaption = ws;
}
Config::~Config()
{
if(stream.IsOpen())
stream.Close();
}
const Rectangle& Config::WindowBounds() const
{
return windowBounds;
}
const std::wstring& Config::WindowCaption() const
{
return windowCaption;
}
void Config::SetWindowBounds(u32 width, u32 height)
{
windowBounds.width = width;
windowBounds.height = height;
}
void Config::SetWindowCaption(const std::wstring& caption)
{
windowCaption = caption;
}
std::string Config::ReadParam(const std::string& param)
{
// Open a new stream for the file
stream.Open();
std::string line = "";
std::string value = "";
while(!stream.EndOfFile())
{
line = stream.ReadLine();
if(line.find(param.c_str()) != std::string::npos)
{
std::vector<std::string> commands = splitStr(line, ':');
if(commands.size() == 1 || commands.size() == 0)
break;
else if(commands[0] == param)
value = commands.back();
}
}
// Close the stream
stream.Close();
if(value == "")
Log("Error reading parameter " + param + " from config file!");
return value;
}
void Config::WriteParam(const std::string& param)
{
}
void Config::WriteParam(const u32& param)
{
WriteParam(std::to_string(param));
}
}
<file_sep>/**
* @file Shapes.cpp
* @author <NAME>
* @brief Definitions for shape functions.
*/
#include "Shapes.h"
namespace IrrGame
{
Rectangle::Rectangle(u32 x, u32 y, u32 width, u32 height)
{
this->x = x;
this->y = y;
this->width = width;
this->height = height;
}
u32 Rectangle::Area() const
{
return width*height;
}
Cube::Cube(u32 x, u32 y, u32 z, u32 width, u32 height, u32 depth)
{
this->x = x;
this->y = y;
this->z = z;
this->width = width;
this->height = height;
this->depth = depth;
}
u32 Cube::Area() const
{
return width*height*depth;
}
}
<file_sep>/**
* @file DebugHUD.h
* @author <NAME>
* @brief Declares a debugging HUD for IrrGame.
* @see DebugHUD
*/
#include "DebugHUD.h"
namespace IrrGame
{
void DebugHUD::Init()
{
smallFont = AddFont("data/fonts/smallFont.xml");
mediumFont = AddFont("data/fonts/mediumFont.xml");
largeFont = AddFont("data/fonts/largeFont.xml");
dimension2du titleDims = TextDimensions(L"IrrGame Debug Display", mediumFont);
title = AddElement(L"IrrGame Debug Display", vector2di(0, 0), mediumFont, SColor(255, 255, 255, 255));
fps = AddElement(L"FPS: ", vector2di(2, 95), smallFont, SColor(255, 255, 255, 255));
timer = AddElement(L"Time(ms):", L"0", vector2di(75, 0), smallFont, SColor(255, 255, 255, 255));
}
void DebugHUD::Update(const Config& config, const u32& fps, const double& elapsedTime)
{
std::string eTime = std::to_string(elapsedTime);
std::wstring eTimews;
eTimews.assign(eTime.begin(), eTime.end());
eTimews.append(L"s");
UpdateElement(timer, eTimews);
}
}
<file_sep>/**
* @file
* @author
* @brief
*/
#include "MyGame.h"
MyGame::MyGame() : Game()
{
}
MyGame::~MyGame()
{
}
void MyGame::Initialize()
{
}
void MyGame::Update()
{
Game::Update();
}
void MyGame::Render()
{
Game::Render();
}<file_sep>var searchData=
[
['inputstate',['InputState',['../classIrrGame_1_1InputState.html',1,'IrrGame']]],
['irreventhandler',['IrrEventHandler',['../classIrrGame_1_1IrrEventHandler.html',1,'IrrGame']]]
];
<file_sep>var searchData=
[
['uncopyable',['Uncopyable',['../classIrrGame_1_1Uncopyable.html',1,'IrrGame']]],
['uncopyable_2eh',['uncopyable.h',['../uncopyable_8h.html',1,'']]],
['up',['Up',['../namespaceIrrGame.html#a0cd2211b782c02b155849fc9304c4d29a258f49887ef8d14ac268c92b02503aaa',1,'IrrGame']]],
['update',['Update',['../classIrrGame_1_1Game.html#a40f7811f6fe6e7886683be7dcb0a5a19',1,'IrrGame::Game::Update()'],['../classIrrGame_1_1GameTime.html#acb87862efbc3daf2b55cb69fbb137205',1,'IrrGame::GameTime::Update()'],['../classIrrGame_1_1InputState.html#abc10661ddc4fb791a8c572327274aa98',1,'IrrGame::InputState::Update()']]],
['updateelement',['UpdateElement',['../classIrrGame_1_1HUD.html#ae10e15dbf860002396b55c29a928aafd',1,'IrrGame::HUD']]]
];
<file_sep>var searchData=
[
['debughud',['DebugHUD',['../classIrrGame_1_1DebugHUD.html',1,'IrrGame']]],
['debughud_2eh',['DebugHUD.h',['../DebugHUD_8h.html',1,'']]],
['deltatime',['DeltaTime',['../classIrrGame_1_1GameTime.html#af7a367da92c520f7063538fdf1fddb9b',1,'IrrGame::GameTime']]],
['down',['Down',['../namespaceIrrGame.html#a0cd2211b782c02b155849fc9304c4d29a08a38277b0309070706f6652eeae9a53',1,'IrrGame']]]
];
<file_sep>/**
* @file
* @author
* @brief
*/
#ifndef MYGAME_H
#define MYGAME_H
#include "Game.h"
using namespace IrrGame;
class MyGame : public Game
{
public:
MyGame();
virtual ~MyGame();
protected:
virtual void Initialize();
virtual void Update();
virtual void Render();
};
#endif // MYGAME_H<file_sep>/**
* @file FileStream.cpp
* @author <NAME>
* @brief fstream wrapper class.
*/
#include "IO.h"
namespace IrrGame
{
FileStream::FileStream()
{
filePath = "";
}
FileStream::FileStream(const std::string& filePath)
{
this->filePath = filePath;
}
FileStream::FileStream(const FileStream& param)
{
cpy(param);
}
const FileStream& FileStream::operator=(const FileStream& param)
{
if(this == ¶m)
return *this;
else
{
cpy(param);
return *this;
}
}
void FileStream::cpy(const FileStream& param)
{
this->filePath = param.filePath;
}
FileStream::~FileStream()
{
if(file.is_open())
file.close();
}
std::string FileStream::ReadLine()
{
if(file.is_open())
{
std::string retVal;
getline(file, retVal);
return retVal;
}
}
char FileStream::ReadChar()
{
if(file.is_open())
{
char character;
file.get(character);
return character;
}
}
void FileStream::WriteLine(const std::string& line)
{
file.write((line + "\n").c_str(), line.length() + 1);
}
void FileStream::Write(const std::string& data)
{
file.write(data.c_str(), data.length());
}
void FileStream::WriteChar(const char& data)
{
file.write(&data, 1);
}
void FileStream::Open()
{
Close();
file.open(filePath, std::ios::in | std::ios::out | std::fstream::app);
if (file.rdstate() == std::ios_base::failbit)
std::cout << "Error! Failed to open stream for file " << filePath << "!\n";
}
void FileStream::Close()
{
if(file.is_open())
file.close();
}
bool FileStream::IsOpen() const
{
return file.is_open();
}
bool FileStream::EndOfFile() const
{
return file.eof();
}
const std::string& FileStream::GetPath() const
{
return filePath;
}
void FileStream::Seek(std::string data)
{
}
}
<file_sep>var searchData=
[
['close',['Close',['../classIrrGame_1_1FileStream.html#a837ae63a6ce0d26f4b3184e5ae488f99',1,'IrrGame::FileStream']]],
['config',['Config',['../structIrrGame_1_1Config.html',1,'IrrGame']]],
['config_2eh',['Config.h',['../Config_8h.html',1,'']]],
['cube',['Cube',['../structIrrGame_1_1Cube.html',1,'IrrGame']]]
];
<file_sep>/**
* @file Game.cpp
* @author <NAME>
* @brief A base game class using the Irrlicht rendering engine.
*/
#include "Game.h"
namespace IrrGame
{
Game::Game()
{
Init();
state = READY;
}
void Game::Init()
{
Log("Initializing IrrGame Object...");
// Initialize the input handler
eventHandler = IrrEventHandler();
// Create and register an input state.
inputState = new InputState();
eventHandler.RegisterInputState(inputState);
// Create an Irrlicht device, with window bounds, and pass a reference to the event handler.
iDevice = createDevice(video::EDT_OPENGL, dimension2d<u32>(cfg.WindowBounds().width, cfg.WindowBounds().height), 16,
false, false, true, &eventHandler);
// Handle any errors creating the Irrlicht device.
if (iDevice == nullptr)
{
Log("Error initializing irrlicht device!");
SetState(ERR_STATE);
}
// Initialize timer
gameTime = new GameTime(iDevice->getTimer());
// Initialize time since last update
timeSinceUpdate = 0;
// Initialize component list
components = std::vector<GameComponent*>();
// Set the window caption using the current configuration.
std::wstring caption = L"IrrGame " + GetIrrGameVersion() + L" : " + cfg.WindowCaption();
iDevice->setWindowCaption((wchar_t*)caption.c_str());
// Obtain pointers to useful objects
iVideoDriver = iDevice->getVideoDriver();
iGUIEnv = iDevice->getGUIEnvironment();
// Initialize the game world
world = World(iDevice->getSceneManager(), iVideoDriver, 10, 10, 10);
// Remove cursor
iDevice->getCursorControl()->setVisible(false);
// Initlialize the debug HUD.
dbgHUD = DebugHUD(cfg, iGUIEnv);
dbgHUD.Init();
}
std::wstring Game::GetIrrGameVersion() const
{
return L"v" + IRRGAME_MAJOR_VER + L"." + IRRGAME_MINOR_VER;
}
const GameState& Game::GetState() const
{
return state;
}
void Game::SetState(const GameState& state)
{
this->state = state;
}
void Game::Run()
{
state = RUNNING;
Initialize();
Log("Entering main game loop...");
while(state == RUNNING)
{
if (!iDevice->run())
errFatal("Irrlicht device failed unexpectedly.");
gameTime->Update(); // Update game time
timeSinceUpdate += gameTime->DeltaTime();
if (timeSinceUpdate >= timeStep)
{
Update(); // Update the game logig
timeSinceUpdate = 0;
}
Render(); // Render the game world
inputState->Flush(); // Flush the input state
}
if(state == ERR_STATE)
Log("IrrGame exitted with ERR_STATE");
else
Log("IrrGame exitted cleanly.");
FreeIDevice();
}
void Game::AddGameComponent(GameComponent* component)
{
components.push_back(component);
}
void Game::Initialize()
{
// Empty for base game
}
void Game::Update()
{
if (inputState->IsKeyPressed(KEY_ESCAPE))
state = EXIT;
#ifdef _DEBUG
if (inputState->IsKeyReleased(KEY_TAB))
{
drawDebugHUD = !drawDebugHUD;
Log("Toggle HUD");
}
#endif // _DEBUG
// Update game components
for (auto component : components)
component->Update();
}
void Game::Render()
{
iVideoDriver->beginScene(true, true, SColor(255, 100, 101, 140));
world.Render();
iGUIEnv->drawAll();
#ifdef _DEBUG
if (drawDebugHUD)
{
dbgHUD.Update(cfg, 0, gameTime->ElapsedTime()/1000);
dbgHUD.Render();
}
#endif // _DEBUG
iVideoDriver->endScene();
// Render game components
for (auto component : components)
component->Render();
}
void Game::FreeIDevice()
{
iDevice->drop();
iDevice = nullptr;
}
void Game::errFatal(const std::string msg)
{
state = ERR_STATE;
}
Game::~Game()
{
if(iDevice)
FreeIDevice();
if (gameTime)
delete gameTime;
for (auto& component : components)
delete component;
}
}
<file_sep>/**
* @file
* @author
* @brief
*/
#ifndef GAMETIME_H
#define GAMETIME_H
#include <ITimer.h>
#ifdef WIN32
#include <Windows.h>
#endif // WIN32
using namespace irr;
namespace IrrGame
{
class GameTime
{
public:
GameTime();
GameTime(ITimer* timer);
virtual ~GameTime();
/** Update the values held by the game time object. */
void Update();
/** Retrieve the total elapsed game time. */
u32 ElapsedTime() const;
/** Retrieve delta time since the last call to update. */
u32 DeltaTime() const;
private:
ITimer* timer;
u32 prevTime; /*!< Time on the previous call to update. */
u32 deltaTime; /*!< Delta time in milliseconds since the timer was last updated. */
u32 elapsedTime; /*!< Total elapsed time in milliseconds. */
};
}
#endif // GAMETIME_H<file_sep>## IrrGame
A small set of wrapper and utility classes for a game using the Irrlicht rendering engine.
<file_sep>/**
* @file stringext.h
* @author <NAME>
* @brief Extension functions for STL string manipulation.
*/
#ifndef _STRING_EXT_H_
#define _STRING_EXT_H_
#include <string>
#include <sstream>
#include <vector>
#include <iostream>
#include "IO.h"
namespace IrrGame
{
/**
* Splits a string given a delimiter.
* @param str The string to split.
* @param delim The delimiter to use to split the string.
*/
static const std::vector<std::string> splitStr(const std::string str, const char& delim)
{
std::stringstream ss(str);
std::string item;
std::vector<std::string> elems = std::vector<std::string>();
while (std::getline(ss, item, delim)) {
elems.push_back(item);
}
return elems;
}
}
#endif // _STRING_EXT_H_
<file_sep>var searchData=
[
['elapsedtime',['ElapsedTime',['../classIrrGame_1_1GameTime.html#a71d1b489b5dfed2590bc509b82ad3201',1,'IrrGame::GameTime']]],
['endoffile',['EndOfFile',['../classIrrGame_1_1FileStream.html#a59dc75726e89fdf929f17adc172b7e7b',1,'IrrGame::FileStream']]],
['errfatal',['errFatal',['../classIrrGame_1_1Game.html#a711559d980c1f06f7ddb18f4b15e2e22',1,'IrrGame::Game']]]
];
<file_sep>/**
* @file Config.h
* @author <NAME>
* @brief Declarations for a configuration structure, reads and writes configuration data.
* @see Config
*/
#ifndef _CONFIG_H_
#define _CONFIG_H_
#include <string>
#include "Shapes.h"
#include "IO.h"
namespace IrrGame
{
/** Represents game configuration data */
struct Config
{
public:
Config();
Config(const Rectangle& windowBounds, const std::string& windowCaption);
~Config();
const Rectangle& WindowBounds() const;
const std::wstring& WindowCaption() const;
void SetWindowBounds(u32 width, u32 height);
void SetWindowCaption(const std::wstring& caption);
private:
Rectangle windowBounds;
std::wstring windowCaption;
const std::string cfgFName;
FileStream stream;
std::string ReadParam(const std::string& param);
void WriteParam(const std::string& param);
void WriteParam(const u32& param);
// Paramaters
const std::string CAPTION = "caption";
const std::string WIDTH = "width";
const std::string HEIGHT = "height";
};
}
#endif // _CONFIG_H_
<file_sep>var searchData=
[
['game_2eh',['Game.h',['../Game_8h.html',1,'']]],
['gametime_2eh',['GameTime.h',['../GameTime_8h.html',1,'']]]
];
<file_sep>/**
* @file HUD.cpp
* @author <NAME>
* @brief Defines a class used to represent a HUD.
* @see HUD
*/
#include "HUD.h"
namespace IrrGame
{
HUD::HUDElement::HUDElement(std::wstring text, std::wstring data, vector2di position, IGUIFont* font, SColor color)
{
this->text = text;
this->data = data;
this->position = position;
this->color = color;
this->font = font;
}
HUD::HUD()
{
elements = std::vector<HUDElement>();
}
HUD::HUD(const Config& cfg, IGUIEnvironment* guiEnv)
{
cfgWidth = cfg.WindowBounds().width;
cfgHeight = cfg.WindowBounds().height;
iGUIEnv = guiEnv;
}
u32 HUD::AddFont(std::string path)
{
fonts.push_back(iGUIEnv->getFont(path.c_str()));
return fonts.size() - 1;
}
IGUIFont* HUD::GetFont(u32 id) const
{
return fonts.at(id);
}
dimension2du HUD::ElementDimensions(u32 elementID)
{
dimension2du dims = elements[elementID].font->getDimension((elements[elementID].text + elements[elementID].data).c_str());
f32 w = ((f32)dims.Width / (f32)cfgWidth) * 100;
f32 h = ((f32)dims.Height / (f32)cfgHeight) * 100;
dims.Width = w;
dims.Height = h;
return dims;
}
dimension2du HUD::TextDimensions(std::wstring text, u32 fontID)
{
dimension2du dims = fonts[fontID]->getDimension(text.c_str());
f32 w = ((f32)dims.Width / (f32)cfgWidth) * 100;
f32 h = ((f32)dims.Height / (f32)cfgHeight) * 100;
dims.Width = w;
dims.Height = h;
return dims;
}
void HUD::UpdateElement(u32 elementID, std::wstring newData)
{
elements.at(elementID).data = newData;
}
HUD::~HUD()
{
}
void HUD::Render()
{
for(auto element : elements)
{
element.font->draw((element.text + element.data).c_str(), rect<s32>((cfgWidth * element.position.X) / 100,
(cfgHeight * element.position.Y) / 100, 0, 0), video::SColor(255, 255, 255, 255));
}
}
u32 HUD::AddElement(std::wstring text, std::wstring data, vector2di position, u32 font, SColor color)
{
if(font < 0 && font > fonts.size())
Log("Invalid font ID passed into HUD.");
elements.push_back(HUDElement(text, data, vector2di(clamp<u32>(position.X, 0, 100), clamp<u32>(position.Y, 0, 100)), GetFont(font), color));
return elements.size()-1;
}
u32 HUD::AddElement(std::wstring text, vector2di position, u32 font, SColor color)
{
return AddElement(text, L"", position, font, color); // Add element with blank data
}
}
<file_sep>var searchData=
[
['update',['Update',['../classIrrGame_1_1Game.html#a40f7811f6fe6e7886683be7dcb0a5a19',1,'IrrGame::Game::Update()'],['../classIrrGame_1_1GameTime.html#acb87862efbc3daf2b55cb69fbb137205',1,'IrrGame::GameTime::Update()'],['../classIrrGame_1_1InputState.html#abc10661ddc4fb791a8c572327274aa98',1,'IrrGame::InputState::Update()']]],
['updateelement',['UpdateElement',['../classIrrGame_1_1HUD.html#ae10e15dbf860002396b55c29a928aafd',1,'IrrGame::HUD']]]
];
<file_sep>/**
* @file Shapes.h
* @author <NAME>
* @brief Declarations for shape structures.
*/
#ifndef _SHAPES_H_
#define _SHAPES_H_
#include <irrlicht.h>
using namespace irr;
namespace IrrGame
{
struct Rectangle
{
Rectangle(u32 x = 0, u32 y = 0, u32 width = 0, u32 height = 0);
u32 Area() const;
u32 x, y;
u32 width, height;
};
struct Cube
{
Cube(u32 x = 0, u32 y = 0, u32 z = 0, u32 width = 0, u32 height = 0, u32 depth = 0);
u32 Area() const;
u32 x, y, z;
u32 width, height, depth;
};
}
#endif // _SHAPES_H_
<file_sep>/**
* @file Log.cpp
* @author <NAME>
* @brief Definitions for writing to a log during debug.
*/
#include "IO.h"
namespace IrrGame
{
#ifdef _DEBUG
static std::string logFilePath = "log.txt";
static FileStream logStream;
void SetLogFile(const std::string& filePath)
{
logFilePath = filePath;
}
void Log(const std::string& data)
{
logStream = FileStream(logFilePath);
logStream.Open();
logStream.WriteLine(data);
std::cout << "IrrGame Log: " << data << std::endl;
logStream.Close();
}
#endif // _DEBUG
#ifdef NDEBUG
void Log(const std::string& data) { }
#endif // NDEBUG
}
<file_sep>/**
* @file DebugHUD.h
* @author <NAME>
* @brief Declares a debugging HUD for IrrGame.
* @see DebugHUD
*/
#ifndef DEBUGHUD_H
#define DEBUGHUD_H
#include "HUD.h"
namespace IrrGame
{
class DebugHUD : public HUD
{
public:
DebugHUD() : HUD() { }
DebugHUD(const Config& cfg, IGUIEnvironment* guiEnv) : HUD(cfg, guiEnv) { }
void Init();
void Update(const Config& config, const u32& fps, const double& elapsedTime);
private:
/* Font IDs */
u32 smallFont;
u32 mediumFont;
u32 largeFont;
/* Element IDs */
u32 title;
u32 version;
u32 fps;
u32 timer;
};
}
#endif // DEBUGHUD_H
<file_sep>/**
* @file Game.h
* @author <NAME>
* @brief Definitions for a base game class using the Irrlicht rendering engine.
*/
#ifndef IRRGAME_H
#define IRRGAME_H
#include <irrlicht.h>
#include "Config.h"
#include "IrrEventHandler.h"
#include "World.h"
#include "IO.h"
#include "DebugHUD.h"
#include "GameTime.h"
#include "GameComponent.h"
// Irrilicht namespace and subnamespaces
using namespace irr;
using namespace core;
using namespace scene;
using namespace video;
using namespace io;
using namespace gui;
/** Primary namespace used by IrrGame */
namespace IrrGame
{
/** Represents a game state. */
enum GameState
{
READY, /*!< The game is ready, but Run() has not been called. */
RUNNING, /*!< The game is currently running and is updating the main loop. */
ERR_STATE, /*!< The game is in error state, and will exit after the current loop. */
EXIT /*!< The game is preparing to exit cleanly by user request, and will exit after the current loop. */
};
/** A Game class. */
class Game
{
public:
Game();
virtual ~Game();
/** Run the game, entering the main loop. */
void Run();
protected:
Config cfg; /** The game configuration object. */
IrrlichtDevice* iDevice; /** The main Irrlicht device. */
IVideoDriver* iVideoDriver; /** The Irrlicht video driver. */
IGUIEnvironment* iGUIEnv; /** The Irrlicht GUI Environment. */
/** Retrieves the current game state. */
const GameState& GetState() const;
/** Sets the current game state. */
void SetState(const GameState& state);
/** Fatal error has occurred, outputs a log message and sets game to error state. */
void errFatal(const std::string msg);
/** Frees the Irrlicht device. */
void FreeIDevice();
/** Override in base class. Called just before entering main game loop. Used for game specific initialization. */
virtual void Initialize();
/** Override in base class. */
virtual void Update();
/** Override in base class. */
virtual void Render();
/** Retrieve the version of IrrGame being used by this game object. */
std::wstring GetIrrGameVersion() const;
/** Add a component to the list of game components. */
void AddGameComponent(GameComponent* component);
private:
// ----- PRIVATE FUNCTIONS-----
/** Internal initialization. */
void Init();
/** Calculate the current frame rate. */
void CalculateFrameRate();
// ----- PRIVATE MEMBERS -----
GameState state; /*!< The current game state. */
std::vector<GameComponent*> components; /*!< Collection of game components. */
InputState* inputState; /*!< The current input state. */
IrrEventHandler eventHandler; /*!< The game event handler. */
World world; /*!< The game world currently loaded. */
GameTime* gameTime; /*!< Contains a snapshot of the current state of game time. */
bool drawDebugHUD; /*!< Whether or not the debug HUD is to be rendered. */
f32 timeStep = 60/1000; /*!< The current fixed time step used by the update loop. */
f32 timeSinceUpdate; /*!< The time since the last call to update. */
const std::wstring IRRGAME_MAJOR_VER = L"0"; /*!< The current major version of IrrGame being used. */
const std::wstring IRRGAME_MINOR_VER = L"1"; /*!< The current minor version of IrrGame being used. */
#ifdef _DEBUG
DebugHUD dbgHUD; /*!< The debugging HUD. */
#endif // _DEBUG
};
}
#endif // IRRGAME_H
<file_sep>#include "MyGame.h"
using namespace IrrGame;
#ifdef NDEBUG
#ifdef WIN32
#pragma comment(linker, "/subsystem:windows /ENTRY:mainCRTStartup")
#endif // WIN32
#endif // NDEBUG
u32 main()
{
MyGame game = MyGame();
game.Run();
}
<file_sep>/**
* @file
* @author
* @brief
*/
namespace IrrGame
{
class GameComponent
{
public:
GameComponent() : visible(true), enabled(true) { };
virtual ~GameComponent();
void SetVisible(bool visible) { this->visible = visible; }
void SetEnabled(bool enabled) { this->enabled = enabled; }
virtual void Update() = 0;
virtual void Render() = 0;
private:
bool visible;
bool enabled;
};
}<file_sep>/**
* @file uncopyable.h
* @author <NAME>
* @brief Declaration for an uncopyable base class.
*/
#ifndef _UNCOPYABLE_H_
#define _UNCOPYABLE_H_
namespace IrrGame
{
class Uncopyable
{
public:
Uncopyable() { }
private:
const Uncopyable& operator=(const Uncopyable& param);
Uncopyable(const Uncopyable& param);
};
}
#endif // _UNCOPYABLE_H_
<file_sep>var searchData=
[
['err_5fstate',['ERR_STATE',['../namespaceIrrGame.html#afb6a2153afcdd0094369f1354c3d6809aff30130ab20dba1945427b7dd9e74469',1,'IrrGame']]],
['exit',['EXIT',['../namespaceIrrGame.html#afb6a2153afcdd0094369f1354c3d6809abc4de6844e2bd1b156749c1019e1cc33',1,'IrrGame']]]
];
<file_sep>/**
* @file World.h
* @author <NAME>
* @brief Declarations for a class that represents the world scene node.
* @see World
*/
#ifndef WORLD_H
#define WORLD_H
#include <irrlicht.h>
#include "IO.h"
using namespace irr;
using namespace scene;
using namespace video;
using namespace core;
namespace IrrGame
{
/** Represents the world scene node. */
class World
{
public:
World();
/*! World Constructor */
/**
@param scene Pointer to the scene manager for the world to use.
@param driver The video driver used by the world.
@param up The up vector used by the world.
*/
World(ISceneManager* scene, IVideoDriver* driver, u32 width, u32 height, u32 depth, const vector3df& up = vector3df(0, 1, 0));
/*! Creates and adds an animated mesh node from a mesh and texture. */
/**
* @param mesh The mesh for the node to use.
* @param texturePath The name of the texture file.
*/
IAnimatedMeshSceneNode* AddAnimatedMesh(const std::string& modelFile, const std::string& textureFile = NO_TEXTURE,
ISceneNode* parent = nullptr, const vector3df& position = ORIGIN, const vector3df& rotation = vector3df(0, 0, 0), const vector3df& scale = vector3df(1.0f, 1.0f, 1.0f));
/*! Creates and adds a scene node from an SMesh and a texture. */
/**
* @param mesh The mesh to use.
* @param textureFile The name of the texture file.
*/
IMeshSceneNode* AddMesh(IMesh* mesh, const std::string& textureFile = NO_TEXTURE);
/*! Renders the world. */
void Render();
virtual ~World();
private:
ISceneManager* scene; /*!< The scene manager the world is using. */
IVideoDriver* driver; /*!< The video driver being used by the world. */
// World Constants
static const std::string TEXTURE_PATH; /*!< Constant string containing address of the global texture directory. */
static const std::string MODEL_PATH; /*!< Constant string containing address of the global model directory. */
static const std::string NO_TEXTURE; /*!< The path of the texture to use on a mesh if none is supplied. */
static const vector3df ORIGIN; /*!< Defines the world origin. */
vector3df up; /*!< Up vector being used by this world. */
};
}
#endif // WORLD_H
<file_sep># ------------------------------------------------------------------------------------------#
# THIS MAKEFILE IS PART OF IRRGAME. #
# #
# Author: <NAME> #
# Date Created: 4/4/2014 #
# Usage: DO NOT MODIFY THIS FILE. Call 'make debug' and 'make release' to build #
# debug and release builds. Use 'make clean' to clean all object files. #
#-------------------------------------------------------------------------------------------#
include MakeConfigure
# ----- TARGETS ----- #
all:
@echo "Please use either 'make debug' or 'make release' targets when building."
# ----- DEBUG TARGET -----
debug: $(COPY_DATA) $(OBJECTS)
@echo "Compiling objects for target '$@'..."
$(CC) $(CCFLAGS) -g $(OBJECTS) -o $(BLD_DIR)/$(EXEC) $(INCL_DIR) $(LIB_DIRS) $(LIBS)
# ----- RELEASE TARGET -----
release: $(COPY_DATA) $(OBJECTS)
@echo "Compiling objects..."
$(CC) $(CCFLAGS) $(OBJECTS) -o $(BLD_DIR)/$(EXEC) $(INCL_DIR) $(LIB_DIRS) $(LIBS)
# ----- CLEAN TARGET -----
clean:
rm -r obj/unix/debug/*.o
rm -r obj/unix/release/*.o
rm -r build/unix/debug/data/*
rm -r build/unix/release/data/*
# ----- PATTERN RULE FOR .CPP TO .O -----
$(INT_DIR)/%.o : $(SRC_DIR)/%.cpp
@echo "Compiling: " $< " into " $(INT_DIR)/$(basename $(notdir $<)).o
$(CC) $(PRP_DIR) $(CCFLAGS) -c $< -o $(INT_DIR)/$(basename $(notdir $<)).o $(INCL_DIR)
# ----- COPY DATA TARGET -----
$(COPY_DATA):
@echo "Copying data files..."
cp -r ./data/ $(BLD_DIR)
<file_sep>var searchData=
[
['world',['World',['../classIrrGame_1_1World.html',1,'IrrGame']]],
['world',['World',['../classIrrGame_1_1World.html#af663c17fe7389fad19e26360f848d95c',1,'IrrGame::World']]],
['world_2eh',['World.h',['../World_8h.html',1,'']]],
['write',['Write',['../classIrrGame_1_1FileStream.html#a3b65ff555bdad7ee74c5b1c2935df1f6',1,'IrrGame::FileStream']]],
['writechar',['WriteChar',['../classIrrGame_1_1FileStream.html#aa03671834de94c26d8b1b7ad833ec089',1,'IrrGame::FileStream']]],
['writeline',['WriteLine',['../classIrrGame_1_1FileStream.html#a31e988a04b7d9c9895ef5807f27ad1eb',1,'IrrGame::FileStream']]]
];
<file_sep>/**
* @file IrrEventHandler.cpp
* @author <NAME>
* @brief Declarations for keyboard input event handlers.
*/
#ifndef INPUTHANDLER_H
#define INPUTHANDLER_H
#include <irrlicht.h>
#include <vector>
using namespace irr;
using namespace core;
namespace IrrGame
{
/** Represents the state of a key. */
enum class KeyState
{
Pressed, /*! Key has just been pressed.*/
Released, /*! Key has just been released.*/
Up, /*!< Key is up. */
Down /*!< Key is down. */
};
/** Typedef of keystate used to represent the state of a mouse button. */
typedef KeyState MouseButtonState;
enum class MouseButton
{
Left,
Right
};
/** Represents the current state of the keyboard. */
class KeyboardState
{
public:
friend class InputState;
private:
KeyboardState();
virtual ~KeyboardState();
KeyState keyStates[KEY_KEY_CODES_COUNT]; /** Collection of the state of each key. */
std::vector<EKEY_CODE> pressedKeys; /*!< Keeps track of keys pressed this frame. */
std::vector<EKEY_CODE> releasedKeys; /*!< Keeps track of keys released this frame. */
};
/** Represents the current state of the mouse. */
class MouseState
{
public:
friend class InputState;
private:
MouseState();
virtual ~MouseState();
vector2di position; /*!< Position of the mouse in the window. */
f32 wheelDir; /*!< Direction and speed the mouse wheel has moved. */
MouseButtonState leftButton; /*!< State of the left mouse button. */
MouseButtonState rightButton; /*!< State of the right mouse button. */
};
/** Stores the current input state. */
class InputState
{
public:
InputState();
virtual ~InputState();
/** Is the given key currently down? */
bool IsKeyDown(EKEY_CODE keyCode) const;
/** Is the given key currently up? */
bool IsKeyUp(EKEY_CODE keyCode) const;
/** Has the given key just been pressed? */
bool IsKeyPressed(EKEY_CODE keyCode) const;
/** Has the given key just been released? */
bool IsKeyReleased(EKEY_CODE keyCode) const;
/** Is the given mouse button currently down? */
bool IsMouseButtonDown(MouseButton button) const;
/** Is the given mouse button currently up? */
bool IsMouseButtonUp(MouseButton button) const;
/** Has the given mouse button just been released? */
bool IsMouseButtonReleased(MouseButton button) const;
/** Has the given mouse button just been pressed? */
bool IsMouseButtonPressed(MouseButton button) const;
/** Get the value of the mouse wheel. */
f32 MouseWheel() const;
/** Flushes the input state. Any pressed buttons are set to down. Placed at the end of a call to update. */
void Flush();
friend class IrrEventHandler;
private:
/** Sets the state of the given key. */
void SetKey(EKEY_CODE key, KeyState state);
/** Sets the state of the given mouse button. */
void SetMouseButton(MouseButton button, MouseButtonState state);
/** @overload */
void SetMousePosition(vector2di position);
/** Set the current state of the mouse wheel. */
void SetMouseWheel(const f32& dir);
KeyboardState keyboardState;
MouseState mouseState;
};
/** Implements IEventReceiver, handles keyboard events. */
class IrrEventHandler : public IEventReceiver
{
public:
IrrEventHandler();
virtual ~IrrEventHandler();
virtual bool OnEvent(const SEvent& event);
/**
* Registers an input state to be updated by the event handler. Once registered, the IrrGameHandler is responsible for managing it as a resource, and
* deletion of it.
*/
/**
* @param inputState The input state to update with the event handler.
*/
void RegisterInputState(InputState* inputState);
private:
InputState* inputState;
};
}
#endif // INPUTHANDLER_H
<file_sep>var searchData=
[
['config',['Config',['../structIrrGame_1_1Config.html',1,'IrrGame']]],
['cube',['Cube',['../structIrrGame_1_1Cube.html',1,'IrrGame']]]
];
<file_sep>/**
* @file HUD.h
* @author <NAME>
* @brief Declares a class used to represent a HUD.
* @see HUD
*/
#ifndef HUD_H
#define HUD_H
#include <irrlicht.h>
#include <vector>
#include <string>
#include "IO.h"
#include "Config.h"
using namespace irr;
using namespace core;
using namespace gui;
using namespace video;
namespace IrrGame
{
/** Heads up display. Derive from this and implement the init function for bespoke heads up displays. */
class HUD
{
public:
HUD();
/** Construct a new heads up display. */
/**
* @param windowWidth The width of the window.
* @param windowHeight The height of the window.
* @param guiEnv The Irrlicht GUI environment used to render text.
*/
HUD(const Config& cfg, IGUIEnvironment* guiEnv);
virtual ~HUD();
/** Draw the HUD elements to the screen. */
void Render();
/** Interface function, override this in base class. */
virtual void Init() = 0;
protected:
/** Add a HUD element that displays some form of data. */
/**
* @param text Text to display next to the data value.
* @param data The data value to display.
* @param position The position to display the text at (x and y between 1-100).
* @return The ID of the element being inserted. Store this for later use in order to update the element.
*/
u32 AddElement(std::wstring text, std::wstring data, vector2di position, u32 font, SColor color);
/** Add a HUD element with only text. */
/**
* @param text Text to display next to the data value.
* @param position The position to display the text at (x and y between 1-100).
* @return The ID of the element being inserted. Store this for later use in order to update the element.
*/
u32 AddElement(std::wstring text, vector2di position, u32 font, SColor color);
/** Update an element in the HUD with new data. */
/**
* @param elementID ID of the element.
* @param newData The new data to display for this element.
*/
void UpdateElement(u32 elementID, std::wstring newData);
/** Adds a font to the HUD. */
/**
* @param path Path of the font XML file and all image files.
* @return Returns the ID of the font.
*/
u32 AddFont(std::string path);
/** Returns font contained within the given ID. */
/**
* @param id The ID of the font.
*/
IGUIFont* GetFont(u32 id) const;
/** Returns the dimensions of the given element on screen. */
/**
* @param elementID The ID of the element to obtain dimensions for.
*/
dimension2du ElementDimensions(u32 elementID);
/** Returns the dimensions of text should it be drawn with the given font. */
/**
* @param text The text to get the dimensions for.
* @param fontID The font to use to draw the text.
*/
dimension2du TextDimensions(std::wstring text, u32 fontID);
protected:
u32 cfgWidth; /*!< The window width of the HUD. */
u32 cfgHeight; /*!< The window width of the HUD. */
private:
/** Class that represents a HUD element. */
struct HUDElement
{
/** Construct a new HUD element. */
/**
* @param text Text to display in this element.
* @param data The data to display in this element.
* @param position The position of this element, clamped to 0-100 on both axes.
* @param font The font ID used by this element.
* @param color The color of this HUD element.
*/
HUDElement(std::wstring text, std::wstring data, vector2di position, IGUIFont* font, SColor color);
std::wstring text; /*!< Text stored by this element. */
std::wstring data; /*!< The data stored and displayed by this element. */
vector2di position; /*!< Position of this element. Clamped to 0-100 X and 0-100 Y. */
IGUIFont* font; /*!< Font used by this element. */
SColor color; /*!< Color used by this HUD element. */
};
std::vector<IGUIFont*> fonts; /*!< Small font used by the HUD. */
IGUIEnvironment* iGUIEnv; /*!< The GUI environment from the Irrlicht device used by this HUD. */
std::vector<HUDElement> elements; /*!< The list of elements in the HUD. */
};
}
#endif // HUD_H
<file_sep>var searchData=
[
['up',['Up',['../namespaceIrrGame.html#a0cd2211b782c02b155849fc9304c4d29a258f49887ef8d14ac268c92b02503aaa',1,'IrrGame']]]
];
<file_sep>/**
* @file FileStream.H
* @author <NAME>
* @brief Declarations for an fstream wrapper class.
*/
#ifndef FILESTREAM_H
#define FILESTREAM_H
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include "stringext.h"
namespace IrrGame
{
/** Write data out to the game log and terminal window. */
extern void Log(const std::string& data);
/** Set the logging file path. */
extern void SetLogPath(const std::string& filePath);
/** Represents a file stream. */
class FileStream
{
public:
FileStream();
/** Construct a new filestream with the given path. Does not open the stream. */
/**
* @param filePath The path of the file with which to use in the stream.
*/
FileStream(const std::string& filePath);
FileStream(const FileStream& param);
const FileStream& operator=(const FileStream& param);
virtual ~FileStream();
/** Read the next line from the file. */
std::string ReadLine();
/** Read the next character from the file. */
char ReadChar();
/** Write a line to the file. */
void WriteLine(const std::string& line);
/** Write a string to the file. */
void Write(const std::string& data);
/** Write a character to the file. */
void WriteChar(const char& data);
/** Open the file stream with the current file path. */
void Open();
/** Close the file stream. */
void Close();
/** Returns whether or not the file is open. */
bool IsOpen() const;
/** Returns whether or not the stream buffer is at the end of the file. */
bool EndOfFile() const;
/** Seek to the given data in the file. */
void Seek(std::string data);
/** Get the path of the file stream. */
const std::string& GetPath() const;
private:
std::fstream file; /*!< The file stream itself. */
std::string filePath; /*!< Path of the file being streamed. */
// Internal copying function
void cpy(const FileStream& param);
};
}
#endif // FILESTREAM_H
<file_sep>var searchData=
[
['seek',['Seek',['../classIrrGame_1_1FileStream.html#a94cc089ee7cb55cfc7b4fbe3c43d3684',1,'IrrGame::FileStream']]],
['setkey',['SetKey',['../classIrrGame_1_1InputState.html#a1ba778cfc3a8d16096234dfc93e5d4b2',1,'IrrGame::InputState']]],
['setlogpath',['SetLogPath',['../namespaceIrrGame.html#a9ea009bbf840bf34da18adabe5376b09',1,'IrrGame']]],
['setstate',['SetState',['../classIrrGame_1_1Game.html#ad597def56990fbda89f37c475a8b61c4',1,'IrrGame::Game']]],
['shapes_2eh',['Shapes.h',['../Shapes_8h.html',1,'']]],
['start',['Start',['../classIrrGame_1_1Timer.html#a1887e33ba31e11d7774679241f4634a0',1,'IrrGame::Timer']]],
['stop',['Stop',['../classIrrGame_1_1Timer.html#a604a538895de9ee5a16c00c25c0e86be',1,'IrrGame::Timer']]],
['stringext_2eh',['stringext.h',['../stringext_8h.html',1,'']]]
];
<file_sep>/**
* @file
* @author
* @brief
*/
#include "Timer.h"
namespace IrrGame
{
Timer::Timer()
{
gameTime = nullptr;
isRunning = false;
}
Timer::Timer(GameTime* gameTime)
{
this->gameTime = gameTime;
}
Timer::~Timer()
{
}
void Timer::Start()
{
isRunning = true;
startTime = gameTime->ElapsedTime();
}
void Timer::Stop()
{
startTime = 0;
isRunning = false;
}
bool Timer::IsRunning() const
{
return isRunning;
}
u32 Timer::GetTime() const
{
if (isRunning)
return gameTime->ElapsedTime() - startTime;
else
return 0;
}
}<file_sep>var searchData=
[
['getfont',['GetFont',['../classIrrGame_1_1HUD.html#ac9089902b7f008fbcb9e8a5a5782acc0',1,'IrrGame::HUD']]],
['getirrgameversion',['GetIrrGameVersion',['../classIrrGame_1_1Game.html#abd22d92d885496c95ccf12ba1ed803bd',1,'IrrGame::Game']]],
['getpath',['GetPath',['../classIrrGame_1_1FileStream.html#a0f00967548f7503127eeb732fc7ea02e',1,'IrrGame::FileStream']]],
['getstate',['GetState',['../classIrrGame_1_1Game.html#aa861b1b9effdb3f6071d26ce5233af2a',1,'IrrGame::Game']]],
['gettime',['GetTime',['../classIrrGame_1_1Timer.html#a724938c330e641c92fdc1fd54e6d4be9',1,'IrrGame::Timer']]]
];
<file_sep>var searchData=
[
['game',['Game',['../classIrrGame_1_1Game.html',1,'IrrGame']]],
['game_2eh',['Game.h',['../Game_8h.html',1,'']]],
['gamestate',['GameState',['../namespaceIrrGame.html#afb6a2153afcdd0094369f1354c3d6809',1,'IrrGame']]],
['gametime',['GameTime',['../classIrrGame_1_1GameTime.html',1,'IrrGame']]],
['gametime_2eh',['GameTime.h',['../GameTime_8h.html',1,'']]],
['getfont',['GetFont',['../classIrrGame_1_1HUD.html#ac9089902b7f008fbcb9e8a5a5782acc0',1,'IrrGame::HUD']]],
['getirrgameversion',['GetIrrGameVersion',['../classIrrGame_1_1Game.html#abd22d92d885496c95ccf12ba1ed803bd',1,'IrrGame::Game']]],
['getpath',['GetPath',['../classIrrGame_1_1FileStream.html#a0f00967548f7503127eeb732fc7ea02e',1,'IrrGame::FileStream']]],
['getstate',['GetState',['../classIrrGame_1_1Game.html#aa861b1b9effdb3f6071d26ce5233af2a',1,'IrrGame::Game']]],
['gettime',['GetTime',['../classIrrGame_1_1Timer.html#a724938c330e641c92fdc1fd54e6d4be9',1,'IrrGame::Timer']]]
];
<file_sep>/**
* @file World.cpp
* @author <NAME>
* @brief Definitions for a class that represents the world scene node.
* @see World
*/
#include "World.h"
namespace IrrGame
{
// Define constants
const std::string World::TEXTURE_PATH = "data/textures/";
const std::string World::MODEL_PATH = "data/models/";
const std::string World::NO_TEXTURE = TEXTURE_PATH + "notexture.bmp";
const vector3df World::ORIGIN = vector3df(0, 0, 0);
World::World()
{
scene = nullptr;
driver = nullptr;
}
World::~World()
{
// Class does not currently manage any resources.
}
World::World(ISceneManager* scene, IVideoDriver* driver, u32 width, u32 height, u32 depth, const vector3df& up)
{
this->scene = scene;
this->driver = driver;
// Add an animated mesh
IAnimatedMeshSceneNode* node = AddAnimatedMesh("Marvin.md2", "Marvin.jpg");
// Change some parameters of the added mesh node
if (node)
{
node->setMaterialFlag(EMF_LIGHTING, false);
node->setMD2Animation(scene::EMAT_RUN);
node->setAnimationSpeed(10);
}
// Initialize a camera
scene->addCameraSceneNodeFPS();
}
IAnimatedMeshSceneNode* World::AddAnimatedMesh(const std::string& modelFile, const std::string& textureFile, ISceneNode* parent, const vector3df& position,
const vector3df& rotation, const vector3df& scale)
{
// Create and add a mesh from the given file and texture
IAnimatedMesh* mesh = scene->getMesh((MODEL_PATH + modelFile).c_str());
if(!mesh)
{
Log("Error! Could not load model from \"" + MODEL_PATH + modelFile + "!\n");
return nullptr;
}
IAnimatedMeshSceneNode* node = scene->addAnimatedMeshSceneNode(mesh);
if(!node)
{
Log("Error! Failed to create node from mesh loaded from \"" + MODEL_PATH + modelFile + "!\n");
return nullptr;
}
ITexture* texture = driver->getTexture((TEXTURE_PATH + textureFile).c_str());
if(!texture)
Log("Error! Failed to load texture from file \"" + TEXTURE_PATH + textureFile + "!\n");
node->setMaterialTexture(0, texture);
return node;
}
IMeshSceneNode* World::AddMesh(IMesh* mesh, const std::string& textureFile)
{
// Create and add a mesh
if(!mesh)
{
Log("Error! no mesh passed into World::AddMesh!\n");
return nullptr;
}
IMeshSceneNode* node = scene->addMeshSceneNode(mesh);
if(!node)
{
Log("Error! Failed to create node mesh!\n");
return nullptr;
}
ITexture* texture = driver->getTexture((TEXTURE_PATH + textureFile).c_str());
if(!texture)
Log("Error! Failed to load texture from file \"" + TEXTURE_PATH + textureFile + "!\n");
node->setMaterialTexture(0, texture);
return node;
}
void World::Render()
{
scene->drawAll();
}
}
<file_sep>/**
* @file IrrEventHandler.cpp
* @author <NAME>
* @brief Definitions for keyboard input event handlers.
*/
#include "IrrEventHandler.h"
#include "IO.h"
namespace IrrGame
{
IrrEventHandler::IrrEventHandler()
{
inputState = nullptr;
}
IrrEventHandler::~IrrEventHandler()
{
if (inputState)
delete inputState;
}
void IrrEventHandler::RegisterInputState(InputState* inputState)
{
this->inputState = inputState;
}
bool IrrEventHandler::OnEvent(const SEvent& event)
{
if (event.EventType == irr::EET_KEY_INPUT_EVENT)
{
if (inputState)
{
if (event.KeyInput.PressedDown)
{
if (inputState->IsKeyUp(event.KeyInput.Key))
inputState->SetKey(event.KeyInput.Key, KeyState::Pressed);
else
inputState->SetKey(event.KeyInput.Key, KeyState::Down);
}
else
{
if (inputState->IsKeyDown(event.KeyInput.Key) || inputState->IsKeyPressed(event.KeyInput.Key))
inputState->SetKey(event.KeyInput.Key, KeyState::Released);
else
inputState->SetKey(event.KeyInput.Key, KeyState::Up);
}
}
else
Log("Error! Could not handle key press, no input state registered with event handler.");
}
if (event.EventType == irr::EET_MOUSE_INPUT_EVENT)
{
if (inputState)
{
switch (event.MouseInput.Event)
{
case EMIE_LMOUSE_PRESSED_DOWN:
if (inputState->IsMouseButtonUp(MouseButton::Left) || inputState->IsMouseButtonReleased(MouseButton::Left))
inputState->SetMouseButton(MouseButton::Left, MouseButtonState::Pressed);
else
inputState->SetMouseButton(MouseButton::Left, MouseButtonState::Down);
break;
case EMIE_LMOUSE_LEFT_UP:
inputState->SetMouseButton(MouseButton::Left, MouseButtonState::Up);
break;
case EMIE_RMOUSE_PRESSED_DOWN:
if (inputState->IsMouseButtonUp(MouseButton::Right) || inputState->IsMouseButtonReleased(MouseButton::Right))
inputState->SetMouseButton(MouseButton::Right, MouseButtonState::Pressed);
else
inputState->SetMouseButton(MouseButton::Right, MouseButtonState::Down);
break;
case EMIE_RMOUSE_LEFT_UP:
inputState->SetMouseButton(MouseButton::Right, MouseButtonState::Up);
break;
case EMIE_MOUSE_MOVED:
inputState->SetMousePosition(vector2di(event.MouseInput.X, event.MouseInput.Y));
break;
case EMIE_MOUSE_WHEEL:
inputState->SetMouseWheel(event.MouseInput.Wheel);
break;
}
}
else
Log("Error! Could not handle mouse input, no input state registered with event handler.");
}
return false;
}
KeyboardState::KeyboardState()
{
for (u32 i = 0; i < KEY_KEY_CODES_COUNT; i++)
keyStates[i] = KeyState::Up;
pressedKeys = std::vector<EKEY_CODE>();
releasedKeys = std::vector<EKEY_CODE>();
}
KeyboardState::~KeyboardState()
{
}
MouseState::MouseState()
{
position = vector2di(0, 0);
leftButton = MouseButtonState::Up;
rightButton = MouseButtonState::Up;
wheelDir = 0;
}
MouseState::~MouseState()
{
}
InputState::InputState()
{
keyboardState = KeyboardState();
mouseState = MouseState();
}
InputState::~InputState()
{
}
void InputState::SetKey(EKEY_CODE key, KeyState state)
{
keyboardState.keyStates[key] = state;
// Update vectors accordingly, more efficient than looping through all keys during flush
if (state == KeyState::Pressed)
keyboardState.pressedKeys.push_back(key);
else if (state == KeyState::Released)
keyboardState.releasedKeys.push_back(key);
}
void InputState::SetMouseButton(MouseButton button, MouseButtonState state)
{
if (button == MouseButton::Left)
mouseState.leftButton = state;
else if (button == MouseButton::Right)
mouseState.rightButton = state;
}
void InputState::SetMousePosition(vector2di position)
{
mouseState.position = position;
}
void InputState::SetMouseWheel(const f32& dir)
{
mouseState.wheelDir = dir;
}
void InputState::Flush()
{
for (auto i : keyboardState.pressedKeys) // Set all keys pressed on this frame to down
SetKey(i, KeyState::Down);
for (auto i : keyboardState.releasedKeys) // Set all keys released on this frame to up
SetKey(i, KeyState::Up);
// Reset mouse wheel
SetMouseWheel(0);
// Update mouse button states
if (mouseState.leftButton == MouseButtonState::Pressed)
SetMouseButton(MouseButton::Left, MouseButtonState::Down);
if (mouseState.rightButton == MouseButtonState::Released)
SetMouseButton(MouseButton::Right, MouseButtonState::Up);
// Clear vectors
keyboardState.releasedKeys.clear();
keyboardState.pressedKeys.clear();
}
bool InputState::IsKeyDown(EKEY_CODE keyCode) const
{
return (keyboardState.keyStates[keyCode] == KeyState::Down);
}
bool InputState::IsKeyUp(EKEY_CODE keyCode) const
{
return (keyboardState.keyStates[keyCode] == KeyState::Up);
}
bool InputState::IsKeyPressed(EKEY_CODE keyCode) const
{
return (keyboardState.keyStates[keyCode] == KeyState::Pressed);
}
bool InputState::IsKeyReleased(EKEY_CODE keyCode) const
{
return (keyboardState.keyStates[keyCode] == KeyState::Released);
}
bool InputState::IsMouseButtonDown(MouseButton button) const
{
switch (button)
{
case MouseButton::Left:
return (mouseState.leftButton == MouseButtonState::Down);
break;
case MouseButton::Right:
return (mouseState.rightButton == MouseButtonState::Down);
break;
default:
Log("Error! Checking state of unrecognized mouse button!");
break;
}
}
bool InputState::IsMouseButtonUp(MouseButton button) const
{
switch (button)
{
case MouseButton::Left:
return (mouseState.leftButton == MouseButtonState::Up);
break;
case MouseButton::Right:
return (mouseState.rightButton == MouseButtonState::Up);
break;
default:
Log("Error! Checking state of unrecognized mouse button!");
break;
}
}
bool InputState::IsMouseButtonReleased(MouseButton button) const
{
switch (button)
{
case MouseButton::Left:
return (mouseState.leftButton == MouseButtonState::Released);
break;
case MouseButton::Right:
return (mouseState.rightButton == MouseButtonState::Released);
break;
default:
Log("Error! Checking state of unrecognized mouse button!");
break;
}
}
bool InputState::IsMouseButtonPressed(MouseButton button) const
{
switch (button)
{
case MouseButton::Left:
return (mouseState.leftButton == MouseButtonState::Pressed);
break;
case MouseButton::Right:
return (mouseState.rightButton == MouseButtonState::Pressed);
break;
default:
Log("Error! Checking state of unrecognized mouse button!");
break;
}
}
f32 InputState::MouseWheel() const
{
return mouseState.wheelDir;
}
}<file_sep>var searchData=
[
['mousestate',['MouseState',['../classIrrGame_1_1MouseState.html',1,'IrrGame']]]
];
|
3fd8e3a221c731d6f4601c66503b4c21b4c19e78
|
[
"JavaScript",
"Makefile",
"C++",
"Markdown"
] | 59
|
JavaScript
|
hkeeble/IrrGame
|
31cf9cf6960da390276bb3170acd64f2ac84d613
|
021acccc448fc3466e771e71986d8999fae7a4dd
|
refs/heads/main
|
<repo_name>fahmisajid/klasifikasiemosi<file_sep>/project.py
import pandas as pd
import numpy as np
import re
import string
import nltk
import streamlit as st
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import confusion_matrix
from sklearn.model_selection import cross_val_predict
from sklearn.metrics import classification_report
#from gensim.models import Word2Vec, KeyedVectors
st.title("Emotion Classification")
df = pd.read_csv('Twitter_Emotion_Datasetab.csv')
text = df['tweet']
y = df['label'].values
count_vect = CountVectorizer()
X_count = count_vect.fit_transform(text)
tfidf_transformer = TfidfTransformer()
X_tfidf = tfidf_transformer.fit_transform(X_count)
classifier = LogisticRegression(multi_class='multinomial', penalty='l2', solver='newton-cg', C= 1.623776739188721)
classifier.fit(X_tfidf, y)
sentence = st.text_input('Input your sentence here:')
text_new =[sentence]
X_new_counts = count_vect.transform(text_new)
X_new_tfidf = tfidf_transformer.transform(X_new_counts)
prediction = classifier.predict(X_new_tfidf)
prediction_proba = classifier.predict_proba(X_new_tfidf)
if sentence:
st.write(prediction[0])
st.subheader('Class labels and index number')
st.write(classifier.classes_)
st.subheader('Prediction Probability')
st.write(prediction_proba)
|
467b6d82be2b5077d8360df14e66192688cf5257
|
[
"Python"
] | 1
|
Python
|
fahmisajid/klasifikasiemosi
|
f65b85c959a4031160c4711af70fa2578ce5dcf9
|
5561cf1381d37338d4efe3f9362430bd9cb3e2f6
|
refs/heads/master
|
<file_sep>import React from 'react';
import { expect } from 'chai';
import { render } from 'enzyme';
import Button from './ActionButton';
describe('<ActionButton />', () => {
it('has a .button classname', () => {
const wrapper = render(<Button/>);
expect(wrapper.find('.button').length).to.equal(1);
});
it('has [status] attribute', () => {
const wrapper = render(<Button />);
expect(wrapper.find('[status]').length).to.equal(1);
});
it('displays the text prop', () => {
const wrapper = render(<Button text="BOOK" />);
expect( wrapper.text() ).to.contain('BOOK');
});
});<file_sep>import React from "react";
const ActionButton = props => (
<button className={`${props.active} ${props.state}`}>
<span className="btn-txt">{props.text}</span>
</button>
);
export default ActionButton;
<file_sep>
## Importance of testing in Software development & How to test your react components?
> Tests says "I am Important" but developer says "I do not want to use a framework with lot of dependencies"
### Do we really test?

### We just love the "IDEA OF TESTING"
We started with, Jasmine-based stack, we’ve adopted a testing stack consisting of Mocha as our test runner, Chai for assertions, and Enzyme for asserting on component output. But than it created like too much dependency. lot of effort. Then we tried Jest and it very cool and works with less effort & writing more of test cases.
One day We just gave a shot to what it would take to migrate all of out test cases to jest. And yes the transition was very simple. And we had removed several dependencies from our code base.
But most importantly it mean set that everytime we hire someone new, they wouldn’t have to thunk about these dependencies, but they will just be thinking about these single dependencies.That means it reduces a lot of overhead that comes whenever we are hiring someone new.
After we migrated to jest running a single test case took almost from 5 seconds to instant run, which means our feed back loop was very tighted which means we ended up writing more test cases.
###### Demo time!!!!

Jest snapshot makes it very simple to test your react components.
```javascript
import React from 'react';
import renderer from 'react-test-renderer';
import ActionButton from '../ActionButton';
test('<Button /> renders with text as prop', () => {
const tree = renderer.create(
<ActionButton text="BOOK" state="disabled" active="button-active"/>
).toJSON();
expect(tree).toMatchSnapshot();
});
```
##### The same tests in chai would actually end up writing too many describes. Also you would manually update your test case once you updated your component.
###### Test with chai & enzyme
```javascript
import React from 'react';
import { expect } from 'chai';
import { render } from 'enzyme';
import Button from './ActionButton';
describe('<ActionButton />', () => {
it('has a .button classname', () => {
const wrapper = render(<Button/>);
expect(wrapper.find('.button').length).to.equal(1);
});
it('has [status] attribute', () => {
const wrapper = render(<Button />);
expect(wrapper.find('[status]').length).to.equal(1);
});
it('displays the text prop', () => {
const wrapper = render(<Button text="BOOK" />);
expect( wrapper.text() ).to.contain('BOOK');
});
});
```
-----------------------
###### Steps to run your tests
To run the test
`npm run test`
To update snapshot
`jest --updateSnapshot`
The idea is quite similar to the UI snapshot tests some of you may know: You take an image of your current app in a specified state and compare it to the previous image you have taken. The problem if you use actual images is that they are big, contain a lot of unused information, depend on your (maybe changing) environment (e.g. browser size). Because of these problems, they feel heavy, the tests take a time to complete and may occasionally fail for no reason. The way Jest improves this situation is that it uses a test renderer to render your React or React Native components to a JSON representation. This representation is stored with the new snapshot feature and may be diffed against new test runs results.
Links to slides http://slides.com/manjuladube/w#/
|
0996624fb859214266f277b867438f4df447df25
|
[
"JavaScript",
"Markdown"
] | 3
|
JavaScript
|
sarveshpro/Testing-React-components
|
b357791d70a0642bf2763e2cbe286b69bf051fb9
|
3313fe9aea01a1708b713015c254eeccf2e120d3
|
refs/heads/main
|
<file_sep>from math import sqrt, sin
def right_square(a, x, func):
return (x - a) * eval(func)
a = int(input('Введіть а: '))
b = int(input("Введіть b: "))
s = right_square(a, 3, "sqrt((4 * x) + sin(sqrt(x ** 3)))") + right_square(a, b, "sqrt((4 * x) + sin(sqrt(x ** 3)))")
print("S = ", s)<file_sep>def count_x(id = 10):
if id == 0:
return 1
else:
return count_x(id - 1) + 2 * id
print(count_x())<file_sep># lab8
Лабораторна робота №8 Когутки Михайла
<file_sep>def sum_func(num):
sum = 0
for i in range(1,6):
sum += num ** i
return sum
def prod_func(num):
prod = 1
for i in range(1,6):
prod *= num ** i
return prod
def mfunc(x):
if x > 0:
return sum_func(x)
else:
return prod_func(x)
if __name__ == "__main__":
a = float(input("Введіть а: "))
b = float(input("Введіть b: "))
u = mfunc(a) + mfunc(2) + mfunc(b)
print("U = ", u)
|
81aee2c84d4820868cd047c0888f810a552b8bc6
|
[
"Markdown",
"Python"
] | 4
|
Python
|
merlin93289528/lab8
|
2526cf2fa205d1b977998e9e352056935f0cd1d4
|
cb6f8b427541c52d1100f6191a7bfde0e92d0bbf
|
refs/heads/master
|
<repo_name>harshasanjeeva/testbackend<file_sep>/todo-routes.js
var express = require('express');
var app = module.exports = express.Router();
var Todo = require('./todo');
app.get('/todos', function(req, res){
Todo.find({}, function(err, todos){
if(err){
return res.json({"success":false, "msg":"Error", "error":err});
}
res.status(200).send({"success":true, "result":todos})
});
});
app.post('/todos', function(req, res){
if(!req.body.text){
return res.status(400).send({"success":false, "msg":"Error", "error":err});
}
var newTodo = new Todo({
text: req.body.text
});
newTodo.save(function(err){
if (err){
console.log("error",err);
return res.json({"success":false, "msg":"Error", "error":err});
}
res.status(201).send({"success":true, "msg":'Succesfully created new TODO'});
});
});
|
218b95e473f2514978290818b7141630320eaa86
|
[
"JavaScript"
] | 1
|
JavaScript
|
harshasanjeeva/testbackend
|
fddb15ad66255e9a14e327ea59c7ebcd818521f3
|
6862c2995dffcc2b5e02b03a21898d0fb245da48
|
refs/heads/master
|
<repo_name>studiowbe/laravel-form<file_sep>/src/Form.php
<?php
namespace Studiow\Form;
use Collective\Html\FormFacade;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
use Studiow\Form\Contracts\Renderable;
use Studiow\Form\Support\Behaviour\CollectsButtons;
use Studiow\Form\Support\Behaviour\CollectsFields;
use Studiow\Form\Support\Behaviour\HasAttributes;
class Form implements Renderable
{
use CollectsFields, CollectsButtons, HasAttributes;
private $model;
protected $view;
public function __construct(array $fields = [], array $buttons = [], array $attributes = [])
{
array_map([$this, 'addField'], $fields);
array_map([$this, 'addButton'], $buttons);
$this->attributes = new Collection($attributes);
}
public function bind(?Model $model = null)
{
$this->model = $model;
return $this;
}
public function open(): string
{
if (! is_null($this->model)) {
return FormFacade::model($this->model, $this->attributes());
}
return FormFacade::open($this->attributes());
}
public function close()
{
return FormFacade::close();
}
public function getView(): string
{
return $this->view ?? 'form::form';
}
protected function getViewData(): array
{
return ['form' => $this];
}
public function render(array $options = []): string
{
return view($this->getView(), $this->getViewData())->with($options);
}
}
<file_sep>/src/Elements/Button.php
<?php
namespace Studiow\Form\Elements;
use Collective\Html\FormFacade;
use Illuminate\Support\Collection;
use Studiow\Form\Contracts\HasId;
use Studiow\Form\Contracts\Renderable;
use Studiow\Form\Support\Behaviour\HasAttributes;
class Button implements HasId, Renderable
{
use HasAttributes;
private $id;
private $label;
public function __construct(string $id, string $label, array $attributes = [])
{
$this->id = $id;
$this->label = $label;
$this->attributes = new Collection($attributes);
$this->set('type', $this->get('type', 'submit'));
}
public function getId(): string
{
return $this->id;
}
public function label(string $label)
{
$this->label = $label;
return $this;
}
public function primary(bool $isPrimary = true)
{
if ($isPrimary) {
$this->addClass('btn-primary');
} else {
$this->removeClass('btn-primary');
}
return $this;
}
public function submit(bool $isSubmit = true)
{
$this->set('type', $isSubmit ? 'submit' : 'button');
return $this;
}
public function render(array $options = []): string
{
return FormFacade::button($this->label, $this->attributes());
}
public static function create(string $id, string $label, array $attributes = [])
{
return new static($id, $label, $attributes);
}
}
<file_sep>/src/Contracts/Renderable.php
<?php
namespace Studiow\Form\Contracts;
interface Renderable
{
public function render(array $options = []): string;
}
<file_sep>/src/Elements/Hidden.php
<?php
namespace Studiow\Form\Elements;
use Collective\Html\FormFacade;
use Studiow\Form\Contracts\Field;
class Hidden implements Field
{
private $id;
private $value;
public function __construct(string $id, string $value = null)
{
$this->id = $id;
$this->value = $value;
}
public function getId(): string
{
return $this->id;
}
public function render(array $options = []): string
{
return sprintf('<input type="hidden" name="%s" value="%s">',$this->id, $this->value);
}
public static function create(string $id, string $value = null)
{
return new static($id, $value);
}
}
<file_sep>/tests/DumpTest.php
<?php
namespace Studiow\Form\Test;
use Collective\Html\HtmlServiceProvider;
use Orchestra\Testbench\TestCase;
use Studiow\Form\Elements\Button;
use Studiow\Form\Elements\Date;
use Studiow\Form\Elements\Email;
use Studiow\Form\Elements\Hidden;
use Studiow\Form\Elements\Number;
use Studiow\Form\Elements\Text;
use Studiow\Form\Form;
use Studiow\Form\FormServiceProvider;
class DumpTest extends TestCase
{
protected function getPackageProviders($app)
{
return [
HtmlServiceProvider::class,
FormServiceProvider::class,
];
}
public function testDump()
{
app('view')->addLocation(__DIR__.'/../views');
$form = new Form(
[
new Text('name', 'Name'),
// Hidden::create('a', 'b') ,
Email::create('email', 'E-mail')->value('test'),
], [
new Button('save', 'Save'),
]);
echo $form->set('class', 'form')->render();
}
}
<file_sep>/src/Elements/Textarea.php
<?php
namespace Studiow\Form\Elements;
class Textarea extends FormControl
{
}
<file_sep>/src/Support/Label.php
<?php
namespace Studiow\Form\Support;
use Illuminate\Support\Collection;
use Studiow\Form\Contracts\HasId;
use Studiow\Form\Support\Behaviour\HasAttributes;
class Label
{
use HasAttributes;
private $field;
private $label;
public function __construct(HasId $field, string $label, array $attributes = [])
{
$this->field = $field;
$this->attributes = new Collection($attributes);
$this->setLabel($label);
}
public function setLabel(string $label)
{
$this->label = $label;
return $this;
}
public function getLabel()
{
return $this->label;
}
}
<file_sep>/src/FormServiceProvider.php
<?php
namespace Studiow\Form;
use Illuminate\Support\ServiceProvider;
class FormServiceProvider extends ServiceProvider
{
public function boot()
{
$this->loadViewsFrom(__DIR__.'/../views', 'form');
}
}
<file_sep>/src/Elements/FormControl.php
<?php
namespace Studiow\Form\Elements;
use Studiow\Form\Contracts\FormControl as FormControlInterface;
use Studiow\Form\Support\Control;
use Studiow\Form\Support\Label;
use Studiow\Form\Support\Wrapper;
abstract class FormControl implements FormControlInterface
{
private $id;
private $label;
private $control;
private $wrapper;
private $value;
protected $view;
public function __construct(string $id, string $label)
{
$this->id = $id;
$this->label = new Label($this, $label);
$this->control = new Control($this);
$this->wrapper = new Wrapper(['class' => 'form-'.$this->type()]);
}
private function type(): string
{
$classname = get_called_class();
return strtolower(substr($classname, strrpos($classname, '\\') + 1));
}
public function getId(): string
{
return $this->id;
}
public function value($value)
{
$this->value = $value;
return $this;
}
public function getValue()
{
return $this->value;
}
public function label(?string $newLabel = null): Label
{
if (! is_null($newLabel)) {
$this->label->setLabel($newLabel);
}
return $this->label;
}
public function control(): Control
{
return $this->control;
}
public function wrapper(): Wrapper
{
return $this->wrapper;
}
protected function getViewData(): array
{
return [
'id' => $this->getId(),
'control_id' => $this->getId(),
'value' => $this->getValue(),
'label' => $this->label()->getLabel(),
'control_attr' => $this->control()->attributes(),
'label_attr' => $this->label()->attributes(),
'wrapper_attr' => $this->wrapper()->attributes(),
];
}
protected function getView(): string
{
return $this->view ?? 'form::field.'.$this->type();
}
public function readonly(bool $isReadonly = true)
{
$this->control()->set('readonly', $isReadonly);
return $this;
}
public function render(array $options = []): string
{
return view($this->getView(), $this->getViewData())->with($options);
}
/**
* @param string $id
* @param string $label
*
* @return static
*/
public static function create(string $id, string $label)
{
return new static($id, $label);
}
}
<file_sep>/src/Elements/Panel.php
<?php
namespace Studiow\Form\Elements;
use Studiow\Form\Contracts\Field;
use Studiow\Form\Support\Behaviour\CollectsFields;
use Studiow\Form\Support\Behaviour\HasAttributes;
class Panel implements Field
{
use CollectsFields, HasAttributes;
private $id;
private $title;
private $description;
public function __construct(string $id, array $fields = [])
{
$this->id = $id;
array_map([$this, 'addField'], $fields);
}
public function getId(): string
{
return $this->id;
}
public function title(string $title)
{
$this->title = $title;
return $this;
}
public function description(string $description)
{
$this->description = $description;
return $this;
}
public function getTitle(): ?string
{
return $this->title;
}
public function getDescription(): ?string
{
return $this->description;
}
public function getView(): string
{
return $this->view ?? 'form::panel';
}
protected function getViewData(): array
{
return ['panel' => $this];
}
public function render(array $options = []): string
{
return view($this->getView(), $this->getViewData())->with($options);
}
/**
* @param string $id
* @param array $fields
*
* @return static
*/
public static function create(string $id, array $fields = [])
{
return new static($id, $fields);
}
}
<file_sep>/src/Elements/Text.php
<?php
namespace Studiow\Form\Elements;
class Text extends FormControl
{
}
<file_sep>/src/Support/Behaviour/HasAttributes.php
<?php
namespace Studiow\Form\Support\Behaviour;
use Illuminate\Support\Collection;
trait HasAttributes
{
/**
* @var Collection
*/
private $attributes;
protected $preventExport = [];
protected function getPreventExport(): array
{
return $this->preventExport;
}
protected function attributesCollection(): Collection
{
return $this->attributes = $this->attributes ?? new Collection();
}
public function set($attribute, $value = null)
{
if (is_array($attribute)) {
foreach ($attribute as $k => $v) {
$this->set($k, $v);
}
}
$this->attributesCollection()->offsetSet($attribute, $value);
return $this;
}
public function get(string $attribute, $default = null)
{
return $this->attributesCollection()->get($attribute, $default);
}
public function remove($attribute)
{
if (is_array($attribute)) {
array_map([$this, 'remove'], $attribute);
}
$this->attributesCollection()->offsetUnset($attribute);
return $this;
}
public function attributes(): array
{
return $this->attributesCollection()->except($this->getPreventExport())->all();
}
private function getClasses(): array
{
return explode(' ', $this->attributesCollection()->get('class', ''));
}
private function setClasses(array $classnames)
{
$this->attributesCollection()->offsetSet('class', implode(' ', array_unique($classnames)));
return $this;
}
public function addClass(string $classname)
{
$classes = $this->getClasses();
$classes[] = $classname;
return $this->setClasses($classes);
}
public function removeClass(string $classname)
{
$this->setClasses(
array_diff($this->getClasses(), [$classname])
);
}
}
<file_sep>/src/Elements/Select.php
<?php
namespace Studiow\Form\Elements;
class Select extends FormControl
{
private $options = [];
protected $view = 'form::field.select';
protected $wrapper_class = 'form-select';
public function __construct(string $id, string $label, array $options = [])
{
parent::__construct($id, $label);
$this->options($options);
}
public function options(array $options)
{
$this->options = $options;
return $this;
}
public function getOptions(): array
{
return $this->options;
}
protected function getViewData(): array
{
$data = parent::getViewData();
$data['options'] = $this->options;
return $data;
}
public static function create(string $id, string $label, array $options = [])
{
return new static($id, $label, $options);
}
}
<file_sep>/src/Contracts/FormControl.php
<?php
namespace Studiow\Form\Contracts;
use Studiow\Form\Support\Control;
use Studiow\Form\Support\Label;
interface FormControl extends Field
{
public function label(?string $newLabel = null): Label;
public function control(): Control;
}
<file_sep>/src/Support/Behaviour/CollectsButtons.php
<?php
namespace Studiow\Form\Support\Behaviour;
use Studiow\Form\Elements\Button;
trait CollectsButtons
{
protected $buttons = [];
public function addButton(Button $button)
{
$this->buttons[$button->getId()] = $button;
return $this;
}
public function hasButton(string $id): bool
{
return array_key_exists($id, $this->buttons);
}
public function button(string $id): ?Button
{
return $this->hasButton($id) ? $this->buttons[$id] : null;
}
public function buttons(): array
{
return $this->buttons;
}
}
<file_sep>/src/Elements/Number.php
<?php
namespace Studiow\Form\Elements;
class Number extends FormControl
{
public function max($maxValue)
{
$this->control()->set('max', $maxValue);
return $this;
}
public function min($minValue)
{
$this->control()->set('min', $minValue);
return $this;
}
public function step($step)
{
$this->control()->set('step', $step);
return $this;
}
}
<file_sep>/src/Elements/Email.php
<?php
namespace Studiow\Form\Elements;
class Email extends FormControl
{
}
<file_sep>/src/Elements/Password.php
<?php
namespace Studiow\Form\Elements;
class Password extends FormControl
{
}
<file_sep>/src/Support/Behaviour/CollectsFields.php
<?php
namespace Studiow\Form\Support\Behaviour;
use Studiow\Form\Contracts\Field;
trait CollectsFields
{
protected $fields = [];
public function addField(Field $field)
{
$this->fields[$field->getId()] = $field;
return $this;
}
public function hasField(string $id): bool
{
return array_key_exists($id, $this->fields);
}
public function field(string $id): ?Field
{
return $this->hasField($id) ? $this->fields[$id] : null;
}
public function fields(): array
{
return $this->fields;
}
}
<file_sep>/src/Elements/Date.php
<?php
namespace Studiow\Form\Elements;
use DateTimeInterface;
class Date extends FormControl
{
public function max(?DateTimeInterface $maxValue = null)
{
$this->control()->set(
'max', is_null($maxValue) ? null : $maxValue->format('Y-m-d')
);
return $this;
}
public function min(?DateTimeInterface $minValue = null)
{
$this->control()->set(
'min', is_null($minValue) ? null : $minValue->format('Y-m-d')
);
return $this;
}
}
<file_sep>/src/Elements/Behaviour/HasMaxMin.php
<?php
namespace Studiow\Form\Elements\Behaviour;
trait HasMaxMin
{
public function min($minValue)
{
$this->control()->set('max', $minValue);
}
public function max($maxValue)
{
$this->control()->set('max', $maxValue);
}
}
<file_sep>/src/Contracts/Field.php
<?php
namespace Studiow\Form\Contracts;
interface Field extends HasId, Renderable
{
}
<file_sep>/src/Support/Control.php
<?php
namespace Studiow\Form\Support;
use Illuminate\Support\Collection;
use Studiow\Form\Contracts\HasId;
use Studiow\Form\Support\Behaviour\HasAttributes;
class Control
{
use HasAttributes;
public function __construct(HasId $field, array $attributes = [])
{
$this->field = $field;
$this->attributes = new Collection($attributes);
}
}
<file_sep>/src/Support/Wrapper.php
<?php
namespace Studiow\Form\Support;
use Illuminate\Support\Collection;
use Studiow\Form\Support\Behaviour\HasAttributes;
class Wrapper
{
use HasAttributes;
public function __construct(array $attributes = [])
{
$this->attributes = new Collection($attributes);
}
}
<file_sep>/src/Contracts/HasId.php
<?php
namespace Studiow\Form\Contracts;
interface HasId
{
public function getId(): string;
}
|
54de6d20791f45d63fdb634017fb830a2bbb389e
|
[
"PHP"
] | 25
|
PHP
|
studiowbe/laravel-form
|
073d164ca6d76f0aeb870cc5006fd7d4760571e5
|
da12433c211eb1b77370a4c603093c409ea42790
|
refs/heads/main
|
<repo_name>Lorenzo-Creativity/Wechat-Interest-Calculator<file_sep>/README.md
# Wechat-Interest-Calculator
利息计算器
本小程序在页面设计上采用四个输入框输入姓名,存入本金,利率和存储年限,一个提交点击按钮,点击按钮后获得利息和存储后总本金的数值。首先事件绑定上,在input输入组件中通过placeholder属性显示输入提示,再通过bindinput绑定输入事件处理函数;再bottom组件中通过bindtap绑定了点击事件函数,再点击提交后返回结果;最后在view组件中嵌套5个view组件来显示,其中一个view将其设为外层view,绑定{{flag}}来设置所有view是否显示,其他4个内层来显示其他信息。
接着是逻辑层的编写,在data中初始化了绑定的数据值,定义了事件函数获取输入的姓名,存入本金,利率和存储年限,在进行for循环利息和总本金计算,最后在用.toFixed(2)函数保留两位小数,再通过setData传到视图层显示出来。
以上为本小程序开发设计总结。
This applet uses four input boxes on the page design to input the name, deposit principal, interest rate and storage period. Click a submit button to obtain the value of interest and total principal after storage. Firstly, on the event binding, the input prompt is displayed through the placeholder attribute in the input component, and then the event handling function is input through the binding; In the bottom component, the click event function is bound through bindtap, and then click submit to return the result; Finally, five view components are nested in the view component to display. One view is set as the outer view, bound with {flag}} to set whether all views are displayed, and the other four inner layers to display other information.
Then the logic layer is written. The bound data value is initialized in data, and the event function is defined to obtain the input name, deposit principal, interest rate and storage years. The for circular interest and total principal are calculated. Finally, the. ToFixed (2) function is used to retain two decimal places, and then transmitted to the view layer through SetData for display.
The above is the summary of this applet development and design.
<file_sep>/电科-1-11-利息计算器/pages/index/index.js
/* index.js */
Page({
data: {
flag: true,
name: '',
principal: '',
interest_rate: '',
access_period: '',
interest:'',
Total_principal_after_deposit_and_withdrawal_period:''
},
nameInput: function (e) {
this.setData({
name: e.detail.value
});
},
principalInput: function (e) {
this.setData({
principal: e.detail.value
});
},
interest_rateInput: function (e) {
this.setData({
interest_rate: e.detail.value
});
},
access_periodInput: function (e) {
this.setData({
access_period: e.detail.value
});
},
mysubmit: function () {
var benjin =parseInt(this.data.principal);
var lilu = parseFloat(this.data.interest_rate);
var lixi = 0;
for(var i = 1;i <= this.data.access_period; i++ ){
lixi += benjin*lilu;
benjin = benjin + benjin*lilu;
}
benjin = benjin.toFixed(2);
lixi = lixi.toFixed(2);
this.setData({
Total_principal_after_deposit_and_withdrawal_period: benjin,
interest: lixi,
flag: false
});
}
}
)
|
a8a38fabe37789562e32401d287404a07352d273
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
Lorenzo-Creativity/Wechat-Interest-Calculator
|
e013dd73823ec63c0a1f6b1069e54291b88d5ca7
|
c577c6be42ff261ade02a569a6550487e3594c8a
|
refs/heads/master
|
<repo_name>techkuz/scala_clover<file_sep>/README.md
Homeworks done for the functional training course by <NAME> @ Clover group, Summer 2019
`$ sbt`
`$ compile`
`$ run`<file_sep>/src/main/python/lec4/simple.py
#
# Task 1: Write a simple Higher Order Function map(data, f), where f() is some arith function and data is a List, Dictionary and Numpy array.
# map(data, f) applies function f() to every element of the data structure and returns a resulting data structure.
#
# Can you make a single implementation, Overloaded for all those 3 data structures? Assume datatype is Int.
# Which algorithmic complexity O(n) should it be? Will it depend on the underlying data structure?
#
#
import numpy as np
import builtins
from typing import overload, List
class Data:
DEFAULT_INTS = 4, 6, 22, 3
def __init__(self):
self.list_data = [*self.DEFAULT_INTS]
self.dict_data = {index: default_int for index, default_int in enumerate(self.DEFAULT_INTS)}
self.np_data = np.array(self.DEFAULT_INTS)
@overload
def hof_func(data: list, operation: builtins = builtins.sum) -> List[int]:
...
@overload
def hof_func(data: dict, operation: builtins = builtins.sum) -> dict:
...
@overload
def hof_func(data: np.array, operation: builtins = builtins.sum) -> np.ndarray:
...
def hof_func(data, operation=sum):
if isinstance(data, list):
return list(map(operation, [data]))
elif isinstance(data, np.ndarray):
return np.array(list(map(operation, [data])))
elif isinstance(data, dict):
return dict(result=list(map(operation, [data.values()])))
def test_task_one():
data_obj = Data()
list_res = hof_func(data=data_obj.list_data)
dict_res = hof_func(data=data_obj.dict_data)
np_data_res = hof_func(data=data_obj.np_data)
print('list:', list_res)
print('dict:', dict_res)
print('np_arr:', np_data_res)
if __name__ == '__main__':
test_task_one()
# Task 2: Implement a speed optimized function for Task 1, the fastest you can. What algorithmic complexity O(n) should it be ?
|
c4f3ee2c54ce11295226f2e70bae7b226212308f
|
[
"Markdown",
"Python"
] | 2
|
Markdown
|
techkuz/scala_clover
|
edd8f684e948213191f358a161b391ee87700c68
|
4831429a8a3b147a2f7bbcfbcecaef4d30c44c09
|
refs/heads/master
|
<repo_name>saraespinosa/puzzle<file_sep>/README.md
# Hey :)
Check out the inspiration [repository](https://github.com/leobetosouza/JSNumberPuzzles)
Read the inspiration [discussion](https://www.facebook.com/groups/javascriptbrasil/permalink/328734297218270/) (pt-BR)
[C9 rocks!](https://c9.io/leocavalcante/puzzle)<file_sep>/puzzle.js
(function ( global, undefined ) {
"use strict";
var puzzle = {
fizzbuzz: function ( i, j ) {
if ( typeof j === 'undefined' ) {
return ( ( i % 3 ) ? '' : 'Fizz' ) + ( ( i % 5 ) ? '' : 'Buzz' ) || i;
} else {
var fb = [];
for ( ; i <= j; i++ )
fb.push( puzzle.fizzbuzz( i ) );
return fb;
}
}
};
global.exports ? global.exports = puzzle : global.puzzle = puzzle;
}( typeof window !== 'undefined' ? window : module ));<file_sep>/test/node.js
var puzzle = require( '../puzzle' ),
vows = require( 'vows' ),
assert = require( 'assert' );
vows.describe( 'fizzbuzz' ).addBatch({
'when the number is divisible by 3': {
topic: puzzle.fizzbuzz( 3 ),
'is Fizz': function ( topic ) {
assert.equal( topic, 'Fizz' );
}
},
'when the number is divisible by 5': {
topic: puzzle.fizzbuzz( 5 ),
'is Buzz': function ( topic ) {
assert.equal( topic, 'Buzz' );
}
},
'when the number is divisible by 3 and 5': {
topic: puzzle.fizzbuzz( 15 ),
'is FizzBuzz': function ( topic ) {
assert.equal( topic, 'FizzBuzz' );
}
},
'when the number is NOT divisible by 3 OR 5': {
topic: puzzle.fizzbuzz( 2 ),
'is it self': function ( topic ) {
assert.equal( topic, 2 );
}
},
'when there is two numbers': {
topic: puzzle.fizzbuzz( 1, 5 ),
'it is an array from i to j mapped to fizzbuzz': function ( topic ) {
assert.equal( topic.length, 5 );
assert.equal( JSON.stringify( topic ), JSON.stringify( [1, 2, 'Fizz', 4, 'Buzz'] ) );
}
}
}).run();
|
e6aa63db0e741830fb49156175a4e15c6d8b4db0
|
[
"Markdown",
"JavaScript"
] | 3
|
Markdown
|
saraespinosa/puzzle
|
24529bc95832fb9b99811177ec665cc60c39017e
|
7e5b02805a2eed382c62814b50a2cfb671120df3
|
refs/heads/master
|
<repo_name>RickiestRick/VirtualBlackboard<file_sep>/src/VirtualBlackboard/Views/DragableSheetUserControll.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace VirtualBlackboard.Views
{
/// <summary>
/// Interaktionslogik für DragableSheetUserControll.xaml
/// </summary>
public partial class DragableSheetUserControll : UserControl
{
private bool _isMoving;
private Point? _buttonPosition;
private static int index = 55;
private double deltaX;
private double deltaY;
private TranslateTransform _currentTT;
public static UniformGrid MyGrid;
public DragableSheetUserControll()
{
InitializeComponent();
index++;
}
private void Samplebutton_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
if (_buttonPosition == null)
_buttonPosition = ((UserControl)sender).TransformToAncestor(MyGrid).Transform(new Point(0, 0));
var mousePosition = Mouse.GetPosition(MyGrid);
deltaX = mousePosition.X - _buttonPosition.Value.X;
deltaY = mousePosition.Y - _buttonPosition.Value.Y;
MyBorder.BorderBrush = new SolidColorBrush(Color.FromRgb(81, 81, 81));
_isMoving = true;
Grid.SetZIndex(this, index++);
Panel.SetZIndex(this, 666);
UniformGrid.SetZIndex(this, index++);
}
private void Samplebutton_PreviewMouseUp(object sender, MouseButtonEventArgs e)
{
_currentTT = ((UserControl)sender).RenderTransform as TranslateTransform;
_isMoving = false;
MyBorder.BorderBrush = new SolidColorBrush(Color.FromRgb(0, 0, 0));
}
private void Samplebutton_PreviewMouseMove(object sender, MouseEventArgs e)
{
if (!_isMoving) return;
var mousePoint = Mouse.GetPosition(MyGrid);
var offsetX = (_currentTT == null ? _buttonPosition.Value.X : _buttonPosition.Value.X - _currentTT.X) + deltaX - mousePoint.X;
var offsetY = (_currentTT == null ? _buttonPosition.Value.Y : _buttonPosition.Value.Y - _currentTT.Y) + deltaY - mousePoint.Y;
((UserControl)sender).RenderTransform = new TranslateTransform(-offsetX, -offsetY);
}
private void UserControl_MouseLeave(object sender, MouseEventArgs e)
{
_currentTT = ((UserControl)sender).RenderTransform as TranslateTransform;
_isMoving = false;
MyBorder.BorderBrush = new SolidColorBrush(Color.FromRgb(0, 0, 0));
}
}
}
<file_sep>/README.md
# VirtualBlackboard
The VirtualBlackboard project is a small standalone Application developed in C# witht the GUI Framework WPF. It provides a simple "blackboard" for creating such called "sheets". Sheets can be dragged with the mouse - and can be turned arround with a double click.

## Features
* Drag and Drop "Sheets"
* Turn sheets arround
* Create/Delete Sheets
* Multilanguage-Support (DE/EN)
## Future Features
* Change background of VirtualBlackboard
* Edit Sheets
* Borderless Fullscreen
* Import/Export
<file_sep>/src/VirtualBlackboard/Model/Sheet.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace VirtualBlackboard.Model
{
[Serializable]
public class Sheet
{
public string DisplayText { get; set; }
}
}
<file_sep>/src/VirtualBlackboard/Views/WelcomeScreenUserControl.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace VirtualBlackboard.Views
{
/// <summary>
/// Interaktionslogik für WelcomeScreenUserControl.xaml
/// </summary>
public partial class WelcomeScreenUserControl : UserControl
{
public WelcomeScreenUserControl()
{
InitializeComponent();
}
private void MenuItem_ContextMenuOpening(object sender, ContextMenuEventArgs e)
{
var grid = sender as Grid;
var cont = grid.ContextMenu;
var proj = (cont.Items[0] as MenuItem).CommandParameter;
(cont.Items[0] as MenuItem).DataContext = WelcomeScreenUC.DataContext;
(cont.Items[0] as MenuItem).CommandParameter = grid.DataContext;
}
}
}
<file_sep>/src/VirtualBlackboard/ViewModel/WelcomeScreenViewModel.cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using VirtualBlackboard.Helpers;
using VirtualBlackboard.Model;
using VirtualBlackboard.Services;
namespace VirtualBlackboard.ViewModel
{
public class WelcomeScreenViewModel : ViewModelBase
{
private ProjectDataProvider _sheetDataProviderService;
public ICollection<Project> AllSheetCollections { get; }
public ICommand DoubleClickCommand { get; set; }
public ICommand DeleteCommand { get; set; }
public WelcomeScreenViewModel()
{
AllSheetCollections = new ObservableCollection<Project>();
_sheetDataProviderService = new ProjectDataProvider();
var sheets=_sheetDataProviderService.GetAllSheets();
sheets.ToList().ForEach(x => AllSheetCollections.Add(x));
DoubleClickCommand = new RelayCommand<Project>(DoubleClick);
DeleteCommand = new RelayCommand<Project>(Delete);
//the last Entry :)
AllSheetCollections.Add(new Project() { DisplayText = Properties.Resources.New_Project });
}
private void Delete(Project obj)
{
_sheetDataProviderService.Delete(obj);
var sheets = _sheetDataProviderService.GetAllSheets();
AllSheetCollections.Clear();
sheets.ToList().ForEach(x => AllSheetCollections.Add(x));
AllSheetCollections.Add(new Project() { DisplayText = Properties.Resources.New_Project });
}
private void DoubleClick(Project obj)
{
if(obj.DisplayText == Properties.Resources.New_Project)
{
Messenger.Trigger("LoadCreateNewProject",null);
}
else
Messenger.Trigger("LoadBlackboard", obj.Sheets);
}
}
}
<file_sep>/src/VirtualBlackboard/ViewModel/CreateNewProjectViewModel.cs
using MahApps.Metro.Controls.Dialogs;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using VirtualBlackboard.Helpers;
using VirtualBlackboard.Model;
using VirtualBlackboard.Services;
namespace VirtualBlackboard.ViewModel
{
public class CreateNewProjectViewModel
{
private Services.ProjectDataProvider _projectDataProvider;
public CreateNewProjectViewModel()
{
Sheets = new ObservableCollection<Sheet>();
CreateCommand = new RelayCommand<object>(CreateProject);
_projectDataProvider = new Services.ProjectDataProvider();
}
public ICollection<Sheet> Sheets { get; set; }
public string ProjectName { get; set; }
public ICommand CreateCommand { get; set; }
public void CreateProject(object obj)
{
var dia = DialogCoordinator.Instance;
if(ProjectName == null || ProjectName==string.Empty)
{
dia.ShowMessageAsync(this, "Warnung", "Projekt Name darf nicht leer sein!");
return;
}
if(File.Exists(Environment.CurrentDirectory + @"\Projects\" + ProjectName))
{
dia.ShowMessageAsync(this, "Warnung", "Projekt bereits vorhanden!");
return;
}
if(Sheets.Any() == false)
{
dia.ShowMessageAsync(this, "Warnung", "Mindestens ein Eintrag muss vorhanden sein!");
return;
}
Project proj = new Project();
proj.DisplayText = ProjectName;
proj.Filepath = Environment.CurrentDirectory + @"\Projects\" + ProjectName;
proj.Sheets = Sheets;
_projectDataProvider.Serialize(proj);
Messenger.Trigger("LoadWelcomeScreen", null);
}
}
}
<file_sep>/src/VirtualBlackboard/ViewModel/MainViewModel.cs
using System;
using System.Collections.Generic;
using System.Windows.Controls;
using System.Windows.Input;
using VirtualBlackboard.Helpers;
using VirtualBlackboard.Model;
using VirtualBlackboard.Services;
using VirtualBlackboard.Views;
namespace VirtualBlackboard.ViewModel
{
public class MainViewModel : ViewModelBase
{
public ICommand HomeCommand { get; set; }
public UserControl ActualContent { get; set; }
public MainViewModel()
{
Messenger.Register("LoadWelcomeScreen", LoadWelcomeScreen);
Messenger.Register("LoadCreateNewProject", LoadCreateNewProject);
Messenger.Register("LoadBlackboard", LoadBlackboard);
HomeCommand = new RelayCommand<object>(x => LoadWelcomeScreen(x));
ActualContent = new WelcomeScreenUserControl();
}
private void LoadBlackboard(object obj)
{
var b = new MainBlackboard();
b.DataContext = new MainBlackboardViewModel(obj as ICollection<Sheet>);
ActualContent = b;
RaisePropertyChanged("ActualContent");
}
private void LoadCreateNewProject(object obj)
{
ActualContent = new CreateNewProjectUserControll();
RaisePropertyChanged("ActualContent");
}
private void LoadWelcomeScreen(object obj)
{
ActualContent = new WelcomeScreenUserControl();
RaisePropertyChanged("ActualContent");
}
}
}
<file_sep>/src/VirtualBlackboard/Services/Messenger.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace VirtualBlackboard.Services
{
public static class Messenger
{
private static List<MessengerObject> registrations = new List<MessengerObject>();
public static void Register(string Key, Action<object> Method)
{
registrations.Add(new MessengerObject(Key, Method));
}
public static void Trigger(string Key, object obj)
{
foreach (var item in registrations)
{
if (item.Key == Key)
item.Method.Invoke(obj);
}
}
class MessengerObject
{
public MessengerObject(string key, Action<object> method)
{
Key = key;
Method = method;
}
public string Key { get; set; }
public Action<object> Method { get; set; }
}
}
}
<file_sep>/src/VirtualBlackboard/Services/SheetDataProviderService.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;
using VirtualBlackboard.Model;
namespace VirtualBlackboard.Services
{
public class ProjectDataProvider
{
public const string ROOTPATH = "Projects";
public ProjectDataProvider()
{
if (!Directory.Exists(ROOTPATH))
{
Directory.CreateDirectory(ROOTPATH);
}
}
public ICollection<Project> GetAllSheets()
{
var myprojs = new List<Project>();
foreach (var item in Directory.GetFiles(ROOTPATH))
{
myprojs.Add(Deserialize(item));
}
return myprojs;
}
public Project Deserialize(string filename)
{
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read);
Project obj = (Project)formatter.Deserialize(stream);
stream.Close();
return obj;
}
public void Serialize(Project proj)
{
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream(proj.Filepath, FileMode.Create, FileAccess.Write, FileShare.None);
formatter.Serialize(stream, proj);
stream.Close();
}
public void Delete(Project proj)
{
File.Delete(proj.Filepath);
}
}
}
<file_sep>/src/VirtualBlackboard/ViewModel/MainBlackboardViewModel.cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using VirtualBlackboard.Helpers;
using VirtualBlackboard.Model;
namespace VirtualBlackboard.ViewModel
{
public class MainBlackboardViewModel : ViewModelBase
{
public ICommand RefreshCommand { get; set; }
public MainBlackboardViewModel(ICollection<Sheet> sheetCollection)
{
SheetCollection = new ObservableCollection<Sheet>();
sheetCollection.ToList().ForEach(x => SheetCollection.Add(x));
RefreshCommand = new RelayCommand<object>(Refresh);
}
private void Refresh(object obj)
{
var l = new List<Sheet>();
SheetCollection.ToList().ForEach(x => l.Add(x));
SheetCollection.Clear();
l.ToList().ForEach(x => SheetCollection.Add(x));
RaisePropertyChanged("SheetCollection");
}
public ObservableCollection<Sheet> SheetCollection { get; }
}
}
<file_sep>/src/VirtualBlackboard/Model/Project.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace VirtualBlackboard.Model
{
[Serializable]
public class Project
{
public string Filepath { get; set; }
public string DisplayText { get; set; }
public ICollection<Sheet> Sheets { get; set; }
}
}
|
9a24c2192970fec40995868a7ce45e63ab9725da
|
[
"Markdown",
"C#"
] | 11
|
C#
|
RickiestRick/VirtualBlackboard
|
ff90dc5809159fdf856fd51983eab9661fbc0a2d
|
88c1600db6b9e376771c4b62b8c096b55d1a2c2b
|
refs/heads/main
|
<repo_name>shariarbd/Bangladesh-district-list-in-php-array<file_sep>/bd_location.php
<?php
//Array of All District of Bangladesh
$bd_location_array = [
'barisal' => explode(', ', 'barisal, bhola, jhalokati, patuakhali, pirojpur'),
'chittagong' => explode(', ', 'bandarban, brahmanbaria, chandpur, chittagong, comilla, cox\'s bazar, feni, khagrachhari, lakshmipur, noakhali, rangamati'),
'dhaka' => explode(', ', 'dhaka, gazipur, narsingdi, manikganj, munshiganj, narayanganj, mymensingh, sherpur, jamalpur, netrokona, kishoreganj, tangail, faridpur, maradipur, shariatpur, rajbari, gopalganj'),
'khulna' => explode(', ', 'bagerhat, chuadanga, jessore, jhenaidaha, khulna, kushtia, magura, meherpur, narail, satkhira'),
'rajshahi' => explode(', ', 'bogra, joypurhat, naogaon, natore, nawabganj, pabna, rajshahi, sirajganj'),
'rangpur' => explode(', ', 'dinajpur, gaibandha, kurigram, lalmonirhat, nilphamari, panchagarh, rangpur, thakurgaon'),
'sylhet' => explode(', ', 'habiganj, maulvi bazar, sunamganj, sylhet'),
];
//Get Division as option list
function get_division_option($array) {
echo "<option>Select Division</option>\n";
foreach ($array as $div => $divDist) {
echo "<option value='".$div."'>".ucfirst($div)."</option>\n";
}
}
// Call the funcion to get Division as option list
// get_division_option($bd_location_array);
//Get District Option list based on Division
function get_dist_option($array){
echo "<option>Select District</option>\n";
foreach ($array as $dist => $index) {
echo "<option value='".$index."'>".ucfirst($index)."</option>\n";
}
}
// Call the funcion to get District as option list
// get_division_option($bd_location_array['dhaka']);
<file_sep>/README.md
Bangladesh District List Array
====================
If you plan to create a zone-based application for Bangladesh, this PHP array could help you a bit.
# Bangladesh-district-list-in-php-array
Bangladesh District List Division wise in a single php array
|
ce1bb289c97f9405027fe19c4814de492520a897
|
[
"Markdown",
"PHP"
] | 2
|
PHP
|
shariarbd/Bangladesh-district-list-in-php-array
|
8e932876745ffdc8805b0fc201faa1a434f25add
|
b33478577f91832893bd03e64e9a538e95aeef92
|
refs/heads/master
|
<repo_name>wangyouan/CEPR_Data<file_sep>/source_code/constant.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Filename: constant
# @Date: 2017/6/3
# @Author: <NAME>
# @Email: <EMAIL>
import os
class Constants(object):
ROOT_PATH = r'D:\CEPR_Data_sort' if not hasattr(os, 'uname') else '/home/zigan/Documents/WangYouan/research/CEPR'
DATA_PATH = os.path.join(ROOT_PATH, 'data')
RESULT_PATH = os.path.join(ROOT_PATH, 'result')
TEMP_PATH = os.path.join(ROOT_PATH, 'temp')
if __name__ == '__main__':
c = Constants()
for i in [c.DATA_PATH, c.RESULT_PATH, c.TEMP_PATH]:
if not os.path.isdir(i):
os.makedirs(i)
<file_sep>/Constant/__init__.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Filename: __init__.py
# @Date: 2017/6/3
# @Author: <NAME>
# @Email: <EMAIL>
from .path_info import PathInfo
class Constant(PathInfo):
pass<file_sep>/Constant/path_info.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Filename: path_info
# @Date: 2017/6/3
# @Author: <NAME>
# @Email: <EMAIL>
import os
class PathInfo(object):
ROOT_PATH = r'D:\CEPR_Data_sort' if not hasattr(os, 'uname') else '/home/zigan/Documents/WangYouan/research/CEPR'
DATA_PATH = os.path.join(ROOT_PATH, 'data')
RESULT_PATH = os.path.join(ROOT_PATH, 'result')
TEMP_PATH = os.path.join(ROOT_PATH, 'temp')<file_sep>/sort_data/step1_merge_all_data.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Filename: step1_merge_all_data
# @Date: 2017/6/3
# @Author: <NAME>
# @Email: <EMAIL>
import os
import pandas as pd
from Constant import Constant as const
if __name__ == '__main__':
data_files = os.listdir(const.DATA_PATH)
data_dfs = []
for f in data_files:
print(f)
if not f.endswith('.dta'):
continue
data_dfs.append(
pd.read_stata(os.path.join(const.DATA_PATH, f), convert_categoricals=False, convert_missing=True))
df = pd.concat(data_dfs, ignore_index=True)
df.to_csv(os.path.join(const.RESULT_PATH, '20170603_merged_data.csv'), index=False)
df.to_pickle(os.path.join(const.RESULT_PATH, '20170603_merged_data.p'))
df.to_stata(os.path.join(const.RESULT_PATH, '20170603_merged_data.dta'))
|
2fa6b6c72507bddbc0d18a9d62daeb78b83ee97a
|
[
"Python"
] | 4
|
Python
|
wangyouan/CEPR_Data
|
1b35522d0304b653ac73f2abb5b8a79a91dacf45
|
044c8d3fd96a22ab120122d946f4683806643706
|
refs/heads/master
|
<repo_name>Funmungus/DigitalSlave<file_sep>/DigitalSlave.ino
/* Avoid reading non-grounded pins */
#define SLAVE_BUTTON_COUNT 12
/* Regular Serial may be taken by USB communication. */
#define SLAVE_SERIAL() Serial
/* Digital pin numbers to read from */
int _pins[] = {2, 3, 4, 5, 6, 7, 8, 9, 10, 14, 15, 16};
/* Current pin state, always same array length as _pins */
int _states[SLAVE_BUTTON_COUNT];
int _current_value = 0;
void setup() {
/* Slave writes serial to master. */
SLAVE_SERIAL().begin(9600);
for (int i = 0; i < SLAVE_BUTTON_COUNT; i++) {
pinMode(_pins[i], INPUT);
}
}
void loop() {
bool hasChanged = false;
int state = 0;
int curBit = 1;
size_t i = 0;
/* Iterate pins to read */
for (; i < SLAVE_BUTTON_COUNT; i++) {
state = digitalRead(_pins[i]);
if (state != _states[i]) {
if (!hasChanged)
hasChanged = true;
if (state)
_current_value |= curBit;
else
_current_value -= curBit;
_states[i] = state;
}
/* Move next bit for next pin */
curBit <<= 1;
}
/* If a value has changed, write bit values to master. */
if (hasChanged)
SLAVE_SERIAL().write((char *)(&_current_value), sizeof(_current_value));
delay(50);
}
|
9c9e5798f66f7ec4e29883aab2df4b278a5160fe
|
[
"C++"
] | 1
|
C++
|
Funmungus/DigitalSlave
|
9510f2c86acb2d4a5045426d11631a72fe172770
|
4474befe47821d551d545e7268c5b38390499dea
|
refs/heads/master
|
<file_sep><?php
/* This is the template for the footer */
$i = 0;
$output = "";
$footerTitle = get_post_meta(get_the_ID(), 'wpcf-footer-title', false);
$array = array_values($footerTitle);
?>
<footer>
<div class="container">
<div class="row">
<div class="col-12">
<div class="row">
<div class="col-12 col-md-4">
<h3><?php echo $array[0]; ?></h3>
<?php
$how_many_last_posts = 6;
$my_query = new WP_Query('post_type=machine&nopaging=1');
if ($my_query->have_posts()) {
echo "<ul>";
$counter = 1;
while ($my_query->have_posts() && $counter <= $how_many_last_posts) {
$my_query->the_post();
?>
<li><a href="<?php the_permalink(); ?>" rel="bookmark" title="Permanent link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></li>
<?php
$counter++;
}
echo "</ul>";
wp_reset_postdata();
}
?>
</div>
<div class="col-12 col-md-4">
<h3 class="mt-4 mt-md-0"><?php echo $array[1]; ?></h3>
<?php
$contacts = get_post_meta(get_the_ID(), 'wpcf-contact-info', false);
foreach($contacts as $value) :
?>
<p><?= $value; ?></p>
<?php endforeach; ?>
</div>
<div class="col-12 col-md-4">
<h3 class="mt-4 mt-md-0"><?php echo $array[2]; ?></h3>
<p><?= get_post_meta(get_the_ID(), 'wpcf-address', true); ?></p>
</div>
</div>
</div>
<div class="col-12 text-center mt-5">
<p><i class="fa fa-copyright"></i> <?= get_post_meta(get_the_ID(), 'wpcf-copyright-content', true); ?></p>
</div>
</div>
</div>
</footer>
<?php wp_footer(); ?>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script type="text/javascript" src="<?= get_stylesheet_directory_uri() ?>/public/js/main.js"></script>
</body>
</html><file_sep><?php
get_header();
get_header('body');
global $post;
?>
<article class="home">
<section class="">
<div class="container">
<div class="row">
<div class="col-12 col-md-10 offset-md-1 col-lg-8 offset-lg-2 text-center">
<h1 class="text-uppercase"><?= get_post_meta(get_the_ID(), 'wpcf-description-title', true); ?></h1>
<p><?= get_post_meta(get_the_ID(), 'wpcf-description-content', true); ?></p>
</div>
</div>
</div>
</section>
<section class="p-0">
<div class="container-fluid backgroundImg" style="background-image:url('<?= get_post_meta(get_the_ID(), 'wpcf-block-img-body', true); ?>')"></div>
</section>
<section class="bgGrey">
<div class="container">
<div class="row">
<div class="col-12 text-center">
<h1 class="text-uppercase"><?= get_post_meta(get_the_ID(), 'wpcf-chart-title', true); ?></h1>
</div>
<div class="col-12 text-center charts_container">
<div class="charts">
<div class="chart_bar">
<span></span>
</div>
<div class="chart_bar">
<span></span>
</div>
<div class="chart_bar">
<span></span>
</div>
</div>
<div class="charts chart_description">
<?php
$years = get_post_meta(get_the_ID(), 'wpcf-chart-description', false);
foreach($years as $value) :
?>
<div class="chart_bar">
<p><?= $value; ?></p>
</div>
<?php endforeach; ?>
</div>
</div>
</div>
</div>
</section>
<section class="">
<div class="container">
<div class="row">
<div class="col-12 text-center">
<h1 class="text-uppercase"><?= get_post_meta(get_the_ID(), 'wpcf-block-img-title', true); ?></h1>
</div>
<div class="col-12">
<div class="row">
<?php
$i = 0;
$clientsImage = get_post_meta(get_the_ID(), 'wpcf-single-image-block', false);
$clientIndustry = get_post_meta(get_the_ID(), 'wpcf-single-image-description', false);
foreach($clientIndustry as $value) :
?>
<div class="col-12 col-md-4 col-lg-3 text-center align-self-end">
<div class="company-info">
<div class="imgBlock mt-5">
<div style="background-image:url('<?= $clientsImage[$i]; ?>')" alt="" class="img-fluid image-bg-behavior"></div>
</div>
<div class="descriptionBlock mt-4">
<p><?= $value; ?></p>
</div>
</div>
</div>
<?php
$i++;
endforeach;
?>
</div>
</div>
<div class="col-md-10 offset-md-1 col-lg-8 offset-lg-2 text-center">
<p class="mt-5"><?= get_post_meta(get_the_ID(), 'wpcf-block-body-description', true); ?></p>
</div>
</div>
</div>
</section>
<section class="bgGrey ecology">
<div class="container">
<div class="row">
<div class="col-12 col-md-6 text-center align-self-center">
<h1 class="text-uppercase"><?= get_post_meta(get_the_ID(), 'wpcf-block-image-description-title', true); ?></h1>
<p><?= get_post_meta(get_the_ID(), 'wpcf-image-description', true); ?></p>
</div>
<div class="col-12 col-md-6 align-self-center">
<div style="background-image:url('<?= get_post_meta(get_the_ID(), 'wpcf-block-show-image', true); ?>')" alt="Green world" class="img-fluid image-bg-behavior"></div>
</div>
</div>
</div>
</section>
</article>
<?php
get_footer();
?><file_sep><?php
/*
* Template Name: Machine Content
*
* @package Dynamo
*/
?>
<div class="row single-machine-info">
<div class="col-12 col-md-6">
<?php if(has_post_thumbnail($post->ID)) : ?>
<?php $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'wpcf-machine-image' ); ?>
<div class="image-bg-behavior" style="background-image:url('<?= $image[0]; ?>')"></div>
<?php endif; ?>
</div>
<div class="col-12 col-md-6">
<div class="machine-information mt-5">
<?php
the_title(sprintf('<h3 class="entry-title"><a href="%s">', esc_url(get_permalink())), '</a></h3>');
?>
<ul>
<?php
$machineInfo = get_post_meta(get_the_ID(), 'wpcf-machine-general-info', false);
foreach($machineInfo as $key => $value) :
?>
<li><?= $value; ?></li>
<?php endforeach; ?>
</ul>
</div>
</div>
</div>
<file_sep><?php
/*
* @package Dynamo
*/
?>
<?php
$my_query = new WP_Query('post_type=machine&nopaging=1');
if ($my_query->have_posts()) {
$counter = 1;
while ($my_query->have_posts()) {
$my_query->the_post();
?>
<div class="col-12 col-md-6 mb-5">
<div class="machineBlock">
<a href="<?php the_permalink(); ?>" rel="bookmark" title="Permanent link to <?php the_title_attribute(); ?>">
<h3 class="text-center mt-4"><?php the_title(); ?></h3>
<?php if(has_post_thumbnail()) : ?>
<div class="machineImg text-center">
<div class="image-bg-behavior mt-3" ><?php the_post_thumbnail(); ?></div>
</div>
<?php endif; ?>
</a>
</div>
</div>
<?php
$counter++;
}
wp_reset_postdata();
}
?><file_sep><?php
/*
* Template for the header
* @package Dynamo
*/
?>
<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
<meta charset="<?php bloginfo('charset'); ?>">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="robots" content="index, follow">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><?php bloginfo('name'); wp_title(); ?></title>
<link rel="prifile" href="http://gmpg.org/xfn/11">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="<KEY>" crossorigin="anonymous">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<link rel="stylesheet" href="<?= get_stylesheet_directory_uri() ?>/public/css/styles.css" type="text/css" media="all">
<?php wp_head(); ?>
</head>
<body <?php body_class(); ?>>
<header>
<div class="container-fluid">
<div class="col-12">
<nav class="navbar navbar-expand-md">
<div class="row align-items-center">
<div class="col-4 d-md-none toggler">
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span><i class="fas fa-bars"></i></span>
<span><i class="fas fa-times"></i></span>
</button>
</div>
<div class="col-7 offset-1 col-md-5 offset-md-0 col-lg-3 offset-lg-0">
<a class="navbar-brand image-bg-behavior" href="index.php" style="background-image:url('<?= get_template_directory_uri() ?>/public/img/dynamo_logo.png')" class="image-bg-behavior"></a>
</div>
<div class="col-md-7 col-lg-9">
<div class="collapse navbar-collapse navbar-light justify-content-end" id="navbarNav">
<?php
wp_nav_menu(array(
'Theme Location' => 'primary',
'container' => false,
'menu_class' => 'navbar navbar-expand-lg',
'menu' => 'Header_menu'
));
?>
</div>
</div>
</div>
</nav>
</div>
</div>
<hr>
<div class="head-background" style="background-image:url('<?= get_post_meta(get_the_ID(), 'wpcf-background-img-header', true) ?>')"></div>
</header>
</body>
</html><file_sep><?php
/*
* Template name: Single Machine
*
* @package Dynamo
*/
get_header();
?>
<article class="container single-tool mt-5 mb-5">
<div class="row">
<div class="col-12 mt-5 mb-5">
<?php
while(have_posts()) : the_post();
get_template_part('content', 'machine');
endwhile;
?>
</div>
</div>
<div class="row">
<div class="col-12 text-center text-lg-left">
<h2 class="mt-5">Gerelateerde machinepark</h2>
<?php
$count = 0;
$related_posts = get_posts(
[
'post_type' => 'machine',
'exclude' => get_the_ID(),
'posts_per_page' => 2,
'order' => 'ASC'
]
);
?>
<div class="row justify-content-center">
<?php foreach ($related_posts AS $post) : ?>
<div class="col-12 col-md-8 col-lg-5 mr-lg-auto">
<div class="machineBlock">
<a href="<?= get_the_permalink($post->ID) ?>">
<h3 class="text-center mt-4"><?php the_title(); ?></h3>
<div class="machineImg text-center">
<div class="background-img image-bg-behavior" style="background-image:url('<?= get_the_post_thumbnail_url($post->ID) ?>')"></div>
</div>
</a>
</div>
</div>
<?php
++$count;
endforeach;
?>
</div>
</div>
</div>
</article>
<?php
get_footer();
?><file_sep><?php
/*
* Template Name: Contact page
*/
?>
<?php
require('header.php');
?>
<article class="contact">
<section class="contactMap p-0">
<div class="container-fluid header-map p-0">
<div id="map" style="height: 28.75rem;"></div>
</div>
</section>
<section>
<div class="container">
<div class="row">
<div class="col-12">
<p class="mb-5"><?= get_post_meta(get_the_ID(), 'wpcf-contact-description', true); ?></p>
</div>
<div class="col-12 col-md-4">
<p><?= get_post_meta(get_the_ID(), 'wpcf-address', true); ?></p>
</div>
<div class="col-12 col-md-4">
<?php
$contacts = get_post_meta(get_the_ID(), 'wpcf-contact-info', false);
foreach($contacts as $value) :
?>
<p><?= $value; ?></p>
<?php endforeach; ?>
</div>
<div class="col-12 col-md-4">
<?php
$commercials = get_post_meta(get_the_ID(), 'wpcf-commercial-info', false);
foreach($commercials as $value) :
?>
<p><?= $value; ?></p>
<?php endforeach; ?>
</div>
</div>
</div>
</section>
</article>
<script>
function initMap() {
var options = {lat: 51.98768889999999, lng: 4.373202399999968};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: options
});
var marker = new google.maps.Marker({
position: options,
map: map
});
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=<KEY>&callback=initMap">
</script>
<?php
require('footer.php');
?><file_sep><?php
/*
* Template Name: Archive machine
*
* @package Dynamo
*/
get_header();
?>
<article class="machines">
<section>
<div class="container">
<div class="row">
<div class="col-12 text-center">
<h1 class="text-uppercase"><?= the_title(); ?></h1>
</div>
<?php
while(have_posts()) : the_post();
get_template_part('listing', 'machine');
endwhile;
?>
</div>
</div>
</section>
</article>
<?php get_footer(); ?><file_sep><?php
/*
* Template Name: Bedrijfsprofiel Page
*/
?>
<?php
require('header.php');
?>
<article class=" home company">
<section class="">
<div class="container">
<div class="row">
<div class="col-12 col-md-10 offset-md-1 col-lg-8 offset-lg-2 text-center">
<h1 class="text-uppercase"><?= get_post_meta(get_the_ID(), 'wpcf-description-title', true); ?></h1>
<p><?= get_post_meta(get_the_ID(), 'wpcf-description-content', true); ?></p>
</div>
</div>
</div>
</section>
<section>
<div class="container-fluid">
<div class="row">
<div class="col-12 text-center">
<h1 class="text-uppercase"><?= get_post_meta(get_the_ID(), 'wpcf-block-img-title', true); ?></h1>
</div>
<div class="col-12">
<div class="row">
<?php
$i = 0;
$serviceImg = get_post_meta(get_the_ID(), 'wpcf-single-image-block', false);
$serviceInfo = get_post_meta(get_the_ID(), 'wpcf-single-image-description', false);
foreach($serviceInfo as $value) :
?>
<div class="col-12 col-md-4 col-lg-3 text-center align-self-end">
<div class="company-info">
<div class="imgBlock mt-5">
<div style="background-image:url('<?= $serviceImg[$i]; ?>')" alt="" class="img-fluid image-bg-behavior"></div>
</div>
<div class="descriptionBlock mt-4">
<p><?= $value; ?></p>
</div>
</div>
</div>
<?php
$i++;
endforeach;
?>
</div>
</div>
</div>
</section>
<section class="bgGrey ecology">
<div class="container">
<div class="row">
<div class="col-12 col-md-6 text-center align-self-center">
<h1 class="text-uppercase"><?= get_post_meta(get_the_ID(), 'wpcf-block-image-description-title', true); ?></h1>
<p><?= get_post_meta(get_the_ID(), 'wpcf-image-description', true); ?></p>
</div>
<div class="col-12 col-md-6 align-self-center">
<div style="background-image:url('<?= get_post_meta(get_the_ID(), 'wpcf-block-show-image', true); ?>')" alt="Green world" class="img-fluid image-bg-behavior"></div>
</div>
</div>
</div>
</section>
</article>
<?php
require('footer.php');
?><file_sep><?php
/*
* Dynamo functions and definitions
* @package Daynamo
*/
/*
* Custom functions
*/
function dynamo_custom_setup() {
// Activate Nav Menu
register_nav_menu( 'primary', __( 'Hoofdmenu', 'dynamo' ) );
// Enable support for Post Formats
add_theme_support('post-formats', array(
'aside',
'image',
'video',
'quote',
'link'
));
add_theme_support( 'post-thumbnails', array( 'machine' ) );
}
add_action('after_setup_theme', 'dynamo_custom_setup');
// Enqueue scripts and styles
function wpdocs_theme_name_scripts() {
wp_enqueue_style( 'script-name', get_template_directory_uri() . '/public/css/styles.css');
}
add_action('wp_enqueue_scripts', 'wpdocs_theme_name_scripts');
// Add custom post type Machines
function machine_init() {
$labels = array (
'name' => 'Machines',
'singular_name' => 'Machine',
'add_new' => 'Add New',
'add_new_item' => 'Add New Machine',
'edit_item' => 'Edit Machine',
'new_item' => 'New Machine',
'view_item' => 'View Machine',
'search_items' => 'Search Machine',
'not_found' => 'No machines found',
'not_found_in_trash' => 'No machines found in Trash'
);
$args = array (
'labels' => $labels,
'description' => 'Custom post type that holds machines',
'public' => true,
'rewrite' => array('slug' => 'machines'),
'has_archive' => true,
'supports' => array(
'title',
'editor',
'thumbnail',
'custom-fields'
)
);
register_post_type('machine', $args);
flush_rewrite_rules();
}
add_action('init', 'machine_init');
// Function to remove meta generator tag
function dynamo_remove_version() {
return '';
}
add_filter('the_generator', 'dynamo_remove_version');
|
754447aa418e10ad355e78e76c698013d66a95db
|
[
"PHP"
] | 10
|
PHP
|
AdelaideDeCastro/dynamo
|
ad5c314a933ee9389377797358e1a47fb3a7ef50
|
47481e3eb20ad9c4be7a580f83bfe5ce4d9cbbd8
|
refs/heads/main
|
<repo_name>kariah/palautusrepositorio_osa3<file_sep>/3.7-3.8/README.md
# Tehtävät 3.7-3.8
<file_sep>/README.md
# # Full Stack open 2021
## Palautusrepositorio Osa3:n tehtäville
<file_sep>/3.9-3.11/README.md
# Tehtävät 3.9-3.11
<file_sep>/3.13-3.14/README.md
# Tehtävät 3.13-3.14
# https://whispering-crag-50275.herokuapp.com
<file_sep>/3.15-3.16/README.md
# Tehtävät 3.15-3.16 (Virheenkäsittelyä muutettu seuraavissa tehtävissä!)
<file_sep>/3.9-3.11/puhelinluettelo/src/components/Persons.js
import React from 'react'
import personService from '../services/persons'
const Persons = (props) => {
const showAll = props.showAll
const persons = props.persons
const setPersons = props.setPersons
const setShowAll = props.setShowAll
const setInfoMessage = props.setInfoMessage
const setErrorMessage = props.setErrorMessage
const removePerson = (id) => {
personService
.remove(id)
.then(response => {
console.log("response ", response)
let filtered = showAll.filter(person => person.id !== id)
setShowAll(filtered)
filtered = persons.filter(person => person.id !== id)
setPersons(filtered)
setTimeout(() => {
let info = `Personid ${id} was deleted succesfully`
setInfoMessage(info)
}, 1000)
setTimeout(() => {
setInfoMessage(null)
}, 5000)
})
.catch(error => {
setErrorMessage(
`Personid '${id}' was already removed from server`
)
setTimeout(() => {
setErrorMessage(null)
}, 5000)
})
}
return (
<div>
{showAll.map(person =>
<p key={person.id}>{person.name} {person.number}
<button onClick={() =>
window.confirm(`Delete ${person.name}?`) &&
removePerson(person.id)}>Delete</button>
</p>)}
</div>
)
}
export default Persons
<file_sep>/puhelinluettelo-server/README.md
# Lopullinen versio - kaikki tehtävät
<file_sep>/3.1-3.6/README.md
# Tehtävät 3.1-3.6
<file_sep>/3.9-3.11/puhelinluettelo/src/App.js
import React, { useState, useEffect } from 'react'
import personService from './services/persons'
import PersonForm from './components/PersonForm'
import Filter from './components/Filter'
import Persons from './components/Persons'
import Notification from './components/Notification'
const App = () => {
const [persons, setPersons] = useState([])
const [infoMessage, setInfoMessage] = useState(null)
const [errorMessage, setErrorMessage] = useState(null)
useEffect(() => {
personService
.getAll()
.then(initialPersons => {
setPersons(initialPersons)
setShowAll(initialPersons)
})
}, [])
const [showAll, setShowAll] = useState(persons)
return (
<div>
<h1>Phonebook</h1>
<Notification infoMessage={infoMessage} errorMessage={errorMessage} />
<Filter
persons={persons}
setShowAll={setShowAll} />
<h2>Add new</h2>
<PersonForm
persons={persons}
showAll={showAll}
setPersons={setPersons}
setShowAll={setShowAll}
setInfoMessage={setInfoMessage}
setErrorMessage={setErrorMessage}
/>
<h2>Numbers</h2>
<Persons
persons={persons}
showAll={showAll}
setPersons={setPersons}
setShowAll={setShowAll}
setInfoMessage={setInfoMessage}
setErrorMessage={setErrorMessage}
/>
</div>
)
}
export default App
<file_sep>/3.13-3.14/index.js
require('dotenv').config()
const express = require('express')
var morgan = require('morgan')
const app = express()
app.use(express.json())
app.use(express.static('build'))
const cors = require('cors')
app.use(cors())
morgan.token('body-data', function getPostData(req) {
return (JSON.stringify(req.body))
})
app.use(morgan(':method :url :status :res[content-length] - :response-time ms - :body-data'))
const Person = require('./models/person')
app.post('/api/persons', (request, response) => {
const body = request.body
if (!body.name || !body.number) {
return response.status(400).json({
error: 'name or number missing'
})
}
const person = new Person({
name: body.name,
number: body.number
})
person.save().then(savedPerson => {
response.json(savedPerson)
})
})
app.get('/api/persons', (req, res) => {
Person
.find({})
.then(persons => {
res.json(persons)
})
})
//GET http://localhost:3001/api/persons/1
app.get('/api/persons/:id', (request, response) => {
Person.findById(request.params.id).then(person => {
if (person) {
response.json(person)
} else {
response.status(404).end()
}
})
})
//DELETE http://localhost:3001/api/persons/1
app.delete('/api/persons/:id', (request, response) => {
const id = Number(request.params.id)
persons = persons.filter(person => person.id !== id)
response.status(204).end()
})
//GET http://localhost:3001/info
app.get('/info', (req, res) => {
let currentDateTime = new Date();
let html = `<div>
<p>Phonebook has info for ${persons.length} people </p>
<p>${currentDateTime}</p>
</div>`
res.send(html)
})
const PORT = process.env.PORT || 3001
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`)
})<file_sep>/3.12/mongo.js
const mongoose = require('mongoose')
if (process.argv.length < 3) {
console.log('give password as argument')
process.exit(1)
}
const password = process.argv[2]
const name = process.argv[3]
const number = process.argv[4]
const id = process.argv[5]
const url = `mongodb+srv://fullstack:${password}@<EMAIL>/phonebook?retryWrites=true'`
mongoose.connect(url, { useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false, useCreateIndex: true })
const personSchema = new mongoose.Schema({
name: String,
number: String,
id: Number,
})
const Person = mongoose.model('Person', personSchema, 'persons')
const person = new Person({
name: name,
number: number,
id: id
})
if (process.argv[3] === undefined && process.argv[4] === undefined) {
console.log('find start')
//Person.find({ "id": 1 }).then(result => {
console.log(Person)
Person
.find({})
.then(result => {
console.log(result)
result.forEach(person => {
console.log(person)
})
mongoose.connection.close()
})
}
else {
//node mongo.js yourpassword Anna 040 - 1234556
person
.save()
.then(response => {
console.log(`Added ${name} ${number} to phonebook`)
console.log(response)
mongoose.connection.close()
})
}
<file_sep>/3.22/README.md
# Tehtävä 3.22
<file_sep>/3.9-3.11/puhelinluettelo-server/README.md
# https://whispering-crag-50275.herokuapp.com<file_sep>/puhelinluettelo-server/index.js
/* eslint-disable no-unused-vars */
/* eslint-disable no-undef */
require('dotenv').config()
const express = require('express')
var morgan = require('morgan')
const app = express()
app.use(express.static('build'))
app.use(express.json())
const cors = require('cors')
app.use(cors())
morgan.token('body-data', function getPostData(req) {
return (JSON.stringify(req.body))
})
app.use(morgan(':method :url :status :res[content-length] - :response-time ms - :body-data'))
const errorHandler = (error, _request, response, next) => {
console.log(error.name)
console.error(error.message)
if (error.name === 'CastError') {
return response.status(400).send(
{
error: 'malformatted id'
}
)
} else
if (error.name === 'ValidationError') {
return response.status(400).json(
{
error: error.message
}
)
}
next(error)
}
const requestLogger = (request, _response, next) => {
console.log('Method:', request.method)
console.log('Path: ', request.path)
console.log('Body: ', request.body)
console.log('---')
next()
}
app.use(requestLogger)
const Person = require('./models/person')
app.post('/api/persons', (request, response, next) => {
const body = request.body
if (!body.name || !body.number) {
return response.status(400).json({
error: 'name or number missing'
})
}
let personFound = false
//Teht�v� 3.20
//N�ytet��n frontissa fronttiin error.response.data.error
//persons.js tiedostossa .error(error => error.response.data)
Person
.findOne({ name: body.name })
.then(person => {
//Tested uniqueness
//addPerson(request, response, next)
if (person !== null) {
personFound = true
}
if (!personFound) {
addPerson(request, response, next)
}
else {
updatePerson(request, response, next, person.id)
}
})
.catch(error => next(error))
})
app.put('/api/persons/:id', (request, response, next) => {
updatePerson(request, response, next, request.params.id)
})
function updatePerson(request, response, next, id) {
console.log('Update person ', id)
const body = request.body
const person = {
name: body.name,
number: body.number
}
console.log(id)
Person.findByIdAndUpdate(id, person, { new: true })
.then(updatedPerson => {
response.json(updatedPerson)
})
.catch(error => next(error))
}
function addPerson(request, response, next) {
console.log('Add person')
const person = new Person({
name: request.body.name,
number: request.body.number
})
person.save()
//.then(savedPerson => {
// response.json(savedPerson)
//})
.then(savedPerson => savedPerson.toJSON())
.then(savedAndFormattedPerson => {
response.json(savedAndFormattedPerson)
})
.catch(error => next(error))
}
app.get('/api/persons', (_request, response, next) => {
Person
.find({})
.then(persons => {
response.json(persons)
})
.catch(error => next(error))
})
//GET http://localhost:3001/api/persons/1
app.get('/api/persons/:id', (request, response, next) => {
Person.findById(request.params.id)
.then(person => {
if (person) {
response.json(person)
} else {
response.status(404).end()
}
})
.catch(error => next(error))
})
//DELETE http://localhost:3001/api/persons/1
app.delete('/api/persons/:id', (request, response, next) => {
Person.findByIdAndRemove(request.params.id)
.then(_result => {
response.status(204).end()
})
.catch(error =>
next(error)
)
})
//GET http://localhost:3001/info
app.get('/info', (_request, response, next) => {
let currentDateTime = new Date()
Person
.find({})
.then(persons => {
//response.json(persons)
let html = `<div>
<p>Phonebook has info for ${persons.length} people </p>
<p>${currentDateTime}</p>
</div>`
response.send(html)
})
.catch(error => next(error))
})
const unknownEndpoint = (_request, response) => {
response.status(404).send({ error: 'unknown endpoint' })
}
// olemattomien osoitteiden k�sittely
app.use(unknownEndpoint)
// t�m� tulee kaikkien muiden middlewarejen rekister�innin j�lkeen!
app.use(errorHandler)
const PORT = process.env.PORT || 3001
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`)
})<file_sep>/3.9-3.11/puhelinluettelo/src/components/PersonForm.js
import React, { useState } from 'react'
import personService from '../services/persons'
const PersonForm = (props) => {
const persons = props.persons
const showAll = props.showAll
const setPersons = props.setPersons
const setShowAll = props.setShowAll
const setInfoMessage = props.setInfoMessage
const setErrorMessage = props.setErrorMessage
const [newPerson, setNewPerson] = useState({
person: {
id: 0,
name: "",
number: ""
}
});
const updateNumber = (id, number) => {
//console.log("id, number ", id, number)
const person = persons.find(p => p.id === id)
const changedPerson = { ...person, number: number }
personService
.update(id, changedPerson)
.then(returnedPerson => {
setPersons(persons.map(person => person.id !== id ? person : returnedPerson))
setShowAll(showAll.map(person => person.id !== id ? person : returnedPerson))
setTimeout(() => {
let info = `Personid ${id} was updated succesfully`
setInfoMessage(info)
}, 1000)
setTimeout(() => {
setInfoMessage(null)
}, 5000)
})
.catch(error => {
setErrorMessage(`Person '${person.name}' was already deleted from server`)
setTimeout(() => {
setErrorMessage(null)
}, 5000)
setPersons(persons.filter(p => p.id !== id))
})
}
const addPerson = (event) => {
event.preventDefault()
let personFound = null
let dialogResult
if (newPerson.person.name !== undefined) {
/* personFound = (persons.find(person => person.name === newPerson.person.name) ? true : false)*/
personFound = (persons.find(person => person.name === newPerson.person.name))
if (personFound != null) {
dialogResult = window.confirm(`${newPerson.person.name} is already added to phonebook, replace the old number with new one`);
}
}
console.log("personFound ", personFound)
if (personFound != null) {
if (dialogResult === true) {
updateNumber(personFound.id, newPerson.person.number)
return
}
else {
return
}
}
const personObject = {
name: newPerson.person.name,
number: newPerson.person.number,
id: persons.length + 1,
}
//add to server db
personService
.create(personObject)
.then(returnedPerson => {
setPersons(persons.concat(returnedPerson))
setShowAll(persons.concat(returnedPerson))
setNewPerson({
person: {
id: 0,
name: "",
number: ""
}
})
setTimeout(() => {
let info = `Person ${personObject.name} was created succesfully`
setInfoMessage(info)
}, 1000)
setTimeout(() => {
setInfoMessage(null)
}, 5000)
})
.catch(error => {
setErrorMessage(
`Create person ${personObject.name} failed.`
)
setTimeout(() => {
setErrorMessage(null)
}, 5000)
})
}
const handlePersonChange = (event) => {
let name = newPerson.person.name
let number = newPerson.person.number
if (event.target.id === "name") {
name = event.target.value
}
else if (event.target.id === "number") {
number = event.target.value
}
setNewPerson({
...newPerson, person: {
name: name,
number: number
}
},
)
}
return (
<form onSubmit={addPerson}>
<div>
Name:
<input
value={newPerson.person.name}
onChange={handlePersonChange}
id="name"
/>
</div>
<div>
Number:
<input
value={newPerson.person.number}
onChange={handlePersonChange}
id="number"
/>
</div>
<div>
<button type="submit">add</button>
</div>
</form>
)
}
export default PersonForm<file_sep>/3.17-3.18/README.md
# Tehtävät 3.17-3.18
# https://whispering-crag-50275.herokuapp.com
<file_sep>/3.12/README.md
# Tehtävä 3.12
# https://whispering-crag-50275.herokuapp.com
<file_sep>/3.7-3.8/index.js
const express = require('express')
var morgan = require('morgan')
const app = express()
app.use(express.json())
morgan.token('body-data', function getPostData(req) {
return (JSON.stringify(req.body))
})
app.use(morgan(':method :url :status :res[content-length] - :response-time ms - :body-data'))
let persons = [
{
"name": "<NAME>",
"number": "040-123456",
"id": 1
},
{
"name": "<NAME>",
"number": "39-44-5323523",
"id": 2
},
{
"name": "<NAME>",
"number": "12-43-234345",
"id": 3
},
{
"name": "<NAME>",
"number": "39-23-6423122",
"id": 4
}
]
const generateId = () => {
const maxId = persons.length > 0
? Math.max(...persons.map(n => n.id))
: 0
return maxId + 1
}
//POST http://localhost:3001/api/persons
app.post('/api/persons', (request, response) => {
const body = request.body
console.log("body ", body)
if (!body.name || !body.number) {
return response.status(400).json({
error: 'name or number missing'
})
}
else {
let isPersonFound = (persons.find(person => person.name === body.name))
if (isPersonFound) {
return response.status(409).json({
error: (`Name must be unique`)
})
}
}
const person = {
name: body.name,
number: body.number,
id: generateId(),
}
persons = persons.concat(person)
response.json(person)
})
//GET http://localhost:3001/api/persons
app.get('/api/persons', (req, res) => {
res.json(persons)
})
//GET http://localhost:3001/api/persons/1
app.get('/api/persons/:id', (request, response) => {
const id = Number(request.params.id)
const person = persons.find(person => person.id === id)
if (person) {
response.json(person)
} else {
response.status(404).end()
}
})
//DELETE http://localhost:3001/api/persons/1
app.delete('/api/persons/:id', (request, response) => {
const id = Number(request.params.id)
persons = persons.filter(person => person.id !== id)
console.log(persons)
response.status(204).end()
})
//GET http://localhost:3001/info
app.get('/info', (req, res) => {
let currentDateTime = new Date();
let html = `<div>
<p>Phonebook has info for ${persons.length} people </p>
<p>${currentDateTime}</p>
</div>`
res.send(html)
})
const PORT = 3001;
// run the server
app.listen(PORT, () => {
console.log(`Puhelinluettelo-server app listening on port ${PORT}!`);
});
<file_sep>/3.19-3.21/README.md
# Tehtävät 3.19-3.21
# https://whispering-crag-50275.herokuapp.com
|
dec5ab75416fae9ed5380c5d31790a71cab8a36b
|
[
"Markdown",
"JavaScript"
] | 19
|
Markdown
|
kariah/palautusrepositorio_osa3
|
15a12a5724592a2675946f6b98dc903eb4cc2fc8
|
ec6e2632fe3f374146958bd80c213edd033d95d2
|
refs/heads/master
|
<repo_name>liashenko/tetris<file_sep>/Tetramino.h
#pragma once
class Tetramino
{
public:
Tetramino(void);
Tetramino(int shape, int x, int y, int angle);
~Tetramino(void);
bool GetValue(int x, int y) const;
void Move (int dx, int dy);
void SetSpeed(int speed);
int GetSpeed() const;
void Rotate();
int GetX() const;
int GetY() const;
private:
int shape;
int angle;
int speed;
int x;
int y;
};
<file_sep>/TestApp.h
// Copyright 2009-2014 Blam Games, Inc. All Rights Reserved.
#pragma once
#include "BaseApp.h"
#include "Tetramino.h"
#include "FilledArea.h"
class TestApp : public BaseApp
{
typedef BaseApp Parent;
private:
//текущая фигура
Tetramino tetramino;
//следующая фигура
Tetramino nextTetramino;
//заполненная область
FilledArea filledArea;
//счётчик для задержки
int counter;
//задержка
static const int DELAY = 20;
public:
TestApp();
virtual void KeyPressed(int btnCode);
virtual void UpdateF(float deltaTime);
void Turn();
void Draw();
void DrawFilledArea();
void DrawTetramino();
void DrawNextTetramino();
};
<file_sep>/FilledArea.cpp
#include "FilledArea.h"
FilledArea::FilledArea(void)
{
Refresh();
}
FilledArea::~FilledArea(void)
{
}
//очищаем заполненную область
void FilledArea::Refresh()
{
for(int i = 0; i < FilledArea::HEIGHT; i++)
{
for(int j = 0; j < FilledArea::WIDTH; j++)
{
map[i][j] = false;
}
}
//нижняя строка заполняется true для обнаружения столкновения фигуры с низом заполненной области
for(int j = 0;j < FilledArea::WIDTH; j++)
{
map[FilledArea::HEIGHT][j] = true;
}
}
bool FilledArea::GetValue(int x, int y) const
{
return map[y][x];
}
bool FilledArea::IsCollision (Tetramino &t) const
{
for(int i = 0; i < 4; i++)
{
for(int j = 0; j < 4; j++)
{
if (t.GetValue(j, i) == true)
{
int x = t.GetX() + j - 1;
int y = t.GetY() + i;
if(x < 0 || x >= FilledArea::WIDTH || y < 0 || y >= FilledArea::HEIGHT)
return true;
if (t.GetValue(j, i) == map[y][x])
return true;
}
}
}
return false;
}
void FilledArea::Merge(Tetramino &t)
{
for(int i = 0; i < 4; i++)
{
for(int j = 0; j < 4; j++)
{
if(t.GetValue(j, i) == true)
{
int x = t.GetX() + j - 1;
int y = t.GetY() + i;
if(x >= 0 || x < FilledArea::WIDTH || y >= 0 || y < FilledArea::HEIGHT)
map[y][x] = map[y][x] | t.GetValue(j, i);
}
}
}
}
void FilledArea::RemoveSolidLines()
{
for(int i = 0; i < FilledArea::HEIGHT; i++)
{
bool solid = true;
for(int j = 0; j < FilledArea::WIDTH; j++)
{
solid &= map[i][j];
}
if(solid == true)
{
RemoveSolidLine(i);
}
}
}
void FilledArea::RemoveSolidLine(int k)
{
//опускаем строки заполненной области
for(int i = k - 1; i >= 0; i--)
{
for(int j = 0; j < FilledArea::WIDTH; j++)
{
map[i + 1][j] = map[i][j];
}
}
//очищаем первую строку заполненной области
for(int j = 0; j < FilledArea::WIDTH; j++)
{
map[0][j] = false;
}
}
<file_sep>/FilledArea.h
#pragma once
#include "Tetramino.h";
class FilledArea
{
public:
enum {HEIGHT = 20, WIDTH = 15};
FilledArea(void);
~FilledArea(void);
bool GetValue(int x, int y) const;
bool IsCollision (Tetramino &t) const;
void Merge(Tetramino &t);
void RemoveSolidLines();
void RemoveSolidLine(int k);
void Refresh();
private:
bool map[HEIGHT + 2][WIDTH];
};
<file_sep>/TestApp.cpp
// Copyright 2009-2014 Blam Games, Inc. All Rights Reserved.
#include "TestApp.h"
TestApp::TestApp() : Parent(200, 180)
{
tetramino = Tetramino(rand() % 5, 8, 1, 0);
nextTetramino = Tetramino(rand() % 5, 8, 1, 0);
filledArea = FilledArea();
//инициилизация счётчика
counter = 1000;
}
void TestApp::DrawFilledArea()
{
//границы заполненной области по горизонтали
for(int j = 0; j < FilledArea::WIDTH + 2; j++)
{
SetChar(j * 1, 0, '#');
SetChar(j * 1, (FilledArea::HEIGHT + 1), '#');
}
//границы заполненной области по вертикали
for(int i = 0; i < FilledArea::HEIGHT + 2; i++)
{
SetChar(0, i * 1, '#');
SetChar((FilledArea::WIDTH + 1), i * 1, '#');
}
//отрисовка заполненной области
for(int i = 1; i <= FilledArea::HEIGHT; i++)
{
for(int j = 1; j <= FilledArea::WIDTH; j++)
{
if(filledArea.GetValue(j - 1, i - 1) == true)
{
SetChar(j * 1, i * 1, '*');
}
else
{
SetChar(j * 1, i * 1, '.');
}
}
}
}
void TestApp::DrawTetramino()
{
int x = tetramino.GetX();
int y = tetramino.GetY();
//отрисовка фигуры
for(int i = 0; i < 4; i++)
{
for(int j = 0; j < 4; j++)
{
if(tetramino.GetValue(j, i) == true)
{
SetChar((x + j) * 1, (y + i) * 1, '*');
}
}
}
}
void TestApp::DrawNextTetramino()
{
//границы области подсказки следующей фигуры по горизонтали
for(int j = FilledArea::WIDTH + 2; j < FilledArea::WIDTH + 9; j++)
{
SetChar(j * 1, 0, '#');
SetChar(j * 1, 5, '#');
}
//границы области подсказки следующей фигуры по вертикали
for(int i = 0; i < 5; i++)
{
SetChar(FilledArea::WIDTH + 8, i*1, '#');
}
//пустые поля области подсказки следующей фигуры
for(int i = 1; i < 5; i++)
{
for(int j = FilledArea::WIDTH + 2; j < FilledArea::WIDTH + 8; j++)
{
SetChar(j*1, i*1, '.');
}
}
//отрисовка следующей фигуры
for(int i = 0; i < 4; i++)
{
for(int j = 0; j < 4; j++)
{
if(nextTetramino.GetValue(j, i) == true)
{
SetChar((j + FilledArea::WIDTH + 3) * 1, (i + 2) * 1, '*');
}
}
}
}
void TestApp::KeyPressed(int btnCode)
{
Tetramino t = tetramino;
if (btnCode == 75)//left
{
t.Move(-1, 0);
}
else if (btnCode == 77)//right
{
t.Move(1, 0);
}
else if (btnCode == 80)//down
{
t.SetSpeed(DELAY);
}
else if(btnCode == 32)//space
{
t.Rotate();
}
if(filledArea.IsCollision(t) == false)
{
tetramino = t;
DrawFilledArea();
DrawTetramino();
}
}
void TestApp::Draw()
{
//отрисовка заполненной области
DrawFilledArea();
//отрисовка текущей фигуры
DrawTetramino();
//отрисовка следующей фигуры
DrawNextTetramino();
}
void TestApp::Turn()
{
//текущую фигуру вниз
Tetramino t = tetramino;
t.Move(0, 1);
//фигура столкнулась с заполненной областью
if(filledArea.IsCollision(t) == false)
{
tetramino = t;
}
else
{
//добавить фигуру к заполненной области
filledArea.Merge(tetramino);
//удалить сплошные линии
filledArea.RemoveSolidLines();
//новая фигура
tetramino = nextTetramino;
nextTetramino = Tetramino(rand() % 5, 8, 1, 0);
//если новая фигура касается заполненной области - обновить игру
if(filledArea.IsCollision(tetramino))
{
filledArea.Refresh();
}
}
}
void TestApp::UpdateF(float deltaTime)
{
//отрисовка экрана
Draw();
//задержка хода
if (counter > DELAY / tetramino.GetSpeed())
{
counter = 0;
//ход
Turn();
}
counter++;
}
|
12b78474aebffb9569a06645cc0bde58574450fa
|
[
"C++"
] | 5
|
C++
|
liashenko/tetris
|
24b8c41cac5d3e5d575ce2c45169f4434452984e
|
c63af9d89a80d82199b91e80350b077773639a64
|
refs/heads/master
|
<repo_name>goragottsen/shopping_bag<file_sep>/A101095885/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Console;
using System.IO;
//Task 1
namespace A101095885
{
class Program
{
static void Main(string[] args)
{
try
{
BoundedBag<string> b = new BoundedBag<string>("ShoppingList", 10);
b.insert("apple");
b.insert("eggs");
b.insert("milk");
b.saveBag("C:/Users/Goragottsen/Desktop/gbc/COMP2129/assignment/A101095885/A101095885/mybag.txt");
BoundedBag<string> c = new BoundedBag<string>("ShoppingList", 10);
c.loadBag("C:/Users/Goragottsen/Desktop/gbc/COMP2129/assignment/A101095885/A101095885/mybag.txt");
WriteLine(c.remove());
WriteLine(c.remove());
WriteLine(c.remove());
}
catch(BagFullException e)
{
}
catch (BagEmptyException e)
{
}
ReadKey();
}
}
//Task 2
public interface Bag<T> where T : class
{
T remove();
void insert(T item);
string getName();
bool isEmpty();
void saveBag(string path);
void loadBag(string path);
}
//Task 3
public class BagEmptyException : Exception
{
public BagEmptyException() { }
public BagEmptyException(string message) : base(message)
{
WriteLine(message);
}
}
public class BagFullException : Exception
{
public BagFullException() { }
public BagFullException(string message) : base(message)
{
WriteLine(message);
}
}
//Task 4
public class BoundedBag<T> : Bag<T> where T : class
{
private string bagName; //bag name
private int size; //max size of the bag
private int lastIndex;
private T[] items;
private Random rnd;
public BoundedBag(string name, int size)
{
bagName = name;
this.size = size;
rnd = new Random();
items = new T[size];
lastIndex = -1;
}
public string getName()
{
return bagName;
}
public bool isEmpty()
{
if (lastIndex == -1)
return true;
return false;
}
public bool isFull()
{
if (lastIndex == size)
return true;
return false;
}
public void loadBag(string path)
{
FileInfo fi = new FileInfo(path);
if (fi.Exists)
{
string[] lines = File.ReadAllLines(@path);
for (int i = 0; i < lines.Length; i++)
{
T it = (T)Convert.ChangeType(lines[i], typeof(T));
items[i] = it;
}
lastIndex = lines.Length - 1;
}
}
public void saveBag(string path)
{
StreamWriter sw = new StreamWriter(@path);
foreach (T item in items)
{
if (item != null)
sw.WriteLine(item);
else
break;
}
sw.Close();
}
public void insert(T item)
{
if (isFull())
{
throw new BagFullException("The Bag is full");
}
else if (isEmpty())
{
lastIndex = 0;
items[lastIndex] = (T)Convert.ChangeType(item, typeof(T));
lastIndex++;
}
else
{
items[lastIndex] = (T)Convert.ChangeType(item, typeof(T));
lastIndex++;
}
}
public T remove()
{
if (!isEmpty())
{
int i = rnd.Next(0, lastIndex);
T removed = items[i];
items[i] = items[lastIndex];
items[lastIndex] = null;
lastIndex--;
return removed;
}
else
{
throw new BagEmptyException("The bag is empty");
}
}
}
}
<file_sep>/A101095885/BoundedBagTest.cs
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Axxx;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Axxx.Tests
{
[TestClass()]
public class BoundedBagTests
{
[TestMethod()]
public void getNameTest()
{
BoundedBag<string> b = new BoundedBag<string>("bag", 3);
Assert.AreEqual("bag", b.getName());
}
[TestMethod()]
public void isEmptyTest1()
{
BoundedBag<string> b = new BoundedBag<string>("bag", 3);
Assert.IsTrue(b.isEmpty());
}
[TestMethod()]
public void isEmptyTest2()
{
BoundedBag<string> b = new BoundedBag<string>("bag", 3);
b.insert("one");
Assert.IsFalse(b.isEmpty());
}
[TestMethod()]
public void isEmptyTest3()
{
BoundedBag<string> b = new BoundedBag<string>("bag", 3);
b.insert("one");
b.remove();
Assert.IsTrue(b.isEmpty());
}
[TestMethod()]
public void isFullTest1()
{
BoundedBag<string> b = new BoundedBag<string>("bag", 0);
Assert.IsTrue(b.isFull());
}
[TestMethod()]
public void isFullTest2()
{
BoundedBag<string> b = new BoundedBag<string>("bag", 1);
b.insert("one");
Assert.IsTrue(b.isFull());
}
[TestMethod()]
public void isFullTest3()
{
BoundedBag<string> b = new BoundedBag<string>("bag", 2);
b.insert("one");
Assert.IsFalse(b.isFull());
}
[TestMethod()]
public void insertTest1()
{
BoundedBag<string> b = new BoundedBag<string>("bag", 3);
b.insert("one");
b.insert("two");
b.insert("one");
Assert.IsTrue(b.isFull());
}
[TestMethod()]
public void insertTest2()
{
BoundedBag<string> b = new BoundedBag<string>("bag", 3);
b.insert("one");
b.insert("two");
b.insert("one");
try
{
b.insert("four");
}
catch (BagFullException e) { }
finally
{
Assert.AreEqual("bag", b.getName());
}
}
[TestMethod()]
public void insertTest3()
{
BoundedBag<string> b = new BoundedBag<string>("bag", 3);
b.insert("one");
b.insert("two");
b.insert("one");
Assert.IsFalse(b.isEmpty());
}
[TestMethod()]
public void removeTest1()
{
BoundedBag<string> b = new BoundedBag<string>("bag", 3);
b.insert("one");
string s = b.remove();
Assert.IsTrue(s.Equals("one"));
}
[TestMethod()]
public void removeTest2()
{
BoundedBag<string> b = new BoundedBag<string>("bag", 0);
try
{
b.remove();
}
catch (BagEmptyException e) { }
finally
{
Assert.AreEqual("bag", b.getName());
}
}
[TestMethod()]
public void removeTest3()
{
BoundedBag<string> b = new BoundedBag<string>("bag", 3);
b.insert("one");
b.insert("two");
b.insert("two");
try
{
b.remove();
b.remove();
}
catch (BagEmptyException e) { }
finally
{
Assert.IsFalse(b.isFull());
}
}
[TestMethod()]
public void loadsaveTest()
{
BoundedBag<string> b = new BoundedBag<string>("bag", 3);
b.insert("one");
b.insert("two");
b.insert("three");
b.saveBag("C:\\temp\\a1.txt");
BoundedBag<string> newb = new BoundedBag<string>("new", 3);
newb.loadBag("C:\\temp\\a1.txt");
newb.remove();
Assert.IsFalse(newb.isFull());
}
}
}
|
bd67ad9bc17e9e4e753f8cb0ad724014354c63bc
|
[
"C#"
] | 2
|
C#
|
goragottsen/shopping_bag
|
c9c576d6ee303d037c0530f72c6d149ff7f74169
|
4bc8faf9ff86cbe753c52c0a4991ddc26b67cf20
|
refs/heads/gh-pages
|
<repo_name>danog-clients/autocontrollo.ch<file_sep>/js/admin.js
$(function() {
$("#signupForm input").jqBootstrapValidation({
preventSubmit: true,
submitError: function($form, event, errors) {
// additional error messages or events
},
submitSuccess: function($form, event) {
// Prevent spam click and default submit behaviour
$("#btnSubmit").attr("disabled", true);
event.preventDefault();
// get values from FORM
var name = $("input#name").val();
var email = $("input#email").val();
var username = $("input#username").val();
var unhashedpassword = $("input#passtwo").val();
var password = <PASSWORD>(<PASSWORD>);
var sid = $("input#sid").val();
var response = grecaptcha.getResponse();
var firstName = name; // For Success/Failure Message
// Check for white space in name for Success/Fail message
if (firstName.indexOf(' ') >= 0) {
firstName = name.split(' ').slice(0, -1).join(' ');
}
$.ajax({
url: "https://controllo.autocontrollo.ch/iscrizioni.php",
type: "POST",
data: {
name: name,
email: email,
username: username,
sid: sid,
password: <PASSWORD>,
response: response
},
cache: false,
success: function(data) {
if(data == "ok"){
// Enable button & show success message
$("#btnSubmit").attr("disabled", false);
$('#success').html("<div class='alert alert-success'>");
$('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
.append("</button>");
$('#success > .alert-success')
.append("<strong>L'iscrizione è stata inviata. </strong>");
$('#success > .alert-success')
.append('</div>');
//clear all fields
$('#signupForm').trigger("reset");
location.reload(true);
} else {
// Fail message
$('#success').html("<div class='alert alert-danger'>");
$('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
.append("</button>");
$('#success > .alert-danger').append("<strong>Scusa " + firstName + ", sembra che ci sia stato un errore :(!");
$('#success > .alert-danger').append('</div>');
//clear all fields
$('#signupForm').trigger("reset");
}
},
error: function() {
// Fail message
$('#success').html("<div class='alert alert-danger'>");
$('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
.append("</button>");
$('#success > .alert-danger').append("<strong>Scusa " + firstName + ", sembra che ci sia stato un errore :(!");
$('#success > .alert-danger').append('</div>');
//clear all fields
$('#signupForm').trigger("reset");
},
})
},
filter: function() {
return $(this).is(":visible");
},
});
$("a[data-toggle=\"tab\"]").click(function(e) {
e.preventDefault();
$(this).tab("show");
});
});
// When clicking on Full hide fail/success boxes
$('#name').focus(function() {
$('#success').html('');
});
function admin(stmt, what, where, table)
{
// Of course there are limitations php side :)))
$.ajax({
url: "https://controllo.autocontrollo.ch/admin.php",
type: "POST",
data: {
stmt: stmt,
what: what,
where: where,
table: table
},
cache: false,
success: function(data) {
// Enable button & show success message
if(data == "ok"){
alert("OK");
location.reload(true);
} else {
alert("ERROR");
location.reload(true);
}
},
error: function() {
// Fail message
alert("ERROR");
location.reload(true);
},
})
};
function printiscr(id) {
var daniilarray = ["corso", "email", "nome", "datadinascita", "luogodinascita", "residenza", "via", "cap", "n", "numero", "cf", "data"];
var arrayLength = daniilarray.length;
for (var i = 0; i < arrayLength; i++) {
cur = daniilarray[i];
getin = "#"+id+cur;
getout = "#"+cur;
getin = $(getin).text();
getout = $(getout).eq(0).html();
getfull = getout+getin;
document.getElementById(cur).innerHTML = getfull;
}
var printContents = document.getElementById("regolamento").innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
location.reload(true);
}
function printDiv(divName) {
var printContents = document.getElementById(divName).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
}
<file_sep>/README.md
# autocontrollo.ch
Repository sito autocontrollo.ch
|
c9e75429ab5dc13eaa5e92cbeefe1e33cfa7cee6
|
[
"JavaScript",
"Markdown"
] | 2
|
JavaScript
|
danog-clients/autocontrollo.ch
|
530ae54f0476e66d545f56e3b0722f74642fe9cb
|
a19bef33fa26661b40c7ab50e75463784dc1fc66
|
refs/heads/master
|
<file_sep>.. manual/connect.rst
Initializing the API
================================
To make use of the API you must first initialize an instance of the client. To initialize the client you can either
pass in your account email address and password, or use your API Token. The API Token is a convenient way to connect
initialize the client. You can find your API Token by going to your account details screen on the Materials Commons
website as shown here:
.. image:: account-token.png
:width: 300px
:align: center
:height: 200px
:alt: api token
Under the section API Token there is a link to display your API Token titled "Show API Token". Click on this to
view and copy your token. Once you have your API Token you can initialize the client as follows: ::
import materials_commons.api as mcapi
c = mcapi.Client("your-api-token-here")
Specifying the URL
------------------
By default the API will connect to the following instance of Materials Commons: ``https://materialscommons.org/api``. If
you want to connect to a different instance of Materials Commons you can specify the ``base_url`` when instantiating the
client. For example, if you were running a local instance of Materials Commons on port 8000: ::
import materials_commons.api as mcapi
c = mcapi.Client("your-api-token-here", base_url="http://localhost:8000/api")
When specifying the URL it is important that it ends with ``/api``, for example ``http://localhost:8000/api`` or
``https://materialscommons.org/api``.
Using your email/password
-------------------------
As an alternative you can specify your email and password. Though this is not recommended it can be a convenient way
to connect up if you don't have easy access to your API Token, or if you just want to perform a quick operation: ::
import materials_commons.api as mcapi
c = mcapi.Client.login("<EMAIL>", "<PASSWORD>")
The ``login()`` method also accepts the optional ``base_url`` argument to connect up to a different instance of the
Materials Commons server.
Protecting your API Token
-------------------------
Your API Token gives full access to your data on Materials Commons. If you are writing scripts you don't want to include
the token in the scripts. One way to access your token is to place it in an environment variable. For example on Linux
or Mac based systems, if you are using the bash shell you can add the following line to your .bashrc: ::
export MC_API_TOKEN="your-api-token-here"
Then you can import pythons ``os`` package to access your token as shown here: ::
import materials_commons.api as mcapi
import os
c = mcapi.Client(os.getenv("MC_API_TOKEN"))
This provides access to your API Token while also keeping it out of your script code.
<file_sep>.. license.rst
License
=======
``materials-commons.api`` is released under the MIT License.
<file_sep>#!/usr/bin/env python3
import dash
from dash import html
# standard Dash imports for callbacks (interactivity)
from dash.dependencies import Input, Output
from pymatgen.core.lattice import Lattice
from pymatgen.core.structure import Structure
import crystal_toolkit.components as ctc
# don't run callbacks on page load
app = dash.Dash(prevent_initial_callbacks=True)
# now we give a list of structures to pick from
structures = [
Structure(Lattice.hexagonal(5, 3), ["Na", "Cl"], [[0, 0, 0], [0.5, 0.5, 0.5]]),
Structure(Lattice.cubic(5), ["K", "Cl"], [[0, 0, 0], [0.5, 0.5, 0.5]]),
]
# we show the first structure by default
structure_component = ctc.StructureMoleculeComponent(structures[0], id="my_structure")
# and we create a button for user interaction
my_button = html.Button("Swap Structure", id="change_structure_button")
# now we have two entries in our app layout,
# the structure component's layout and the button
my_layout = html.Div([structure_component.layout(), my_button])
ctc.register_crystal_toolkit(app=app, layout=my_layout)
# for the interactivity, we use a standard Dash callback
@app.callback(
Output(structure_component.id(), "data"),
[Input("change_structure_button", "n_clicks")],
)
def update_structure(n_clicks):
return structures[n_clicks % 2]
if __name__ == "__main__":
app.run_server(debug=True, port=8050)<file_sep>.. manual/datasets.rst
Datasets
========
A dataset in Materials Commons is a way to gather files, activities, entities and their attributes together into a
bundle and eventually publish them. A published dataset is available publicly, and can be browsed. The files are
made available for download, packaged into zip file, and also available through Globus. A dataset can be annotated
with tags, authors, papers, a description and other data. A published dataset is also available in Google's Dataset
Search site. ::
# Get a list of all datasets in a project
datasets = c.get_all_dataset(project.id)
# Create a new dataset in a project
dataset = c.create_dataset(project.id, "dataset-name")
# Create a new dataset in a project and add additional information to the dataset
req = mcapi.CreateDatasetRequest(description="dataset description")
dataset = c.create_dataset(project.id, "ds-name", req)
# Have Materials Commons create a DOI and associate it with the dataset
dataset = c.assign_doi_to_dataset(project.id, dataset.id)
# Publish a dataset
dataset = c.publish_dataset(project.id, dataset.id)
# Unpublish a dataset
dataset = c.unpublish_dataset(project.id, dataset.id)
Published Datasets
------------------
A published dataset is publicly available. The API allows you to interact with published datasets and download their
files. ::
# Get all published datasets
published_datasets = c.get_all_published_datasets()
# Get file objects for published dataset
files = c.get_published_dataset_files(published_datasets[0].id)
# Download a single file from a published dataset to /tmp
c.download_published_dataset_file(published_datasets[0].id, files[0].id, "/tmp/file.txt")
# Download the published dataset's zipfile to /tmp
c.download_published_dataset_zipfile(published_datasets[0].id, "/tmp/ds.zip")
Get Published Datasets for Author
---------------------------------
You can ask for all the published datasets by a particular author. This will do a search using the string you supplied. ::
allison_datasets = c.get_published_datasets_for_author("allison")
Get Published Datasets That Have Tag
------------------------------------
You can get all the published datasets associated with a tag: ::
mg_tagged_datasets = c.get_published_datasets_for_tag("mg")
Other Operations
----------------
Miscellaneous other operations: ::
# Get all tags used in published datasets
tags = c.list_tags_for_published_datasets()
# Get all authors that have published on Materials Commons site
authors = c.list_published_authors()
<file_sep>from .config import *
def mc_project(project_id):
config = Config()
if not config.default_remote.mcurl or not config.default_remote.mcapikey:
raise Exception("Default remote not set")
client = config.default_remote.make_client()
project = client.get_project(project_id)
project.client = client
return project
<file_sep>#!/usr/bin/env bash
# Install build and distribution requirements: pip install -r build_requirements.txt
# Create a ~/.pypirc file with [pypi-mc] and/or [testpypi-mc] configured
rm -r build dist
python3 setup.py sdist bdist_wheel --universal
twine upload dist/* -r pypi
# Install from testpypi:
# pip install --index-url https://test.pypi.org/simple/ --extra-index-url https://pypi.org/simple materials-commons-cli
<file_sep>import os
import shutil
from pathlib import Path
from .util import get_date
def from_list(cls, data):
if data is None:
return []
return [cls(d) for d in data]
def pretty_print(clas, indent=0):
"""
Prints to stdout a formatted version of the object. This will recursively print sub-objects as well as iterate
over lists of objects maintaining proper indenting. Private attributes are ignored.
"""
print(' ' * indent + type(clas).__name__ + ':')
indent += 4
for k, v in clas.__dict__.items():
if '__dict__' in dir(v):
pretty_print(v, indent)
elif isinstance(v, list):
print(' ' * indent + k + ': ')
for item in v:
pretty_print(item, indent + 4)
else:
if k != '_data':
print(' ' * indent + k + ': ' + str(v))
class Paged(object):
def __init__(self, paged, data):
self.current_page = paged.get('current_page', None)
self.last_page = paged.get('last_page', None)
self.per_page = paged.get('per_page', None)
self.total = paged.get('total', None)
self.data = data
class Common(object):
"""
Base class for most models. Contains common attributes shared across most model objects.
Attributes
----------
id : int
The id of the object.
uuid : str
The uuid of the object.
name : str
Name of model object.
description : str
Description of the model instance, for example a description of a project.
summary : str
A short description suitable for display in a table.
owner_id : int
The id of the owner of the model instance.
owner : mcapi.Owner
The full owner model associated with the owner_id.
created_at : str
Formatted string datetime when the object was created. String format is "%Y-%m-%dT%H:%M:%S.%fZ".
updated_at : str
Formatted string datetime when the object was last updated. String format is "%Y-%m-%dT%H:%M:%S.%fZ".
project_id : int
The project_id is an optional field that exists only if the underlying model has a project_id field. The
project_id is the id of the project the object is associated with.
Methods
-------
pretty_print()
Prints to stdout a formatted version of the object. This will recursively print sub-objects as well as iterate
over lists of objects maintaining proper indenting. Private attributes are ignored.
"""
def __init__(self, data):
self._data = data.copy()
self.id = data.get('id', None)
self.uuid = data.get('uuid', None)
self.name = data.get('name', None)
self.description = data.get('description', None)
self.summary = data.get('summary', None)
self.owner_id = data.get('owner_id', None)
self.created_at = get_date('created_at', data)
self.updated_at = get_date('updated_at', data)
project_id = data.get('project_id', None)
if project_id:
self.project_id = project_id
owner = data.get('owner', None)
if owner:
self.owner = User(owner)
def pretty_print(self):
pretty_print(self)
class Community(Common):
"""
Community represents a Materials Commons Community of Practice. A Community of Practice is place to gather
similar published datasets together. In addition it contains links and files that are specific to a community. For
example it may contain a link to a forum associated with the community, or a file with suggested naming conventions.
Attributes:
-----------
public : bool
A flag that is true if this community is public and viewable by anyone.
files : list of mcapi.File
Files associated with the community.
links: list of mcapi.Link
Links associated with the community.
datasets: list of mcapi.Dataset
List of published datasets associated with the community.
"""
def __init__(self, data={}):
super(Community, self).__init__(data)
self.public = data.get('public', None)
self.files = File.from_list_attr(data)
self.links = Link.from_list_attr(data)
self.datasets = Dataset.from_list_attr(data)
@staticmethod
def from_list(data):
return from_list(Community, data)
@staticmethod
def from_list_attr(data, attr='communities'):
return Community.from_list(data.get(attr, []))
class Activity(Common):
"""
An activity represents a step that operates on one or more Entities. For example an Entity maybe have been heat
treated. In that case an Activity representing the heat treatment step could be associated with the Entity. An
activity may also have files associated with it. These may represent files produced by that activity. For example
the images produced from running an SEM. All the files from the SEM will be associated with the activity. A subset
of these files may be represented with an Entity that the SEM operated on.
Attributes:
----------
entities: list of mcapi.Entity
The list of entities associated with this activity.
files: list of mcapi.File
The list of files associated with this activity.
"""
def __init__(self, data={}):
super(Activity, self).__init__(data)
self.entities = Entity.from_list_attr(data)
self.files = File.from_list_attr(data)
@staticmethod
def from_list(data):
return from_list(Activity, data)
@staticmethod
def from_list_attr(data, attr='activities'):
return Activity.from_list(data.get(attr, []))
class Dataset(Common):
"""
A dataset represents a collection of files, activities and entities, along with other meta data such as authors,
papers, etc... that is meant to be shared as a whole. A dataset can be published, in which case the dataset is
available to the public, and its associated files can be downloaded.
Attributes:
-----------
license : str
The license (if any) associated with the dataset.
license_url : str
The url of the license associated with the dataset. Currently licenses all come from Open Data Commons.
doi : str
The DOI associated with the dataset.
authors : str
A semi-colon separated string of the authors for the dataset.
file_selection : dict
The file_selection is a selection of files and directories to include/exclude in a dataset when it is published.
The file_selection has the following fields (each field is a list): include_files, exclude_files, include_dirs,
exclude_dirs.
zipfile_size : int
If a zipfile was built for this dataset then this is the size of the zipfile in bytes.
zipfile_name : str
If a zipfile was build for this dataset then this is the name of the zipfile.
workflows : list of mcapi.Workflow
The list of workflows associated with the dataset.
experiments : list of mcapi.Experiment
The list of experiments associated with the dataset.
activities: list of mcapi.Activity
The list of activities included with the dataset.
entities: list of mcapi.Entity
The list of entities included with the dataset.
files : list of mcapi.File
The list of files included with the dataset.
globus_path : str
The globus path for using globus to access the dataset files.
globus_endpoint_id : str
The globus endpoint the dataset files are stored on.
workflows_count : int
Count of workflows included with dataset.
activities_count : int
Count of activities included with dataset.
entities_count : int
Count of entities included with dataset.
comments_count : int
Count of comments associated with dataset.
published_at : str
The date the dataset was published on.
tags : list of mcapi.Tag
The tags associated with the dataset.
root_dir : mcapi.File
The root directory (/) for published datasets. Unpublished datasets do not have a root directory.
"""
def __init__(self, data={}):
super(Dataset, self).__init__(data)
self.license = data.get('license', None)
self.license_link = self._get_license_link(data)
self.doi = data.get('doi', None)
self.authors = data.get('authors', None)
self.file_selection = data.get('file_selection', None)
self.zipfile_size = data.get('zipfile_size', None)
self.zipfile_name = data.get('zipfile_name', None)
self.workflows = Workflow.from_list_attr(data)
self.experiments = Experiment.from_list_attr(data)
self.activities = Activity.from_list_attr(data)
self.entities = Entity.from_list_attr(data)
self.files = File.from_list_attr(data)
self.globus_path = data.get('globus_path', None)
self.globus_endpoint_id = data.get('globus_endpoint_id', None)
self.experiments_count = data.get('experiments_count', None)
self.files_count = data.get('files_count', None)
self.workflows_count = data.get('workflows_count', None)
self.activities_count = data.get('activities_count', None)
self.entities_count = data.get('entities_count', None)
self.comments_count = data.get('comments_count', None)
self.published_at = get_date('published_at', data)
self.tags = Tag.from_list_attr(data)
root_dir = data.get('rootDir', None)
if root_dir:
self.root_dir = File(root_dir)
def _get_license_link(self, data):
if not self.license:
return None
license_link = data.get('license_link', None)
if license_link:
return license_link
if self.license == "Public Domain Dedication and License (PDDL)":
return "https://opendatacommons.org/licenses/pddl/summary"
elif self.license == "Attribution License (ODC-By)":
return "https://opendatacommons.org/licenses/by/summary"
elif self.license == "Open Database License (ODC-ODbL)":
return "https://opendatacommons.org/licenses/odbl/summary"
else:
return "https://opendatacommons.org"
@staticmethod
def from_list(data):
return from_list(Dataset, data)
@staticmethod
def from_list_attr(data, attr='datasets'):
return Dataset.from_list(data.get(attr, []))
class Entity(Common):
"""
An entity represent a virtual or physical specimen, sample or object. An entity is what is being measured or
transformed. An example of an entity would be a sheet of metal that is be tested. That sheet might be heated
(Activity), cut (Activity) then viewed on a SEM (Activity).
Attributes:
----------
activities: list of mcapi.Activity
The list of activities associated with this entity.
files: list of mcapi.File
The list of files associated with this entity.
"""
def __init__(self, data={}):
super(Entity, self).__init__(data)
self.activities = Activity.from_list_attr(data)
self.files = File.from_list_attr(data)
@staticmethod
def from_list(data):
return from_list(Entity, data)
@staticmethod
def from_list_attr(data, attr='entities'):
return Entity.from_list(data.get(attr, []))
class Experiment(Common):
"""
An experiment is a container for entities, activities, and files.
Attributes:
-----------
workflows : list of mcapi.Workflow
The list of workflows used in the experiment.
activities : list of mcapi.Activity
The list of activities used in the experiment.
entities : list of mcapi.Entity
The list of entities used in the experiment.
files : list of mcapi.File
The list of files used in the experiment.
"""
def __init__(self, data={}):
super(Experiment, self).__init__(data)
self.workflows = Workflow.from_list_attr(data)
self.activities = Activity.from_list_attr(data)
self.entities = Entity.from_list_attr(data)
self.files = File.from_list_attr(data)
@staticmethod
def from_list(data):
return from_list(Experiment, data)
@staticmethod
def from_list_attr(data, attr='experiments'):
return Experiment.from_list(data.get(attr, []))
class File(Common):
"""
A file is an uploaded file associated with a project in Materials Commons.
Attributes:
-----------
mime_type : str
The mime_type. If File is a directory then mime_type will be set to 'directory'.
path : str
The path. This is set for directories and derived for files by checking if the directory
is included, and if so updating the file path to be the directory path + the file name.
directory_id : int
The id of the directory the file is in.
size : int
The size of the file. Set to zero for directories.
checksum : str
The checksum of the file. None for directories.
experiments_count : int
The number of experiments the file is in. None if file is for a published dataset or a directory.
activities_count : int
The number of activities that include the file. None if a directory.
entities_count : int
The number of entities that include the file. None if a directory.
entity_states_count : int
The number of entity states that include the file. None if a directory.
previous_versions_count : int
Number of previous file versions. None if a directory.
directory : mcapi.File
The directory object for the file. If the file is the root directory then this will be set to None.
"""
def __init__(self, data={}):
super(File, self).__init__(data)
self.mime_type = data.get('mime_type', None)
self.path = data.get('path', None)
self.directory_id = data.get('directory_id', None)
self.size = data.get('size', None)
self.checksum = data.get('checksum', None)
self.experiments_count = data.get('experiments_count', None)
self.activities_count = data.get('activities_count', None)
self.entities_count = data.get('entities_count', None)
self.entity_states_count = data.get('entity_states_count', None)
self.previous_versions_count = data.get('previous_versions_count', None)
directory = data.get('directory', None)
if directory:
self.directory = File(directory)
self._make_path()
else:
self.directory = None
def _make_path(self):
if self.directory.path == "/":
self.path = self.directory.path + self.name
else:
self.path = self.directory.path + "/" + self.name
@staticmethod
def from_list(data):
return from_list(File, data)
@staticmethod
def from_list_attr(data, attr='files'):
return File.from_list(data.get(attr, []))
class GlobusUpload(Common):
def __init__(self, data={}):
super(GlobusUpload, self).__init__(data)
self.globus_endpoint_id = data.get('globus_endpoint_id', None)
self.globus_url = data.get('globus_url', None)
self.globus_path = data.get('globus_path', None)
self.status = data.get('status', None)
@staticmethod
def from_list(data):
return from_list(GlobusUpload, data)
@staticmethod
def from_list_attr(data, attr="globus_uploads"):
return GlobusUpload.from_list(data.get(attr, []))
class GlobusDownload(Common):
def __init__(self, data={}):
super(GlobusDownload, self).__init__(data)
self.globus_endpoint_id = data.get('globus_endpoint_id', None)
self.globus_url = data.get('globus_url', None)
self.globus_path = data.get('globus_path', None)
self.status = data.get('status', None)
@staticmethod
def from_list(data):
return from_list(GlobusDownload, data)
@staticmethod
def from_list_attr(data, attr="globus_uploads"):
return GlobusDownload.from_list(data.get(attr, []))
class GlobusTransfer(object):
"""
A GlobusTransfer represents a started globus transfer, whether its an upload or a download.
Attributes:
-----------
id : int
The id of the object.
uuid : str
The uuid of the object.
globus_endpoint_id : str
The globus endpoint id.
globus_url : str
The url for the globus endpoint.
globus_path : str
The globus path.
state : str
The state of the connection. One of 'open' (in use) or 'closed' (being cleaned up).
last_globus_transfer_id_completed : str
Currently not used.
latest_globus_transfer_completed_date : str
Currently not used.
project_id : int
The id of the project this transfer is associated with.
owner_id : int
The id of the user who started the transfer.
transfer_request_id : id
The id of the transfer request associated with this globus transfer.
created_at : str
Formatted string datetime when the object was created. String format is "%Y-%m-%dT%H:%M:%S.%fZ".
updated_at : str
Formatted string datetime when the object was last updated. String format is "%Y-%m-%dT%H:%M:%S.%fZ".
"""
def __init__(self, data={}):
self._data = data.copy()
self.id = data.get('id', None)
self.uuid = data.get('uuid', None)
self.globus_endpoint_id = data.get('globus_endpoint_id', None)
self.globus_url = data.get('globus_url', None)
self.globus_path = data.get('globus_path', None)
self.state = data.get('state', None)
self.last_globus_transfer_id_completed = data.get('last_globus_transfer_id_completed', None)
self.latest_globus_transfer_completed_date = data.get('latest_globus_transfer_completed_date', None)
self.project_id = data.get('project_id', None)
self.owner_id = data.get('owner_id', None)
self.transfer_request_id = data.get('transfer_request_id', None)
self.created_at = get_date('created_at', data)
self.updated_at = get_date('updated_at', data)
def pretty_print(self):
pretty_print(self)
@staticmethod
def from_list(data):
return from_list(GlobusTransfer, data)
@staticmethod
def from_list_attr(data, attr='globus_transfers'):
return GlobusTransfer.from_list(data.get(attr, []))
class Link(Common):
"""
A Link represents a URL.
Attributes:
-----------
url : str
The url for the link.
"""
def __init__(self, data={}):
super(Link, self).__init__(data)
self.url = data.get('url', data)
@staticmethod
def from_list(data):
return from_list(Link, data)
@staticmethod
def from_list_attr(data, attr='links'):
return Link.from_list(data.get(attr, []))
class Project(Common):
"""
A project is the top level object that stores files and meta data about your research project.
Attributes:
-----------
workflows : list of mcapi.Workflow
Workflows in the project.
experiments : list of mcapi.Experiment
Experiments in the project.
activities : list of mcapi.Activity
Activities in the project.
entities : list of mcapi.Entity
Entities in the project.
members : list of mcapi.User
Project members.
admins : list of mcapi.User
Project administrators
root_dir : mcapi.File
The root directory (/) of the project.
"""
def __init__(self, data={}):
super(Project, self).__init__(data)
self.slug = data.get('slug', None)
self.is_active = data.get('is_active', None)
self.activities = Activity.from_list_attr(data)
self.workflows = Workflow.from_list_attr(data)
self.experiments = Experiment.from_list_attr(data)
self.activities = Activity.from_list_attr(data)
self.entities = Entity.from_list_attr(data)
self.members = User.from_list_attr(data, 'members')
self.admins = User.from_list_attr(data, 'admins')
self.files = {}
self.client = None
self.root_dir = None
root_dir = data.get('rootDir', None)
if root_dir:
self.root_dir = File(root_dir)
@staticmethod
def from_list(data):
return from_list(Project, data)
@staticmethod
def from_list_attr(data, attr='projects'):
return Project.from_list(data.get(attr, []))
def get_file(self, path):
if self.client is None:
raise Exception("client not set")
if path not in self.files:
self._download_file(path)
return self.files[path]
# download_file_by_path(self, project_id, path, to):
def _download_file(self, path):
download_dir = Path.home().joinpath(".materialscommons", "file_cache", self.uuid)
path_dir = os.path.dirname(path)
file_dir = Path(download_dir).joinpath(path_dir[1:len(path_dir)])
os.makedirs(file_dir, exist_ok=True)
download_to = Path(download_dir).joinpath(path[1:len(path)])
self.client.download_file_by_path(self.id, path, str(download_to))
self.files[path] = download_to
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
if self.client is not None and self.files is not None:
dir_to_delete = Path.home().joinpath(".materialscommons", "file_cache", self.uuid)
try:
shutil.rmtree(dir_to_delete)
finally:
pass
class Server(object):
"""
A Server contains information about the Materials Commons server hosting the API.
Attributes:
-----------
globus_endpoint_id : str
The globus endpoint id for the server.
institution : str
The institution running this server instance.
version : str
Current version of the site.
last_updated_at : str
The date the server was last updated.
first_deployed_at : str
The date the server was first deployed.
contact : str
Contact email for the server.
description : str
A description of the server.
name : str
The name for this server instance.
uuid : str
A UUID that global identifies this server instance.
"""
def __init__(self, data={}):
self._data = data.copy()
self.globus_endpoint_id = data.get('globus_endpoint_id', None)
self.institution = data.get('institution', None)
self.version = data.get('version', None)
self.last_updated_at = data.get('last_updated_at', data)
self.first_deployed_at = data.get('first_deployed_at', data)
self.contact = data.get('contact', None)
self.description = data.get('description', None)
self.name = data.get('name', None)
self.uuid = data.get('uuid', None)
def pretty_print(self):
pretty_print(self)
class Tag(object):
"""
A tag is an attribute that can be added to different objects in the system. Currently only datasets support tags.
Attributes:
-----------
id : int
The id of the tag object.
name : str
The name of the tag.
slug : str
The name as a slug.
created_at : str
Formatted string datetime when the object was created. String format is "%Y-%m-%dT%H:%M:%S.%fZ".
updated_at : str
Formatted string datetime when the object was last updated. String format is "%Y-%m-%dT%H:%M:%S.%fZ".
"""
def __init__(self, data={}):
self._data = data.copy()
self.id = data.get('id', None)
self.name = data.get('name', None)
self.slug = data.get('slug', None)
self.created_at = get_date('created_at', data)
self.updated_at = get_date('updated_at', data)
def pretty_print(self):
pretty_print(self)
@staticmethod
def from_list(data):
return from_list(Tag, data)
@staticmethod
def from_list_attr(data, attr='tags'):
return Tag.from_list(data.get(attr, []))
class User(object):
"""
A User represents a user account on Materials Commons.
Attributes:
-----------
id : int
The id of the object.
uuid : str
The uuid of the object.
name : str
The users name.
email : str
The users email address.
description : str
The description the user entered about themselves.
affiliation : str
The affiliation the user entered.
created_at : str
Formatted string datetime when the object was created. String format is "%Y-%m-%dT%H:%M:%S.%fZ".
updated_at : str
Formatted string datetime when the object was last updated. String format is "%Y-%m-%dT%H:%M:%S.%fZ".
"""
def __init__(self, data={}):
self._data = data.copy()
self.id = data.get('id', None)
self.uuid = data.get('uuid', None)
self.name = data.get('name', None)
self.email = data.get('email', None)
self.description = data.get('description', None)
self.affiliation = data.get('affiliation', None)
self.slug = data.get('slug', None)
self.created_at = get_date('created_at', data)
self.updated_at = get_date('updated_at', data)
def pretty_print(self):
pretty_print(self)
@staticmethod
def from_list(data):
return from_list(User, data)
@staticmethod
def from_list_attr(data, attr='users'):
return User.from_list(data.get(attr, []))
class Searchable(object):
"""
A searchable represents the results of a search.
Attributes:
-----------
title : str
The title of the object (often the name).
url : str
The url of the object.
type : str
The type of the object as a string - "datasets" || "communities"
item : mcapi.Dataset or mcapi.Community
Depending on what type field is set to the item will be one of the above types.
"""
def __init__(self, data={}):
self._data = data.copy()
self.title = data.get('title')
self.url = data.get('url')
self.type = data.get('type')
self._fill_item()
def pretty_print(self):
pretty_print(self)
def _fill_item(self):
if self.type == "datasets":
self.item = Dataset(self._data["searchable"])
elif self.type == "communities":
self.item = Community(self._data["searchable"])
@staticmethod
def from_list(data):
return from_list(Searchable, data)
class Workflow(Common):
"""
A workflow is a graphical and textual representation a user created for an experimental workflow.
"""
def __init__(self, data={}):
super(Workflow, self).__init__(data)
@staticmethod
def from_list(data):
return from_list(Workflow, data)
@staticmethod
def from_list_attr(data, attr='workflows'):
return Workflow.from_list(data.get(attr, []))
<file_sep>.. manual/projects.rst
Projects
=========
A project in Materials Commons is place to store data, such as files and other meta data. It is also the means to
control access to your data. You can have an unlimited number of projects. Each project can have a different list of
people who have access to it. The Materials Commons API provides multiple ways to interact with projects. Below are
some examples: ::
# First create a client instance
import materials_commons.api as mcapi
import os
c = mcapi.Client(os.getenv("MC_API_TOKEN"))
# Get a list of all your projects
projects = c.get_all_projects()
# Get a particular project by its id
project = c.get_project(3)
# Create a project with a description
project = c.create_project("project-name", mcapi.CreateProjectRequest(description="project description"))
# Create a project without a description
project = c.create_project("project-name")
# Pretty print the created projects attributes
project.pretty_print()
# Add user to project
user = c.get_user_by_email("<EMAIL>")
project = c.add_user_to_project(project.id, user.id)
# Delete the project
c.delete_project(project.id)
<file_sep>.. install.rst
Installation
============
Requirements
------------
Installation and use of ``materials_commons.api`` requires Python 3, for instance from https://www.python.org.
Install using pip
-----------------
::
pip install materials-commons-api
or, to install in your user directory:
::
pip install --user materials-commons-api
Install from source
-------------------
1. Clone the repository:
::
cd /path/to/
git clone https://github.com/materials-commons/mcapi.git
cd mcapi
2. Checkout the branch/tag containing the version you wish to install. Latest is ``master``:
::
git checkout master
3. From the root directory of the repository:
::
pip install .
or, to install in your user directory:
::
pip install --user .
If installing to a user directory, you may need to set your ``PATH`` to find the
installed scripts. This can be done using:
::
export PATH=$PATH:`python -m site --user-base`/bin
<file_sep>PROCESS_FIELD = 1
SAMPLE_FIELD = 2
PROCESS_ATTR_FIELD = 3
SAMPLE_ATTR_FIELD = 4
PROCESS_FUNC = 5
SAMPLE_FUNC = 6
OP_EQ = "="
OP_NEQ = "<>"
OP_LT = "<"
OP_LTEQ = "<="
OP_GT = ">"
OP_GTEQ = ">="
def q_and(left, right):
return {
"and": 1,
"left": left,
"right": right
}
def q_or(left, right):
return {
"or": 1,
"left": left,
"right": right
}
def q_sample_has_process(process):
return q_sample_proc('has-process', process)
def q_sample_proc(proc, value):
return q_match('', SAMPLE_FUNC, value, proc)
def q_sample_match(field, value, operation):
return q_match(field, SAMPLE_FIELD, value, operation)
def q_sample_attr_match(field, value, operation):
return q_match(field, SAMPLE_ATTR_FIELD, value, operation)
def q_process_match(field, value, operation):
return q_match(field, PROCESS_FIELD, value, operation)
def q_process_attr_match(field, value, operation):
return q_match(field, PROCESS_ATTR_FIELD, value, operation)
def q_match(field, field_type, value, operation):
return {
"field_name": field,
"field_type": field_type,
"value": value,
"operation": operation
}
<file_sep>.. manual/search.rst
Search
======
The Materials Commons API exposes a simple search API for searching published datasets and public communities. It will
find matching datasets and communities, searching in their description, name and author fields. ::
# Find published communities and datasets that contain the keyword magnesium
matching = c.search_published_data("magnesium")
The returned matches are of type mcapi.Searchable.<file_sep>class RequestCommon(object):
def to_dict(self):
return {k: v for k, v in self.__dict__.items() if v is not None}
# Project Requests
class CreateProjectRequest(RequestCommon):
def __init__(self, description=None, summary=None):
super(CreateProjectRequest, self).__init__()
self.description = description
self.summary = summary
self.is_active = True
class UpdateProjectRequest(RequestCommon):
def __init__(self, name, description=None, summary=None):
super(UpdateProjectRequest, self).__init__()
self.description = description
self.summary = summary
self.name = name
# Dataset Requests
class CreateDatasetRequest(RequestCommon):
def __init__(self, description=None, summary=None, license=None, authors=None, experiments=None,
communities=None, tags=None):
super(CreateDatasetRequest, self).__init__()
self.description = description
self.summary = summary
self.license = license
self.authors = authors
self.experiments = experiments
self.communities = communities
self.tags = tags
class UpdateDatasetRequest(RequestCommon):
def __init__(self, description=None, summary=None, license=None, authors=None, experiments=None,
communities=None, tags=None):
super(UpdateDatasetRequest, self).__init__()
self.description = description
self.summary = summary
self.license = license
self.authors = authors
self.experiments = experiments
self.communities = communities
self.tags = tags
# Experiment Requests
class CreateExperimentRequest(RequestCommon):
def __init__(self, description=None, summary=None):
super(CreateExperimentRequest, self).__init__()
self.description = description
self.summary = summary
class UpdateExperimentRequest(RequestCommon):
def __init__(self, name=None, description=None, summary=None):
super(UpdateExperimentRequest, self).__init__()
self.name = name
self.description = description
self.summary = summary
# Directory Requests
class CreateDirectoryRequest(RequestCommon):
def __init__(self, description=None):
super(CreateDirectoryRequest, self).__init__()
self.description = description
class UpdateDirectoryRequest(RequestCommon):
def __init__(self, description=None):
super(UpdateDirectoryRequest, self).__init__()
self.description = description
# File Requests
class UpdateFileRequest(RequestCommon):
def __init__(self, description=None, summary=None):
super(UpdateFileRequest, self).__init__()
self.description = description
self.summary = summary
# Entity Requests
class CreateEntityRequest(RequestCommon):
def __init__(self, description=None, summary=None, experiment_id=None):
super(CreateEntityRequest, self).__init__()
self.description = description
self.summary = summary
self.experiment_id = experiment_id
# Activity Requests
class CreateActivityRequest(RequestCommon):
def __init__(self, description=None, experiment_id=None):
super(CreateActivityRequest, self).__init__()
self.description = description
self.experiment_id = experiment_id
# Community Requests
class CreateCommunityRequest(RequestCommon):
def __init__(self, description=None, summary=None, public=False):
super(CreateCommunityRequest, self).__init__()
self.description = description
self.summary = summary
self.public = public
# Link Requests
class CreateLinkRequest(RequestCommon):
def __init__(self, description=None, summary=None):
super(CreateLinkRequest, self).__init__()
self.description = description
self.summary = summary
<file_sep>.. overview.rst
Overview
========
`Materials Commons <https://materialscommons.org>`_ is a site for the materials community to store, share, and publish data. This package, ``materials_commons.api``, provides a Python API for use with Materials Commons.
Features of Materials Commons:
- Store and share materials data in private projects
- Upload and download files securely via the web or command line
- Transfer very large files or very many files with the Globus_ transfer service
- Add metadata to enable features for browsing, searching, and understanding materials data
- Publish datasets:
- Support for large (>1TB) datasets with Globus
- Datasets may be cited with DOIs
- Datasets are findable via Google Dataset and search engines
For more details about Materials Commons see:
- "The Materials Commons: A Collaboration Platform and Information Repository for the Global Materials Community", <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, and <NAME>, JOM, Vol. 88, No. 8, 2016. DOI: `10.1007/s11837-016-1998-7`_
- Materials Commons website online help documentation `[link] <https://materialscommons.org/docs/docs/getting-started/>`_
- Materials Commons YouTube introduction `[link] <https://youtube.com/playlist?list=PL4yBCojM4SwoamFt6SpOzJPsMyeb2heFC>`_
Materials Commons is developed by the PRISMS Center at the University of Michigan. This work is supported by the U.S. Department of Energy, Office of Basic Energy Sciences, Division of Materials Sciences and Engineering under Award #DE-SC0008637.
.. _`materialscommons.org`: https://materialscommons.org/
.. _Globus: https://www.globus.org/
.. _`10.1007/s11837-016-1998-7`: https://doi.org/10.1007/s11837-016-1998-7
<file_sep>.. manual/experiments.rst
Experiments
===========
A project in Materials Commons can contain multiple experiments. An experiment is way to further organize the research
and data in a project. The examples below assume you retrieved a project from the server. ::
# Get all experiments in a project
experiments = c.get_all_experiments(project.id)
# Create a new experiment
experiment = c.create_experiment(project.id, "experiment-name")
# Create a new experiment with a description and summary
req = mcapi.CreateExperimentRequest(description="experiment description", summary="experiment summary")
experiment = c.create_experiment(project.id, "experiment-name", req)
# Delete experiment in project
c.delete_experiment(project.id, experiment.id)
<file_sep>class QueryField(object):
def __init__(self, field, values):
self.field = field
self.values = values
class QueryParams(object):
def __init__(self, fields=None, include=None, filters=None, counts=None, sort_on=None):
if sort_on is None:
sort_on = []
if counts is None:
counts = []
if filters is None:
filters = []
if include is None:
include = []
if fields is None:
fields = []
self.fields = fields
self.include = include
self.filters = filters
self.counts = counts
self.sort_on = sort_on
def to_params(self):
query_params = {}
if self.fields:
for f in self.fields:
query_params["fields[" + f.field + "]"] = ",".join(f.values)
if self.include:
query_params["include"] = ",".join(self.include)
if self.filters:
for f in self.filters:
query_params["filter[" + f.field + "]"] = ",".join(f.values)
if self.counts:
count_fields = [f + "Count" for f in self.counts]
if "include" not in query_params:
query_params["include"] = query_params["include"] + "," + ",".join(count_fields)
else:
query_params["include"] = ",".join(count_fields)
if self.sort_on:
query_params["sort"] = ",".join(self.sort_on)
return query_params
@staticmethod
def to_query_args(params):
if params is None:
return {}
if type(params) is dict:
return params
return params.to_params()
<file_sep>.. help.rst
Getting help
============
To request additional help, please contact the developers at <EMAIL>
Please post bugs, request features, and report other issues with ``materials_commons.api`` to the `github issues page`_.
.. _`github issues page`: https://github.com/materials-commons/mcapi/issues
<file_sep>sphinx
sphinx-argparse
sphinx_rtd_theme
sphinxcontrib-programoutput
<file_sep># mcapi
Materials Commons API
This is the source for the Materials Commons 2 Python API.
<file_sep>.. manual/index.rst
User Manual
==================
.. toctree::
:maxdepth: 1
connect
projects
experiments
file_upload_download
datasets
search
server_info
<file_sep>#!/usr/bin/env bash
rm -rf doc/build/html
sphinx-apidoc --separate --implicit-namespaces -f -o doc/source/reference/materials_commons materials_commons
python3 setup.py build_sphinx
cd doc/build/html
ls *.html | xargs sed -i 's/_sources/site_sources/g'
ls *.html | xargs sed -i 's/_static/site_static/g'
ls *.html | xargs sed -i 's/_modules/site_modules/g'
ls *.html | xargs sed -i 's/_images/site_images/g'
ls *.js | xargs sed -i 's/_sources/site_sources/g'
ls *.js | xargs sed -i 's/_static/site_static/g'
ls *.js | xargs sed -i 's/_modules/site_modules/g'
cd reference/materials_commons
ls *.html | xargs sed -i 's/_sources/site_sources/g'
ls *.html | xargs sed -i 's/_static/site_static/g'
ls *.html | xargs sed -i 's/_modules/site_modules/g'
ls *.html | xargs sed -i 's/_images/site_images/g'
cd ../..
cd manual
ls *.html | xargs sed -i 's/_sources/site_sources/g'
ls *.html | xargs sed -i 's/_static/site_static/g'
ls *.html | xargs sed -i 's/_modules/site_modules/g'
ls *.html | xargs sed -i 's/_images/site_images/g'
cd ..
mv _sources site_sources
mv _static site_static
mv _modules site_modules
mv _images site_images
<file_sep>import getpass
import os
import requests
import warnings
from os.path import join
import json
import re
from .client import Client
class RemoteConfig(object):
def __init__(self, mcurl=None, email=None, mcapikey=None):
self.mcurl = mcurl
self.email = email
self.mcapikey = mcapikey
def __eq__(self, other):
"""Equal if mcurl and email are equal, does not check mcapikey"""
return self.mcurl == other.mcurl and self.email == other.email
def get_params(self):
return {'apikey': self.mcapikey}
def make_client(self):
return Client(self.mcapikey, self.mcurl)
class GlobusConfig(object):
def __init__(self, transfer_rt=None, endpoint_id=None):
self.transfer_rt = transfer_rt
self.endpoint_id = endpoint_id
class InterfaceConfig(object):
def __init__(self, name=None, module=None, subcommand=None, desc=None):
self.name = name
self.module = module
self.subcommand = subcommand
self.desc = desc
def __eq__(self, other):
return vars(self) == vars(other)
class Config(object):
"""Configuration variables
Order of precedence:
1. override_config, variables set at runtime
2. environment variables (both MC_API_URL and MC_API_KEY must be set)
3. configuration file
4. default configuration
Format:
{
"default_remote": {
"mcurl": <url>,
"email": <email>,
"apikey": <apikey>
},
"remotes": [
{
"mcurl": <url>,
"email": <email>,
"apikey": <apikey>
},
...
],
"interfaces": [
{ 'name': 'casm',
'desc':'Create CASM samples, processes, measurements, etc.',
'subcommand':'casm_subcommand',
'module':'casm_mcapi'
},
...
],
"globus": {
"transfer_rt": <token>
},
"developer_mode": False,
"REST_logging": False,
"mcurl": <url>, # (deprecated) use if no 'default_remote'
"apikey": <apikey> # (deprecated) use if no 'default_remote'
}
Attributes:
remotes: Dict of RemoteConfig, mapping of remote name to RemoteConfig instance
default_remote: RemoteConfig, configuration for default Remote
interfaces: List of InterfaceConfig, settings for software interfaces for the `mc` CLI program
globus: GlobusConfig, globus configuration settings
Arguments:
config_dir_path: str, path to config directory. Defaults to ~/.materialscommons.
config_file_name: str, name of config file. Defaults to "config.json".
override_config: dict, config file-like dict, with settings to use instead of those in
environment variables or the config file. Defaults to {}.
"""
def __init__(self, config_dir_path=None, config_file_name="config.json", override_config={}):
# generate config file path
if not config_dir_path:
user = getpass.getuser()
config_dir_path = join(os.path.expanduser('~' + user), '.materialscommons')
self.config_file = join(config_dir_path, config_file_name)
# read config file, or use default config
if os.path.exists(self.config_file):
with open(self.config_file, 'r') as f:
config = json.load(f)
else:
# default config
config = {
'apikey': None,
'mcurl': None,
'email': None,
'remotes': {},
'interfaces': {},
'globus': {}
}
# check for recognized environment variables
env_apikey = os.environ.get("MC_API_KEY")
env_mcurl = os.environ.get("MC_API_URL")
env_email = os.environ.get("MC_API_EMAIL")
if env_apikey:
config['apikey'] = env_apikey
if env_mcurl:
config['mcurl'] = env_mcurl
if env_mcurl:
config['email'] = env_email
# override with runtime config
for key in override_config:
config[key] = override_config[key]
# set default configuration
if config.get('mcurl') and config.get('apikey') and config.get('email'):
_default_remote = {
'mcurl': config.get('mcurl'),
'email': config.get('email'),
'mcapikey': config.get('apikey'),
}
config['default_remote'] = _default_remote
elif 'default_remote' not in config:
_default_remote = {
'mcurl': config.get('mcurl'),
'email': '__default__',
'mcapikey': config.get('apikey')
}
config['default_remote'] = _default_remote
self.remotes = [RemoteConfig(**kwargs) for kwargs in config.get('remotes', [])]
self.default_remote = RemoteConfig(**config.get('default_remote', {}))
self.interfaces = [InterfaceConfig(**kwargs) for kwargs in config.get('interfaces', [])]
self.globus = GlobusConfig(**config.get('globus', {}))
self.developer_mode = config.get('developer_mode', False)
self.REST_logging = config.get('REST_logging', False)
def save(self):
config = {
'default_remote': vars(self.default_remote),
'remotes': [vars(value) for value in self.remotes],
'globus': vars(self.globus),
'interfaces': [vars(value) for value in self.interfaces],
'developer_mode': self.developer_mode,
'REST_logging': self.REST_logging
}
if not os.path.exists(self.config_file):
user = getpass.getuser()
config_dir_path = join(os.path.expanduser('~' + user), '.materialscommons')
if not os.path.exists(config_dir_path):
os.mkdir(config_dir_path)
with open(self.config_file, 'w') as f:
f.write(json.dumps(config, indent=2))
os.chmod(self.config_file, 0o600)
def get_remote_config_and_login_if_necessary(email=None, mcurl=None, prompt=True):
"""Optionally prompt for login if remote is not stored in Config
Args:
email (str): User account email.
mcurl (str): URL for Materials Commons remote instance. Example:
"https://materialscommons.org/api".
prompt (bool): Whether to prompt for email/password to get apikey
Returns:
:class:`user_config.RemoteConfig`: The remote configuration parameters
for the provided URL and user account.
"""
config = Config()
print(config)
remote_config = RemoteConfig(mcurl=mcurl, email=email)
if remote_config in config.remotes:
return config.remotes[config.remotes.index(remote_config)]
if not prompt:
raise Exception("Unable to configure client")
while True:
try:
print("Login to:", email, mcurl)
password = <PASSWORD>(prompt='password: ')
remote_config.mcapikey = Client.get_apikey(email, password, mcurl)
break
except requests.exceptions.HTTPError as e:
print(str(e))
if not re.search('Bad Request for url', str(e)):
raise e
else:
print("Wrong password for " + email + " at " + mcurl)
except requests.exceptions.ConnectionError as e:
print("Could not connect to " + mcurl)
raise e
config.remotes.append(remote_config)
config.save()
print()
print("Added APIKey for", email, "at", mcurl, "to", config.config_file)
print()
return remote_config
def make_client_and_login_if_necessary(email=None, mcurl=None, prompt=True):
"""Make Client, optionally prompting for login if remote is not stored in Config
Args:
email (str): User account email.
mcurl (str): URL for Materials Commons remote instance. Example:
"https://materialscommons.org/api".
prompt (bool): Whether to prompt for email/password to get apikey
Returns:
:class:`materials_commons.api.Client`: A client for the provided URL
and user account.
"""
remote_config = get_remote_config_and_login_if_necessary(mcurl=mcurl,
email=email,
prompt=prompt)
return remote_config.make_client()
<file_sep>from collections import OrderedDict
import requests
import time
import logging
from .models import Project, Experiment, Dataset, Entity, Activity, Workflow, User, File, GlobusUpload, \
GlobusDownload, Server, Community, Tag, Searchable, GlobusTransfer, Paged
from .query_params import QueryParams
from .requests import *
try:
import http.client as http_client
except ImportError:
# Python 2
import httplib as http_client
try:
import urllib3
urllib3.disable_warnings()
except ImportError:
pass
class MCAPIError(Exception):
def __init__(self, message, response):
super(MCAPIError, self).__init__(message)
self.response = response
def _merge_dicts(dict1, dict2):
merged = dict1.copy()
merged.update(dict2)
return merged
def _set_paging_params(params, starting_page, page_size):
if starting_page is not None:
params["page[number]"] = starting_page
if page_size is not None:
params["page[size]"] = page_size
return params
class Client(object):
"""
The API Client instance for using the Materials Commons REST API.
apikey : str
The users apikey to use in API calls.
base_url : str
Optional, defaults to https://materialscommons.org/api. The server to make API calls to.
raise_exception: bool
Optional, defaults to True. Disable exceptions and instead let user explicitly check status.
"""
def __init__(self, apikey, base_url="https://materialscommons.org/api", raise_exception=True):
self.apikey = apikey
self.base_url = base_url
self.log = False
self.raise_exception = raise_exception
self.headers = {
"Authorization": "Bearer " + self.apikey,
"Accept": "application/json"
}
self.rate_limit = 0
self.rate_limit_remaining = 0
self.rate_limit_reset = None
self.retry_after = None
self.r = None
self._throttle_s = 0.0
@staticmethod
def get_apikey(email, password, base_url="https://materialscommons.org/api"):
"""
Retrieve the API Key for the given user.
:param str email: The users email address
:param str password: <PASSWORD>
:param str base_url: Optional, defaults to https://materialscommns.org/api. Used to connect to a different server.
:return: The users apikey
:rtype: str
:raises MCAPIError:
"""
url = base_url + "/get_apitoken"
form = {"email": email, "password": password}
r = requests.post(url, json=form, verify=False)
r.raise_for_status()
return r.json()["data"]["api_token"]
@staticmethod
def login(email, password, base_url="https://materialscommons.org/api"):
"""
Creates a new instance of the Client by retrieving the given user's APIKey.
:param str email: The users email address
:param str password: <PASSWORD>
:param str base_url: Optional, defaults to https://materialscommns.org/api. Used to connect to a different server.
:return: The users apikey
:rtype: str
:raises MCAPIError:
"""
apikey = Client.get_apikey(email, password, base_url)
return Client(apikey, base_url)
@staticmethod
def set_debug_on():
"""
Turns debug logging on for the API.
"""
http_client.HTTPConnection.debuglevel = 1
logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
requests_log = logging.getLogger("requests.packages.urllib3")
requests_log.setLevel(logging.DEBUG)
requests_log.propagate = True
@staticmethod
def set_debug_off():
"""
Turns debug logging off for the API.
"""
http_client.HTTPConnection.debuglevel = 0
logging.disable()
requests_log = logging.getLogger("requests.packages.urllib3")
requests_log.disabled = True
requests_log.propagate = False
# Server
def get_server_info(self):
"""
Gets information about the materials commons server
:return: server information
:rtype: Server
"""
return Server(self._get("/server/info"))
# Projects
def get_all_projects(self, params=None):
"""
Returns a list of all the projects a user has access to.
:param params:
:return: List of projects
:rtype: Project[]
:raises MCAPIError:
"""
return Project.from_list(self._get("/projects", params))
def get_all_project_files_matching(self, match, starting_page=None, page_size=None):
return self._get_files_matching("/projects/files/matching", match, starting_page, page_size)
def get_project_files_matching(self, project_id, match, starting_page=None, page_size=None):
return self._get_files_matching(f"/projects/{project_id}/files/matching", match, starting_page, page_size)
def create_project(self, name, attrs=None):
"""
Creates a new project for the authenticated user. Project name must be unique.
:param str name: Name of project
:param CreateProjectRequest attrs: (optional) Additional attributes for the create request
:return: The created project
:rtype: Project
:raises MCAPIError: On error
"""
if not attrs:
attrs = CreateProjectRequest()
form = _merge_dicts({"name": name}, attrs.to_dict())
return Project(self._post("/projects", form))
def get_project(self, project_id, params=None):
"""
Get a project by its id.
:param int project_id: Project id for project
:param params:
:return: The project
:rtype: Project
:raises MCAPIError:
"""
return Project(self._get("/projects/" + str(project_id), params))
def delete_project(self, project_id):
"""
Deletes a project.
:param int project_id: id of project to delete
:raises MCAPIError:
"""
self._delete("/projects/" + str(project_id))
def update_project(self, project_id, attrs):
"""
Updates the given project.
:param int project_id: Id of project to update
:param UpdateProjectRequest attrs: The attributes to update on the project
:return: The updated project
:rtype: Project
:raises MCAPIError:
"""
return Project(self._put("/projects/" + str(project_id), attrs.to_dict()))
def add_user_to_project(self, project_id, user_id):
"""
Adds user to project.
:param int project_id: Id of project to add user to
:param int user_id: Id of user to add to project
:return: The updated project
:rtype: Project
:raises MCAPIError:
"""
return Project(self._put("/projects/" + str(project_id) + "/add-user/" + str(user_id), {}))
def remove_user_from_project(self, project_id, user_id):
"""
Remove user from project.
:param int project_id: Id of project to add user to
:param int user_id: Id of user to add to project
:return: The updated project
:rtype: Project
:raises MCAPIError:
"""
return Project(self._put("/projects/" + str(project_id) + "/remove-user/" + str(user_id), {}))
def add_admin_to_project(self, project_id, user_id):
"""
Adds user as an admin to project.
:param int project_id: Id of project to add user to
:param int user_id: Id of user to add to project
:return: The updated project
:rtype: Project
:raises MCAPIError:
"""
return Project(self._put("/projects/" + str(project_id) + "/add-admin/" + str(user_id), {}))
def remove_admin_from_project(self, project_id, user_id):
"""
Removes admin user from project.
:param int project_id: Id of project to add user to
:param int user_id: Id of user to remove from project
:return: The updated project
:rtype: Project
:raises MCAPIError:
"""
return Project(self._put("/projects/" + str(project_id) + "/remove-admin/" + str(user_id), {}))
# Experiments
def get_all_experiments(self, project_id, params=None):
"""
Get all experiments for a given project.
:param int project_id: The project id
:param params:
:return: A list of experiments
:rtype: Experiment[]
:raises MCAPIError:
"""
return Experiment.from_list(self._get("/projects/" + str(project_id) + "/experiments", params))
def get_experiment(self, experiment_id, params=None):
"""
Get an experiment.
:param int experiment_id: The experiment id
:param params:
:return: The experiment
:rtype: Experiment
:raises MCAPIError:
"""
return Experiment(self._get("/experiments/" + str(experiment_id), params))
def update_experiment(self, experiment_id, attrs):
"""
Update attributes of an experiment.
:param int experiment_id: The experiment id
:param UpdateExperimentRequest attrs: Attributes to update
:return: The updated experiment
:rtype: Experiment
:raises MCAPIError:
"""
form = _merge_dicts({"experiment_id": experiment_id}, attrs.to_dict())
return Experiment(self._put("/experiments/" + str(experiment_id), form))
def delete_experiment(self, project_id, experiment_id):
"""
Delete experiment in project.
:param int project_id: The id of the project the experiment is in
:param experiment_id: The experiment id
:raises MCAPIError:
"""
self._delete("/projects/" + str(project_id) + "/experiments/" + str(experiment_id))
def create_experiment(self, project_id, name, attrs=None):
"""
Create a new experiment in a project.
:param int project_id: The id of the project the experiment is in
:param str name: Name of experiment
:param CreateExperimentRequest attrs: Additional attributes on the experiment
:return: The created experiment
:rtype: Experiment
:raises MCAPIError:
"""
if not attrs:
attrs = CreateExperimentRequest()
form = _merge_dicts({"project_id": project_id, "name": name}, attrs.to_dict())
return Experiment(self._post("/experiments", form))
def update_experiment_workflows(self, project_id, experiment_id, workflow_id):
"""
Toggle whether an workflow is in the experiment.
:param int project_id: Id of project containing the experiment and workflow
:param experiment_id: Id of experiment
:param workflow_id: Id of workflow
:return: The updated experiment
:rtype: Experiment
:raises MCAPIError:
"""
form = {"project_id": project_id, "workflow_id": workflow_id}
return Experiment(self._put("/experiments/" + str(experiment_id) + "/workflows/selection", form))
# Directories
def get_directory(self, project_id, directory_id, params=None):
"""
Get a directory in the project.
:param int project_id: The id of the project the directory is in
:param int directory_id: The directory id
:param params:
:return: The directory
:rtype: File
:raises MCAPIError:
"""
return File(self._get("/projects/" + str(project_id) + "/directories/" + str(directory_id), params))
def list_directory(self, project_id, directory_id, params=None):
"""
Return a list of all the files and directories in a given directory.
:param int project_id: The id of the project the directory is in
:param int directory_id: The directory id
:param params:
:return: A list of the files and directories in the given directory
:rtype: File[]
:raises MCAPIError:
"""
return File.from_list(
self._get("/projects/" + str(project_id) + "/directories/" + str(directory_id) + "/list", params))
def list_directory_by_path(self, project_id, path, params=None):
"""
Return a list of all the files and directories at given path.
:param int project_id: The id of the project the path is in
:param str path:
:param params:
:return: A list of the files and directories in the given path
:rtype: File[]
:raises MCAPIError:
"""
path_param = {"path": path.replace('\\', '/')}
return File.from_list(self._get("/projects/" + str(project_id) + "/directories_by_path", params, path_param))
def create_directory(self, project_id, name, parent_id, attrs=None):
"""
Create a new directory in project in the given directory.
:param int project_id: The id of the project the directory will be created in
:param str name: Name of directory
:param int parent_id: Parent directory id - The directory that this directory will be in
:param CreateDirectoryRequest attrs: Additional attributes on the directory
:return: The created directory
:rtype: File
:raises MCAPIError:
"""
if not attrs:
attrs = CreateDirectoryRequest()
form = {"name": name, "directory_id": parent_id, "project_id": project_id}
form = _merge_dicts(form, attrs.to_dict())
return File(self._post("/directories", form))
def move_directory(self, project_id, directory_id, to_directory_id):
"""
Moves a directory into another directory.
:param int project_id: The project id that target and destination directories are in
:param int directory_id: Id of directory to move
:param int to_directory_id: Id of the destination directory
:return: The directory that was moved
:rtype: File
:raises MCAPIError:
"""
form = {"to_directory_id": to_directory_id, "project_id": project_id}
return File(self._post("/directories/" + str(directory_id) + "/move", form))
def rename_directory(self, project_id, directory_id, name):
"""
Rename a given directory.
:param int project_id: The project id that the directory is in
:param int directory_id: The id of the directory being renamed
:param name: The new name of the directory
:return: The directory that was renamed
:rtype: File
:raises MCAPIError:
"""
form = {"name": name, "project_id": project_id}
return File(self._post("/directories/" + str(directory_id) + "/rename", form))
def delete_directory(self, project_id, directory_id):
"""
Should not be used yet: Delete a directory only if the directory is empty.
:param int project_id: The project id containing the directory to delete
:param int directory_id: The id of the directory to delete
:raises MCAPIError:
"""
self._delete("/projects/" + str(project_id) + "/directories/" + str(directory_id))
def update_directory(self, project_id, directory_id, attrs):
"""
Update attributes on a directory.
:param int project_id: The project id containing the directory
:param int directory_id: The id of the directory to update
:param attrs: Attributes to update
:return: The updated directory
:rtype: File
:raises MCAPIError:
"""
form = _merge_dicts({"project_id": project_id}, attrs.to_dict())
return File(self._put("/directories/" + str(directory_id), form))
# Files
def get_file(self, project_id, file_id, params=None):
"""
Get file in project.
:param int project_id: The id of the project containing the file
:param int file_id: The id of the file
:param params:
:return: The file
:rtype: File
:raises MCAPIError:
"""
return File(self._get("/projects/" + str(project_id) + "/files/" + str(file_id), params))
def get_file_versions(self, project_id, file_id, params=None):
"""
Get versions for file in project (does not include file given).
:param int project_id: The id of the project containing the file
:param int file_id: The id of the file
:param params:
:return: File versions
:rtype: File[]
:raises MCAPIError:
"""
return File.from_list(
self._get("/projects/" + str(project_id) + "/files/" + str(file_id) + "/versions", params))
def set_as_active_file(self, project_id, file_id):
"""
Set file as active version, changing current active file version to inactive.
:param int project_id: The id of the project containing the file
:param int file_id: The id of the file
:return: File
:rtype: File
:raises MCAPIError:
"""
return File(self._put("/projects/" + str(project_id) + "/files/" + str(file_id) + "/make_active", {}))
def get_file_by_path(self, project_id, file_path):
"""
Get file by path in project.
:param int project_id: The id of the project containing the file
:param file_path: The path to the file
:return: The file
:rtype: File
:raises MCAPIError:
"""
form = {"path": file_path.replace('\\', '/'), "project_id": project_id}
return File(self._post("/files/by_path", form))
def update_file(self, project_id, file_id, attrs):
"""
Update attributes of a file.
:param project_id:
:param file_id:
:param UpdateFileRequest attrs: Attributes to update
:return: The updated file
:rtype: File
:raises MCAPIError:
"""
form = _merge_dicts({"project_id", project_id}, attrs.to_dict())
return File(self._put("/files/" + str(file_id), form))
def delete_file(self, project_id, file_id, force=False):
"""
Delete a file in a project.
:param int project_id: The id of the project containing the file
:param int file_id: The id of the file to delete
:raises MCAPIError:
"""
params = None
if force:
params = {"force": True}
self._delete("/projects/" + str(project_id) + "/files/" + str(file_id), params=params)
def move_file(self, project_id, file_id, to_directory_id):
"""
Move file into a different directory.
:param int project_id: The project id of the file and the destination directory
:param int file_id: The id of the file to move
:param int to_directory_id: The id of the destination directory
:return: The moved file
:rtype: File
:raises MCAPIError:
"""
form = {"directory_id": to_directory_id, "project_id": project_id}
return File(self._post("/files/" + str(file_id) + "/move", form))
def rename_file(self, project_id, file_id, name):
"""
Rename a file.
:param int project_id: The project id of the file to rename
:param int file_id: The id of the file to rename
:param str name: The files new name
:return: The rename file
:rtype: File
:raises MCAPIError:
"""
form = {"name": name, "project_id": project_id}
return File(self._post("/files/" + str(file_id) + "/rename", form))
def download_file(self, project_id, file_id, to):
"""
Download a file.
:param int project_id: The project id containing the file to download
:param int file_id: The id of the file to download
:param str to: path including file name to download file to
:raises MCAPIError:
"""
self._download("/projects/" + str(project_id) + "/files/" + str(file_id) + "/download", to)
def download_file_by_path(self, project_id, path, to):
"""
Download a file by path.
:param int project_id: The project id containing the file to download
:param str path: The path in the project of the file
:param str to: path including file name to download file to
:raises MCAPIError:
"""
file = self.get_file_by_path(project_id, path.replace('\\', '/'))
self.download_file(project_id, file.id, to)
def upload_file(self, project_id, directory_id, file_path):
"""
Uploads a file to a project.
:param int project_id: The project to upload file to
:param int directory_id: The directory in the project to upload the file into
:param str file_path: path of file to upload
:return: The created file
:rtype: File
:raises MCAPIError:
"""
files = File.from_list(
self._upload("/projects/" + str(project_id) + "/files/" + str(directory_id) + "/upload", file_path))
return files[0]
def upload_bytes(self, project_id, directory_id, name, f):
files = File.from_list(
self._upload_raw("/projects/" + str(project_id) + "/files/" + str(directory_id) + "/upload/" + str(name),
f))
return files[0]
def list_files_changed_since(self, project_id, since, starting_page=None, page_size=None):
"""
Lists files changed (uploaded) in project since datetime in since
:param int project_id: The id of the project
:param str since: The datetime to get files changed since, form "YYYY-MM-DD HH:MM:SS"
:param int starting_page: The starting page to retrieve
:param int page_size: Number of entries per page
:return: The list of files changed
:rtype: Paged
:raises MCAPIError:
"""
params = {"since": since}
if starting_page is not None:
params["page[number]"] = starting_page
if page_size is not None:
params["page[size]"] = page_size
files = File.from_list(
self._get("/projects/" + str(project_id) + "/file-changes-since", params))
p = Paged(self.r.json(), files)
first_page = p.current_page
last_page = p.last_page
yield p
for page in range(first_page + 1, last_page + 1):
params["page[number]"] = page
files = File.from_list(self._get("/projects/" + str(project_id) + "/file-changes-since", params))
yield Paged(self.r.json(), files)
# Entities
def get_all_entities(self, project_id, params=None):
"""
Get all entities in a project.
:param int project_id: The id of the project
:param params:
:return: The list of entities
:rtype: Entity[]
:raises MCAPIError:
"""
return Entity.from_list(self._get("/projects/" + str(project_id) + "/entities", params))
def get_entity(self, project_id, entity_id, params=None):
"""
Get an entity.
:param int project_id: The id of the project containing the entity
:param int entity_id: The id of the entity
:param params:
:return: The entity
:rtype: Entity
:raises MCAPIError:
"""
return Entity(self._get("/projects/" + str(project_id) + "/entities/" + str(entity_id), params))
def create_entity(self, project_id, name, activity_id, request=None, attrs=None):
"""
Creates a new entity in the project.
:param project_id: The id of the project to create entity in
:param str name: The entity name
:param activity_id: The activity to associated the samples as initially coming from
:param CreateEntityRequest request: Attributes of the entity
:param attrs: Array of dicts of the form {"name": "name-of-attr", "unit": "optional-unit", "value": dict | bool | int | float | str}
:return: The created entity
:rtype: Entity
:raises MCAPIError:
"""
if not request:
request = CreateEntityRequest()
if not attrs:
attrs = []
form = _merge_dicts({
"name": name,
"project_id": project_id,
"attributes": attrs,
"activity_id": activity_id,
}, request.to_dict())
return Entity(self._post("/entities", form))
def delete_entity(self, project_id, entity_id):
"""
Delete an entity.
:param int project_id: The id of the project containing the entity
:param int entity_id: The entity id
:raises MCAPIError:
"""
self._delete("/projects/" + str(project_id) + "/entities/" + str(entity_id))
def create_entity_state(self, project_id, entity_id, activity_id, current=True, attrs=None):
"""
Adds a new state to an existing entity.
:param int project_id: The id of the project containing the entity
:param int entity_id: The id of the entity to associate the state with
:param in activity_id: The id of the activity that created the state
:param bool current: Whether to mark the state as the current state
:param attrs: Array of dicts of the form {"name": "name-of-attr", "unit": "optional-unit", "value": dict | bool | int | float | str}
:return: Entity
:raises MCAPIError:
"""
if not attrs:
attrs = []
form = {"current": current, "attributes": attrs}
return Entity(self._post("/projects/" + str(project_id) + "/entities/" + str(entity_id) + "/activities/" + str(
activity_id) + "/create-entity-state", form))
# Activities
def get_all_activities(self, project_id, params=None):
"""
Get all activities in a project.
:param int project_id: The id of the project
:param params:
:return: List of activities
:rtype: Activity[]
:raises MCAPIError:
"""
return Activity.from_list(self._get("/projects/" + str(project_id) + "/activities", params))
def get_activity(self, project_id, activity_id, params=None):
"""
Get an activity.
:param int project_id: The id of the project containing the activity
:param int activity_id: The id of the activity
:param params:
:return: The activity
:rtype: Activity
:raises MCAPIError:
"""
return Activity(self._get("/projects/" + str(project_id) + "/activities/" + str(activity_id), params))
def create_activity(self, project_id, name, request=None, attrs=None):
"""
Create a new activity in the project.
:param project_id: The project to create the activity int
:param str name: Name of activity
:param CreateActivityRequest request: Attributes on the activity
:param attrs: Array of dicts of the form {"name": "name-of-attr", "unit": "optional-unit", "value": dict | bool | int | float | str}
:return: The activity to create
:rtype: Activity
:raises MCAPIError:
"""
if not request:
request = CreateActivityRequest()
if not attrs:
attrs = []
form = _merge_dicts({"project_id": project_id, "name": name, "attributes": attrs}, request.to_dict())
return Activity(self._post("/activities", form))
def delete_activity(self, project_id, activity_id):
"""
Deletes an activity.
:param project_id: The id of the project containing the activity
:param activity_id: The id of the activity to delete
:raises MCAPIError:
"""
self._delete("/projects/" + str(project_id) + "/activities/" + str(activity_id))
# Datasets
def get_all_datasets(self, project_id, params=None):
"""
Get all datasets in a project.
:param int project_id: The project id
:param params:
:return: The list of datasets
:rtype: Dataset[]
:raises MCAPIError:
"""
return Dataset.from_list(self._get("/projects/" + str(project_id) + "/datasets", params))
def get_all_published_datasets(self, params=None):
"""
Get all published datasets.
:param params:
:return: The list of published datasets
:rtype: Dataset[]
:raises MCAPIError:
"""
return Dataset.from_list(self._get("/published/datasets", params))
def get_published_dataset(self, dataset_id, params=None):
"""
Get published dataset.
:param int dataset_id: The dataset id
:param params:
:return: The dataset
:rtype: Dataset
:raises MCAPIError:
"""
return Dataset(self._get("/published/datasets/" + str(dataset_id), params))
def get_published_dataset_files(self, dataset_id, params=None):
"""
Get files for a published dataset.
:param int dataset_id: The dataset id
:param params:
:rtype: File[]
:return: The files
:raises MCAPIError:
"""
return File.from_list(
self._get("/published/datasets/" + str(dataset_id) + "/files", params))
def get_published_dataset_directory(self, dataset_id, directory_id, params=None):
"""
Get a directory in a published dataset.
:param int dataset_id: The id of the published dataset the directory is in
:param int directory_id: The directory id
:param params:
:return: The directory
:rtype: File
:raises MCAPIError:
"""
return File(self._get("/published/datasets/" + str(dataset_id) + "/directories/" + str(directory_id), params))
def list_published_dataset_directory(self, dataset_id, directory_id, params=None):
"""
Return a list of all the files and directories in a given published dataset directory.
:param int dataset_id: The id of the dataset the directory is in
:param int directory_id: The directory id
:param params:
:return: A list of the files and directories in the given directory
:rtype: File[]
:raises MCAPIError:
"""
return File.from_list(
self._get("/published/datasets/" + str(dataset_id) + "/directories/" + str(directory_id) + "/list", params))
def list_published_dataset_directory_by_path(self, dataset_id, path, params=None):
"""
Return a list of all the files and directories at given path.
:param int dataset_id: The id of the dataset the path is in
:param str path:
:param params:
:return: A list of the files and directories in the given path
:rtype: File[]
:raises MCAPIError:
"""
path_param = {"path": path.replace('\\', '/')}
return File.from_list(
self._get("/published/datasets/" + str(dataset_id) + "/directories_by_path", params, path_param))
def get_published_dataset_entities(self, dataset_id, params=None):
"""
Get entities for a published dataset.
:param int dataset_id: The dataset id
:param params:
:rtype: Entity[]
:return: The entities
:raises MCAPIError:
"""
return Entity.from_list(
self._get("/published/datasets/" + str(dataset_id) + "/entities", params))
def get_published_dataset_activities(self, dataset_id, params=None):
"""
Get activities for a published dataset.
:param int dataset_id: The dataset id
:param params:
:rtype: Activity[]
:return: The activities
:raises MCAPIError:
"""
return Activity.from_list(
self._get("/published/datasets/" + str(dataset_id) + "/activities", params))
def search_published_data(self, search_str):
"""
Search published datasets for matching string.
:param str search_str: string to search on
:return: List of matches
:rtype: Searchable[]
:raises MCAPIError:
"""
form = {"search": search_str}
return Searchable.from_list(self._post("/published/data/search", form))
def get_all_published_dataset_files_matching(self, match, starting_page=None, page_size=None):
return self._get_files_matching("/published/datasets/files/matching", match, starting_page, page_size)
def get_published_dataset_files_matching(self, dataset_id, match, starting_page=None, page_size=None):
return self._get_files_matching(f"/published/datasets/{dataset_id}/files/matching", match, starting_page,
page_size)
def import_dataset(self, dataset_id, project_id, directory_name):
"""
Launches a job to import a dataset into a project. The import will complete at some.
point in the future. There isn't currently a way to query the import status.
:param int dataset_id: The dataset id to import
:param int project_id: A project id the user has access to
:param string directory_name: The top level directory to import the dataset into (will be created)
:raises MCAPIError:
"""
form = {"directory": directory_name}
self._post("/projects/" + str(project_id) + "/datasets/" + str(dataset_id) + "/import", form)
def get_dataset(self, project_id, dataset_id, params=None):
"""
Get dataset in a project.
:param int project_id: The project id containing the dataset
:param int dataset_id: The dataset id
:param params:
:return: The dataset
:rtype: Dataset
:raises MCAPIError:
"""
return Dataset(self._get("/projects/" + str(project_id) + "/datasets/" + str(dataset_id), params))
def get_dataset_files(self, project_id, dataset_id, params=None):
"""
Get files for a dataset.
:param int project_id: The project id containing the dataset
:param int dataset_id: The dataset id
:param params:
:rtype: File[]
:return: The files
:raises MCAPIError:
"""
return File.from_list(
self._get("/projects/" + str(project_id) + "/datasets/" + str(dataset_id) + "/files", params))
def get_dataset_entities(self, project_id, dataset_id, params=None):
"""
Get entities for a dataset.
:param int project_id: The project id containing the dataset
:param int dataset_id: The dataset id
:param params:
:rtype: Entity[]
:return: The entities
:raises MCAPIError:
"""
return Entity.from_list(
self._get("/projects/" + str(project_id) + "/datasets/" + str(dataset_id) + "/entities", params))
def get_dataset_activities(self, project_id, dataset_id, params=None):
"""
Get activities for a dataset.
:param int project_id: The project id containing the dataset
:param int dataset_id: The dataset id
:param params:
:rtype: Activity[]
:return: The activities
:raises MCAPIError:
"""
return Activity.from_list(
self._get("/projects/" + str(project_id) + "/datasets/" + str(dataset_id) + "/activities", params))
def delete_dataset(self, project_id, dataset_id):
"""
Delete an unpublished dataset.
:param int project_id: The project id containing the dataset
:param int dataset_id: The id of the dataset
:raises MCAPIError:
"""
self._delete("/projects/" + str(project_id) + "/datasets/" + str(dataset_id))
def update_dataset_file_selection(self, project_id, dataset_id, file_selection):
"""
Update the file selection for a dataset.
:param int project_id: Project id containing dataset
:param int dataset_id: Id of dataset
:param file_selection: {
"include_file": str,
"remove_include_file": str,
"exclude_file": str,
"remove_exclude_file": str,
"include_dir": str,
"remove_include_dir": str,
"exclude_dir": str,
"remove_exclude_dir": str}
:return: The updated dataset
:rtype: Dataset
:raises MCAPIError:
"""
form = {"project_id": project_id}
form = _merge_dicts(form, file_selection)
return Dataset(self._put("/datasets/" + str(dataset_id) + "/selection", form))
def change_dataset_file_selection(self, project_id, dataset_id, file_selection):
"""
Change the file selection for a dataset to match the passed in dataset.
:param int project_id: Project id containing dataset
:param int dataset_id: Id of dataset
:param file_selection: {
"include_files": array,
"exclude_files": array,
"include_dirs": array,
"exclude_dirs": array}
:return: The updated dataset
:rtype: Dataset
:raises MCAPIError:
:return: The updated Dataset
"""
return Dataset(
self._put("/projects/" + str(project_id) + "/datasets/" + str(dataset_id) + "/change_file_selection",
file_selection))
def update_dataset_activities(self, project_id, dataset_id, activity_id):
"""
Toggle whether an activity is in a dataset.
:param int project_id: Project id containing dataset and activity
:param int dataset_id: Id of dataset
:param int activity_id: Id of activity
:return: The updated dataset
:rtype: Dataset
:raises MCAPIError:
"""
form = {"project_id": project_id, "activity_id": activity_id}
return Dataset(self._put("/datasets/" + str(dataset_id) + "/activities/selection", form))
def update_dataset_entities(self, project_id, dataset_id, entity_id):
"""
Toggle whether an entity is in a dataset.
:param int project_id: Project id containing dataset and entity
:param int dataset_id: Id of dataset
:param int entity_id: Id of entity
:return: The updated dataset
:rtype: Dataset
:raises MCAPIError:
"""
form = {"project_id": project_id, "entity_id": entity_id}
return Dataset(self._put("/datasets/" + str(dataset_id) + "/entities", form))
def update_dataset_workflows(self, project_id, dataset_id, workflow_id):
"""
Toggle whether an workflow is in a dataset.
:param int project_id: Project id containing dataset and workflow
:param int dataset_id: Id of dataset
:param int workflow_id: Id of workflow
:return: The updated dataset
:rtype: Dataset
:raises MCAPIError:
"""
form = {"project_id": project_id, "workflow_id": workflow_id}
return Dataset(self._put("/datasets/" + str(dataset_id) + "/workflows", form))
def publish_dataset(self, project_id, dataset_id):
"""
Publish a dataset.
:param int project_id: The id of the project containing the dataset
:param int dataset_id: The dataset id
:return: The dataset
:rtype: Dataset
:raises MCAPIError:
"""
form = {"project_id": project_id}
return Dataset(self._put("/datasets/" + str(dataset_id) + "/publish", form))
def unpublish_dataset(self, project_id, dataset_id):
"""
Unpublish an published dataset.
:param int project_id: The id of the project containing the dataset
:param int dataset_id: The dataset id
:return: The dataset
:rtype: Dataset
:raises MCAPIError:
"""
form = {"project_id": project_id}
return Dataset(self._put("/datasets/" + str(dataset_id) + "/unpublish", form))
def create_dataset(self, project_id, name, attrs=None):
"""
Create a new dataset in a project.
:param int project_id: The project to create the dataset in
:param string name: The name of the dataset
:param CreateDatasetRequest attrs: Attributes of the dataset
:return: The created dataset
:rtype: Dataset
:raises MCAPIError:
"""
if not attrs:
attrs = CreateDatasetRequest()
form = _merge_dicts({"name": name}, attrs.to_dict())
return Dataset(self._post("/projects/" + str(project_id) + "/datasets", form))
def update_dataset(self, project_id, dataset_id, name, attrs=None):
"""
Update an existing dataset.
:param int project_id: The project to create the dataset in
:param int dataset_id: The id of the dataset
:param str name: The name of the dataset (doesn't need to be different)
:param UpdateDatasetRequest attrs: The attributes to update
:return: The updated dataset
:rtype: Dataset
:raises MCAPIError:
"""
if not attrs:
attrs = UpdateDatasetRequest()
form = _merge_dicts({"name": name}, attrs.to_dict())
return Dataset(self._put("/projects/" + str(project_id) + "/datasets/" + str(dataset_id), form))
def assign_doi_to_dataset(self, project_id, dataset_id):
"""
Assign DOI to existing dataset.
:param int project_id: The project to create the dataset in
:param int dataset_id: The id of the dataset
:return: The updated dataset with DOI
:rtype: Dataset
:raises MCAPIError:
"""
return Dataset(self._put("/projects/" + str(project_id) + "/datasets/" + str(dataset_id) + "/assign_doi", {}))
def download_published_dataset_zipfile(self, dataset_id, to):
"""
Download the zipfile for a published dataset.
:param int dataset_id: The id of the published dataset
:param str to: The path including the file name to write the download to
:raises MCAPIError:
"""
self._download("/published/datasets/" + str(dataset_id) + "/download_zipfile", to)
def download_published_dataset_file(self, dataset_id, file_id, to):
"""
Download file from a published dataset.
:param int dataset_id: The id of the published dataset
:param int file_id: The id of the file in the dataset
:param str to: The path including the file name to write the download to
:raises MCAPIError:
"""
self._download("/published/datasets/" + str(dataset_id) + "/files/" + str(file_id) + "/download", to)
def check_file_in_dataset(self, project_id, dataset_id, file_id):
"""
Check if file is in the dataset selection.
:param int project_id: project dataset and file are in
:param int dataset_id: dataset to check file_selection against
:param int file_id: file to check
:return: {'in_dataset': True} or {'in_dataset': False}
:raises MCAPIError:
"""
return self._get("/projects/" + str(project_id) + "/datasets/" + str(dataset_id) + "/files/" + str(
file_id) + "/check_selection")
def check_file_by_path_in_dataset(self, project_id, dataset_id, file_path):
"""
Check if file path is in the dataset selection. Throws an error if the file_path isn't in the project.
:param int project_id: project dataset and file_path are in
:param int dataset_id: data to check file_selection against
:param str file_path: file_path to check against dataset file_selection
:return: {'in_dataset': True} or {'in_dataset': False}
:raises MCAPIError:
"""
form = {"file_path": file_path.replace('\\', '/')}
return self._post("/projects/" + str(project_id) + "/datasets/" + str(dataset_id) + "/check_select_by_path",
form)
# Globus
def create_globus_upload_request(self, project_id, name):
"""
Create a new globus request in the given project.
:param int project_id: The project id for the upload
:param name: The name of the request
:return: The globus request
:rtype: GlobusUpload
:raises MCAPIError:
"""
form = {"project_id": project_id, "name": name}
return GlobusUpload(self._post("/globus/uploads", form))
def delete_globus_upload_request(self, project_id, globus_upload_id):
"""
Delete an existing globus upload request.
:param int project_id:
:param int globus_upload_id:
:raises MCAPIError:
"""
self._delete("/projects/" + str(project_id) + "/globus/" + str(globus_upload_id) + "/uploads")
def finish_globus_upload_request(self, project_id, globus_upload_id):
"""
Mark a globus upload request as finished.
:param int project_id: The project id for the upload
:param int globus_upload_id: The id of the globus upload
:return: The globus upload
:rtype: GlobusUpload
:raises MCAPIError:
"""
form = {"project_id": project_id}
return GlobusUpload(self._put("/globus/" + str(globus_upload_id) + "/uploads/complete", form))
def get_all_globus_upload_requests(self, project_id, params=None):
"""
Get all globus uploads in a project.
:param int project_id: The project id
:return: List of globus uploads
:rtype: GlobusUpload[]
:raises MCAPIError:
"""
return GlobusUpload.from_list(self._get("/projects/" + str(project_id) + "/globus/uploads", params))
def create_globus_download_request(self, project_id, name):
"""
Create a globus download request for a project.
:param int project_id:
:param str name: The name of the download request
:return: The globus download
:rtype: GlobusDownload
:raises MCAPIError:
"""
form = {"project_id": project_id, "name": name}
return GlobusDownload(self._post("/globus/downloads", form))
def delete_globus_download_request(self, project_id, globus_download_id):
"""
Delete an existing globus download request.
:param int project_id: The id of the project containing the download request
:param int globus_download_id: The id of the globus download to delete
:raises MCAPIError:
"""
self._delete("/projects/" + str(project_id) + "/globus/" + str(globus_download_id) + "/downloads")
def get_all_globus_download_requests(self, project_id, params=None):
"""
Get all globus download requests for a project.
:param int project_id: The project
:return: List of all globus downloads
:rtype: GlobusDownload[]
:raises MCAPIError:
"""
return GlobusDownload.from_list(self._get("/projects/" + str(project_id) + "/globus/downloads", params))
def get_globus_download_request(self, project_id, globus_download_id, params=None):
"""
Get a globus download.
:param int project_id: The id of the project containing the globus download
:param int globus_download_id: The globus download id
:return: The globus download
:rtype: GlobusDownload
:raises MCAPIError:
"""
return GlobusDownload(
self._get("/projects/" + str(project_id) + "/globus/downloads/" + str(globus_download_id), params))
def open_globus_transfer(self, project_id, params=None):
"""
Open a globus transfer request for current user in project. If one is already
active then it returns the already active request.
:param int project_id: The id of the project associated with this globus transfer
:return: The globus transfer
:rtype: GlobusTransfer
:raises MCAPIError:
"""
return GlobusTransfer(self._get("/projects/" + str(project_id) + "/globus/open", params))
def close_globus_transfer(self, project_id):
"""
Closes an existing globus transfer. If there isn't an open transfer for the user in project then
does nothing and returns success.
:param int project_id: The id of the project to close globus transfer for the current user
:return: None
:raises MCAPIError:
"""
self._get_no_value("/projects/" + str(project_id) + "/globus/close")
# Users
def get_user_by_email(self, email, params=None):
"""
Get a user by their email.
:param string email: email address of user to lookup
:return: The user
:rtype: User
:raises MCAPIError:
"""
return User(self._get("/users/by-email/" + email, params))
def list_users(self, params=None):
"""
List users of Materials Commons.
:return: List of users
:rtype: User[]
:raises MCAPIError:
"""
return User.from_list(self._get("/users", params))
# Communities
def create_community(self, name, attrs={}):
"""
Creates a new community owned by the user.
:param str name: Name of community
:param CreateCommunityRequest attrs: (optional) Additional attributes for the create request
:return: The created community
:rtype: Community
:raises MCAPIError:
"""
if not attrs:
attrs = CreateCommunityRequest()
form = _merge_dicts({"name": name}, attrs.to_dict())
return Community(self._post("/communities", form))
def get_all_public_communities(self, params=None):
"""
Get all public communities.
:rtype: Community[]
:return: List of public communities
:raises MCAPIError:
"""
return Community.from_list(self._get('/communities/public', params))
def get_all_my_communities(self, params=None):
"""
Get all communities owned by user.
:rtype: Community[]
:return: List of communities
:raises MCAPIError:
"""
return Community.from_list(self._get('/communities', params))
def get_community(self, community_id, params=None):
"""
Get a commmunity.
:param int community_id: The id of the community to get
:param params: Query specific parameters
:rtype: Community
:return: The Community
:raises MCAPIError:
"""
return Community(self._get("/communities/" + str(community_id), params))
def add_dataset_to_community(self, dataset_id, community_id):
"""
Add a dataset to a community. The dataset must have been published.
:param int dataset_id:
:param int community_id:
:rtype: Community
:return: The community with the dataset
:raises MCAPIError:
"""
return Community(self._post("/communities/" + str(community_id) + "/datasets/" + str(dataset_id) + "/add"))
def remove_dataset_from_community(self, dataset_id, community_id):
"""
Remove a dataset from a community.
:param int dataset_id:
:param int community_id:
:raises MCAPIError:
"""
self._delete("/communities/" + str(community_id) + "/datasets/" + str(dataset_id))
def upload_file_to_community(self, file_path, community_id):
"""
TODO: A file has other attributes such as description and summary
Uploads a file to a community.
:param str file_path: path of file to upload
:param int community_id: The community to upload the file to
:return: The community
:rtype: Community
:raises MCAPIError:
"""
return Community(self._upload("/communities/" + str(community_id) + "/upload", file_path))
def delete_file_from_community(self, file_id, community_id):
"""
Deletes file from the community and deletes the file on the system.
:param int file_id: The file to delete
:param int community_id: The community to delete it from
:raises MCAPIError:
"""
self._delete("/communities/" + str(community_id) + "/files/" + str(file_id))
def create_link_in_community(self, community_id, name, url, attrs=None):
"""
Adds a link to a community.
:param int community_id: The community to add the link to
:param str name: name to show for url
:param str url: url to add
:param CreateLinkRequest attrs: additional attrs
:return: The community
:rtype: Community
:raises MCAPIError:
"""
if not attrs:
attrs = CreateLinkRequest()
form = _merge_dicts({"url": url, "name": name}, attrs.to_dict())
return Community(self._post("/communities/" + str(community_id) + "/links", form))
def delete_link_from_community(self, link_id, community_id):
"""
Delete a link from a community and remove it from the system.
:param int link_id: The link to remove
:param int community_id: The community to delete the link from
:raises MCAPIError:
"""
self._delete("/communities/" + str(community_id) + "/links/" + str(link_id))
def list_tags_in_community(self, community_id):
"""
List all the unique tags across all the published datasets in a community.
:param int community_id: The community to list the tags for
:return: The list of tags
:rtype: Tag[]
:raises MCAPIError:
"""
return self._get("/communities/" + str(community_id) + "/tags")
def get_published_datasets_for_author(self, author):
"""
Get all published datasets for an author.
:param str author: Author name string
:return: List of datasets author is on
:rtype: Dataset[]
:raises MCAPIError:
"""
form = {"author": author}
return Dataset.from_list(self._post("/published/authors/search", form))
def get_published_datasets_for_tag(self, tag):
"""
Get all published datasets tagged with tag.
:param str tag: tag to use
:return: List of datasets tagged with tag
:rtype: Dataset[]
:raises MCAPIError:
"""
form = {"tag": tag}
return Dataset.from_list(self._post("/published/tags/search", form))
def list_authors_in_community(self, community_id):
"""
List all unique authors across all the published datasets in a community.
:param int community_id: The community to list the authors for
:return: The list of authors
:rtype: string[]
:raises MCAPIError:
"""
return self._get("/communities/" + str(community_id) + "/authors")
# Tags
def list_tags_for_published_datasets(self):
"""
List all tags used in published datasets.
:return: List of tags
:rtype: Tag[]
:raises MCAPIError:
"""
return Tag.from_list(self._get("/published/tags"))
# Authors
def list_published_authors(self):
"""
List all published authors.
:return: List of authors
:rtype: User[]
:raises MCAPIError:
"""
return self._get("/published/authors")
# MQL
def mql_load_project(self, project_id):
self._post("/queries/" + str(project_id) + "/load-project", {})
def mql_reload_project(self, project_id):
self._post("/queries/" + str(project_id) + "/load-project", {})
def mql_execute_query(self, project_id, statement, select_processes=True, select_samples=True):
self.mql_load_project(project_id)
form = {
"statement": statement,
"select_processes": select_processes,
"select_samples": select_samples
}
return self._post("/queries/" + str(project_id) + "/execute-query", form)
# Internal
def _get_files_matching(self, url, match, starting_page, page_size):
params = _set_paging_params({}, starting_page, page_size)
form = {}
# API user can either send us a single string match, or an array of matches
# The api takes a list, so we need to convert a single item to an array.
if isinstance(match, list):
form["match"] = match
else:
form["match"] = [match]
files = File.from_list(self._post(url, form, params=params))
p = Paged(self.r.json(), files)
first_page = p.current_page
last_page = p.last_page
yield p
for page in range(first_page + 1, last_page + 1):
params["page[number]"] = page
files = File.from_list(self._post(url, form, params=params))
yield Paged(self.r.json(), files)
def _throttle(self):
if self._throttle_s < 0:
self._throttle_s = 0.0
if self._throttle_s:
time.sleep(self._throttle_s)
# request calls
def _download(self, urlpart, to):
self._throttle()
url = self.base_url + urlpart
with requests.get(url, stream=True, verify=False, headers=self.headers) as r:
self._handle(r)
with open(to, 'wb') as f:
for chunk in r.iter_content(chunk_size=8192):
if chunk:
f.write(chunk)
def _upload(self, urlpart, file_path):
self._throttle()
url = self.base_url + urlpart
with open(file_path, 'rb') as f:
files = [('files[]', f)]
r = requests.post(url, verify=False, headers=self.headers, files=files)
return self._handle_with_json(r)
def _upload_raw(self, urlpart, f):
self._throttle()
url = self.base_url + urlpart
files = [('files[]', f)]
r = requests.post(url, verify=False, headers=self.headers, files=files)
return self._handle_with_json(r)
def _get(self, urlpart, params={}, other_params={}):
self._throttle()
url = self.base_url + urlpart
if self.log:
print("GET:", url)
params_to_use = _merge_dicts(QueryParams.to_query_args(params), other_params)
r = requests.get(url, params=params_to_use, verify=False, headers=self.headers)
return self._handle_with_json(r)
def _get_no_value(self, urlpart):
self._throttle()
url = self.base_url + urlpart
if self.log:
print("GET:", url)
r = requests.get(url, verify=False, headers=self.headers)
return self._handle(r)
def _post(self, urlpart, data, params=None):
self._throttle()
url = self.base_url + urlpart
if self.log:
print("POST:", url)
data = OrderedDict(data)
r = requests.post(url, json=data, verify=False, headers=self.headers, params=params)
return self._handle_with_json(r)
def _put(self, urlpart, data):
self._throttle()
url = self.base_url + urlpart
if self.log:
print("PUT:", url)
data = OrderedDict(data)
r = requests.put(url, json=data, verify=False, headers=self.headers)
return self._handle_with_json(r)
def _delete(self, urlpart, params=None):
self._throttle()
url = self.base_url + urlpart
if self.log:
print("DELETE:", url)
r = requests.delete(url, verify=False, params=params, headers=self.headers)
self._handle(r)
def _delete_with_value(self, urlpart):
self._throttle()
url = self.base_url + urlpart
if self.log:
print("DELETE:", url)
r = requests.delete(url, verify=False, headers=self.headers)
return self._handle_with_json(r)
def _handle(self, r):
# try:
# import json
# print("-----------------------------")
# print(json.dumps(r.json(), indent=2))
# print("-----------------------------")
# except:
# print("no json")
self.r = r
self._update_rate_limits_from_request(r)
try:
r.raise_for_status()
return True
except requests.HTTPError as e:
if not self.raise_exception:
return False
raise MCAPIError(str(e), e.response)
def _handle_with_json(self, r):
if not self._handle(r):
return None
if r.headers.get('content-type') == 'application/json':
result = r.json()
if "data" in result:
return result["data"]
else:
return result
return None
def _update_rate_limits_from_request(self, r):
self.rate_limit = int(r.headers.get('x-ratelimit-limit', self.rate_limit))
self.rate_limit_remaining = int(r.headers.get('x-ratelimit-remaining', self.rate_limit_remaining))
self.rate_limit_reset = r.headers.get('x-ratelimit-reset', None)
self.retry_after = r.headers.get('retry-after', None)
if self.rate_limit_remaining < 10:
self._throttle_s = 60. / (self.rate_limit_remaining - 1.)
else:
self._throttle_s = 0.0
<file_sep>#!/usr/bin/env python3
import os
import sys
# import requests
# from xml.etree import ElementTree
import materials_commons.api as mcapi
import yaml
from urllib.parse import urlparse
import posixpath
import OpenVisus as ov
from matplotlib import pyplot as plt
from slugify import slugify
def create_ds_name_from_url(url):
# Take off filename
p = posixpath.dirname(url.path)
# Now iterate over path peeling off each part of path
# to create the dataset name. End when the basename
# is equal to 1mb
ds_name = ""
while True:
name = posixpath.basename(p)
if name == "1mb":
break
if ds_name == "":
ds_name = name
else:
ds_name += f"-{name}"
p = posixpath.dirname(p)
return slugify(ds_name)
if __name__ == "__main__":
c = mcapi.Client(os.getenv("MCAPI_KEY"), base_url="http://localhost:8000/api")
proj = c.get_project(77)
c.set_debug_on()
with open('/home/gtarcea/Dropbox/transfers/datasets.yaml') as f:
try:
ds = yaml.safe_load(f)
i = 0
for ds_entry in ds:
if i == 1:
break
remote = ds_entry["remote"]
if remote is None:
continue
with open("ov-template.ipynb", "r") as t:
data = t.read()
data = data.replace("{remote-here}", remote)
with open("dataset.ipynb", "w") as out:
out.write(data)
url = urlparse(remote)
key = remote[len("s3://"):]
profile = "sealstorage"
s3_url = f"https://maritime.sealstorage.io/api/v0/s3/{key}?profile={profile}"
print(f"s3_url = {s3_url}")
db = ov.LoadDataset(s3_url)
data = db.read()
# Remove idx file
ds_name = create_ds_name_from_url(url)
plt.imsave(f"{ds_name}.png", data)
ds_dir = c.create_directory(77, ds_name, proj.root_dir.id)
c.upload_file(77, ds_dir.id, f"./{ds_name}.png")
c.upload_file(77, ds_dir.id, "./dataset.ipynb")
description = f"OpenVisus Dataset\n"
for key, value in ds_entry.items():
if key != "source" and key != "remote":
if value is not dict:
description += f"{key}: {value}\n"
else:
description += "{key}:\n"
for k, v in value.items():
description += f" {k}: {v}\n"
print(f"Creating dataset {ds_name}")
ds_request = mcapi.CreateDatasetRequest(description=description,
license="Open Database License (ODC-ODbL)")
# tags=[{"value": "OpenVisus"}])
created_ds = c.create_dataset(77, ds_name, ds_request)
file_selection = {
"include_files": [f"/{ds_name}/{ds_name}.png", f"/{ds_name}/dataset.ipynb"],
"exclude_files": [],
"include_dirs": [],
"exclude_dirs": []
}
c.change_dataset_file_selection(77, created_ds.id, file_selection)
os.remove(f"{ds_name}.png")
i = 1
except yaml.YAMLError as e:
print(e)
i = 1
# c.set_debug_on()
# r = requests.get("http://atlantis.sci.utah.edu/mod_visus?action=list")
# tree = ElementTree.fromstring(r.content)
# group = ""
# for elem in tree.iter():
# if elem.tag == "group":
# group = elem.attrib["name"]
# elif elem.tag == "dataset":
# ds = elem.attrib["name"]
# print(f"Dataset {ds} in group {group}")
# mod_visus = requests.get("https://atlantis.sci.utah.edu/mod_visus?action=readdataset&dataset=" + ds)
# data = mod_visus.text.split('\n')[5]
# ds_request = mcapi.CreateDatasetRequest(description="OpenVisus Dataset\n" + "Group: " + group + "\n" + data,
# license="Open Database License (ODC-ODbL)")
# # tags=[{"value": "OpenVisus"}])
# created_ds = c.create_dataset(77, ds, ds_request)
# group = child.attrib["name"]
# for ds in child:
# dsname = child.attrib["name"]
# print("Dataset " + dsname + " in group " + group)
<file_sep>.. manual/server_info.rst
Server
======
The API supports querying about the server itself. ::
server_info = c.get_server_info()
The API lets you the current server version, last date it was updated, the globus endpoint id so you can use globus
for file uploads and downloads, and other meta data information. For more see `Server` class.<file_sep>.. manual/file_upload_download.rst
File Upload and Download
========================
The Materials Commons API supports uploading files. If you have a large number of files, or individual files that are
bigger than 250MB it is recommended that you use Globus to perform your uploads and downloads. Showing how to use the
Globus API is outside the scope of this documentation. ::
# Create directory off of project root directory
dir = c.create_directory(project.id, "d1", project.root_dir.id)
# Upload file in /tmp to newly created directory
file = c.upload_file(project.id, dir.id, "/tmp/file-to-upload.txt")
# Download newly uploaded file and write it to a different name in /tmp
c.download_file(project.id, file.id, "/tmp/newly-downloaded-file.txt")
# Download file by path on server. Project file paths start with / as their root, so
# to download the file we uploaded into d1 named file-to-upload.txt it will be located
# on the server at /d1/file-to-upload.txt.
c.download_file_by_path(project.id, "/d1/file-to-upload.txt", "/tmp/download-again.txt")
# Rename the file we previously uploaded from file-to-upload.txt to file.txt
file = c.rename_file(project.id, file.id, "file.txt")
# Move the file from the d1 directory to the root directory
file = c.move_file(project.id, file.id, project.root_dir.id)
# Delete the uploaded file
c.delete_file(project.id, file.id)
<file_sep>.. materials_commons.api index
The Materials Commons API
=========================
`Materials Commons <https://materialscommons.org>`_ is a site for the materials community to store, share, and publish data. This package, ``materials_commons.api``, provides a Python API for use with Materials Commons.
.. toctree::
:maxdepth: 2
overview
install
manual/index
``materials_commons.api`` Reference <reference/materials_commons/modules>
help
license
``mcapi`` is available on GitHub_.
.. _GitHub: https://github.com/materials-commons/mcapi
<file_sep># build with: python setup.py install --user
from setuptools import setup, find_namespace_packages
from materials_commons.api import __version__
setup(
name='materials_commons-api',
version=__version__,
description='API interface to Materials Commons',
long_description="""This package contains the materials_commons.api module. This module is an interface
to the Materials Commons project. We assume you have used (or are otherwise familiar with) the Materials
Commons web site, https://materialscommons.org/, or a similar site based on the
Materials Commons code (https://github.com/materials-commons/materialscommons), and intend to use these
tools in that context.""",
url='https://materials-commons.github.io/materials-commons-api/html/index.html',
author='Materials Commons development team',
author_email='<EMAIL>',
license='MIT',
package_data={
# If any package contains *.txt files, include them:
"": ["*.txt"]
},
include_package_data=True,
packages=['materials_commons.api'],
zip_safe=False,
classifiers=[
# How mature is this project? Common values are
# 3 - Alpha
# 4 - Beta
# 5 - Production/Stable
'Development Status :: 4 - Beta',
# Indicate who your project is intended for
'Intended Audience :: Developers',
'Intended Audience :: Science/Research',
'Topic :: Scientific/Engineering :: Information Analysis',
# Pick your license as you wish (should match "license" above)
'License :: OSI Approved :: MIT License',
# Specify the Python versions you support here. In particular, ensure
# that you indicate whether you support Python 2, Python 3 or both.
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.8'
],
keywords='materials science mc materials-commons prisms',
install_requires=[
"requests",
"urllib3",
]
)
<file_sep>#!/usr/bin/env python3
import sys
import time
import logging
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
class MyLoggingEventHandler(FileSystemEventHandler):
"""Logs all the events captured."""
def __init__(self, logger=None):
super().__init__()
self.events = {}
self.logger = logger or logging.root
def on_moved(self, event):
super().on_moved(event)
what = 'directory' if event.is_directory else 'file'
self.logger.info("Moved %s: from %s to %s", what, event.src_path,
event.dest_path)
def on_created(self, event):
super().on_created(event)
what = 'directory' if event.is_directory else 'file'
self.events[event.src_path] = "created"
self.logger.info("Created %s: %s", what, event.src_path)
def on_deleted(self, event):
super().on_deleted(event)
what = 'directory' if event.is_directory else 'file'
self.events[event.src_path] = "deleted"
self.logger.info("Deleted %s: %s", what, event.src_path)
def on_modified(self, event):
super().on_modified(event)
what = 'directory' if event.is_directory else 'file'
self.events[event.src_path] = "modified"
self.logger.info("Modified %s: %s", what, event.src_path)
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
path = sys.argv[1] if len(sys.argv) > 1 else '.'
event_handler = MyLoggingEventHandler()
observer = Observer()
observer.schedule(event_handler, path, recursive=True)
observer.start()
try:
while True:
time.sleep(1)
finally:
observer.stop()
observer.join()
print(event_handler.events)
<file_sep>import datetime
import os
def to_datetime(dt_str):
return datetime.datetime.strptime(dt_str, "%Y-%m-%dT%H:%M:%S.%fZ")
def get_date(attr_name, data):
date = data.get(attr_name, None)
if date is None:
return date
return to_datetime(date)
def get_file_path(path, project_id=None, c=None):
"""
Gets the path for a file. If project_id, c, and the environment
variable MCFS_DIR are all set, then get_file_path() assumes it
is running on the Materials Commons server and returns the path
to the file stored in Materials Commons storage. Otherwise it
assumes it is running in a local environment and just returns
the path sent in.
This function allows developers to create tools that will run
on the Materials Commons server, but test them locally. It is
recommended that all paths be relative paths with the
assumption that the tool is running in the project root.
:param str path: Path for file to look up
:param int|None project_id: If set the project_id the file is in
:param Client|None: The materials_commons.api.Client client
:return: The file path
:rtype: str
:raises MCAPIError:
"""
if c is None:
return path
if project_id is None:
return path
mcfs_dir = os.getenv("MCFS_DIR")
if mcfs_dir is None:
return path
p = os.path.normpath(os.path.join("/", path))
f = c.get_file_by_path(project_id, p)
uuid_parts = f.uuid.split("-")
return os.path.join(mcfs_dir, uuid_parts[1][0:2], uuid_parts[1][2:4], f.uuid)
<file_sep># Generating the documentation
Install documentation dependencies. From repository root:
pip install -r doc_requirements.txt
From repository root run:
sphinx-apidoc --separate --implicit-namespaces -f -o doc/source/reference/materials_commons materials_commons
python setup.py build_sphinx
<file_sep>__version__ = '2.0b5'
from .client import Client, MCAPIError
from .models import Project, Activity, Dataset, Entity, Experiment, File, User, Workflow, GlobusTransfer, GlobusUpload, \
GlobusDownload, Paged
from .query_params import QueryParams, QueryField
from .requests import *
from .query import *
from .util import get_file_path
from .mc_project import mc_project
from .config import *
|
1fba3556be16c4e10d9226be543ba2d262433c4d
|
[
"reStructuredText",
"Markdown",
"Python",
"Text",
"Shell"
] | 31
|
reStructuredText
|
materials-commons/mcapi
|
d52c7ab398829483cff82a5ec8bf024386e559be
|
09b86a5acc1c4befcd3b75643abf65e350b50d1e
|
refs/heads/master
|
<repo_name>KMS-training-2018-test/test<file_sep>/src/test/BranchTest.java
package test;
public class BranchTest {
public static void main(String args[]){
System.out.println("児島だよ!!!");
}
}
|
a1969faab3d5df4772d0f0d0e3a32bd9045f9b97
|
[
"Java"
] | 1
|
Java
|
KMS-training-2018-test/test
|
79e09318d2aa0d7d33e2cee5f22fcae8e541f7d0
|
9be5a7e16de7f8b223c4d770e16102d703af1d4c
|
refs/heads/master
|
<repo_name>caibaozi/axf<file_sep>/App/views.py
from django.shortcuts import render
# Create your views here.
from App.models import Nav, Mustbuy, Wheel
def home(request):
navs = Nav.objects.all()
mustbuys = Mustbuy.objects.all()
wheels = Wheel.objects.all()
data = {
'wheels':wheels,
'navs':navs,
'mustbuys':mustbuys,
}
return render(request,'home/home.html',context= data)
def market(request):
return render(request,'market/market.html')
def mine(request):
return render(request,'mine/mine.html')
def cart(request):
return render(request,'cart/cart.html')
|
3ce6176f956646b68d372ed1a0ee0847e77e2771
|
[
"Python"
] | 1
|
Python
|
caibaozi/axf
|
4458600be78583e3338524159827ef1650d4b011
|
66c0146a4afad7658506d8ba3e793530a3cf5954
|
refs/heads/main
|
<repo_name>Aura-Buddy/Shell<file_sep>/practicingUserInput.sh
echo "Please enter your name"
read name
read Greeting
echo "It is nice to meeet you $name $Greeting"
<file_sep>/commandExecution.sh
#! /bin/bash
./commandLineArguments.sh Ethan Stop
<file_sep>/checkingStrings.sh
echo > outputFile.txt
IFS=''
i="hi"
j=0
input="check.txt"
while read data; do
echo "1 $data"
done < $input
echo done
<file_sep>/readingConfigtx.sh
echo > outputFile.txt
IFS=''
j=2
k=2
flag=0
function removeFile {
rm outputFile.txt
}
function startNetwork {
cp outputFile.txt /Users/aurachristinateasley/fresh-fabric/fabric-samples/test-network/configtx/configtx.yaml
pushd /Users/aurachristinateasley/fresh-fabric/fabric-samples/fabcar
./startFabric.sh
pushd /Users/aurachristinateasley/fresh-fabric/fabric-samples/fabcar/go
(time go run attemptingConcurrency.go) &>CPUandTime"$j""$k".txt
go run queryAllHighThroughput.go &>ledger"$j""$k".txt
docker logs -t peer0.org1.example.com &>peerLog"$j""$k".txt
cp ledger"$j""$k".txt /Users/aurachristinateasley/Desktop/"Lab Meetings"/"Weekly Pursuits 4.12 - 4.19"/MontyCarloResults/Ledger
cp CPUandTime"$j""$k".txt /Users/aurachristinateasley/Desktop/"Lab Meetings"/"Weekly Pursuits 4.12 - 4.19"/MontyCarloResults/CPUandTime
cp peerLog"$j""$k".txt /Users/aurachristinateasley/Desktop/"Lab Meetings"/"Weekly Pursuits 4.12 - 4.19"/MontyCarloResults/PeerLog
rm CPUandTime"$j""$k" ledger"$j""$k" peerLog"$j""$k"
popd
popd
}
function decrementK () {
k=2
}
function incrementK () {
k=$(($k+2))
}
function incrementJ () {
j=$(($j+2))
}
function readFile () {
removeFile
input="/Users/aurachristinateasley/Desktop/configtx.yaml"
while read data; do
if [ "$data" == " BatchTimeout: 0s" ]; then
echo " BatchTimeout: "$j"s" >> outputFile.txt
elif [ "$data" == " MaxMessageCount: 0" ]; then
echo " MaxMessageCount: "$k"" >> outputFile.txt
else
echo $data >> outputFile.txt
fi
done < $input
if [ $k -ge 50 ]; then
incrementJ
decrementK
fi
incrementK
startNetwork
echo "Done: j is now $j, k is now $k"
}
while [ $j -le 50 ]; do
readFile $j $k
done
<file_sep>/dataStorage.sh
#!/bin/sh
a=0
while [ $a -lt $1 ]
do
# Print the values
echo $a
# increment the value
a=`expr $a + 1`
echo $(date) >> data.txt
done
<file_sep>/README.md
# Shell
Lessons learned through Shell language
<file_sep>/practicingConcactenating.sh
header='01'
sendingmessage=$header$1
echo $sendingmessage
|
5a4100cb2bedddc37d1a45af745185d48a62a9f9
|
[
"Markdown",
"Shell"
] | 7
|
Shell
|
Aura-Buddy/Shell
|
224e4a53e697de0bf4c37e982b233ab7e7ce3130
|
2d535449f006a8735a886fadf2506641ba191507
|
refs/heads/develop
|
<repo_name>Vladik/fcdk.live<file_sep>/README.md
# fcdk.live
Test text
<file_sep>/Source/functions/parse-fcdkv.js
const request = require('request');
const cheerio = require('cheerio');
module.exports = {
parse: function parse(db) {
var host = 'http://www.fcdynamo.kiev.ua/ru/';
request(host, function (error, response, html) {
if (!error && response.statusCode == 200) {
var $ = cheerio.load(html);
$($('#tab_news1 > ul.news-list > li > div.text-holder > h3 > a').get().reverse()).each(function(i, element){
var time = new Date().getTime();
var title = $(this).text();
var href = $(this).attr('href');
var id = 'fcdkv' + href.toLowerCase().replace(/[^\w\s]/gi,'').slice(-15);
var content = db.child(id);
content.once('value', function(snapshot) {
if(snapshot.val() === null){
content.set({
title: title,
url: href,
time: time
});
}
});
});
}
});
}
};
<file_sep>/Source/functions/parse-dymna.js
const request = require('request');
const cheerio = require('cheerio');
module.exports = {
parse: function parse(db) {
var host = 'http://www.dynamomania.com';
request(host, function (error, response, html) {
if (!error && response.statusCode == 200) {
var $ = cheerio.load(html);
$($('div.news > .message a').get().reverse()).each(function(i, element){
var time = new Date().getTime();
var title = $(this).find('div.text-main').text();
var href = $(this).attr('href');
var id = 'dymna' + href.toLowerCase().replace(/[^\w\s]/gi,'').slice(-15);
var content = db.child(id);
content.once('value', function(snapshot) {
if(snapshot.val() === null){
content.set({
title: title,
url: host + href,
time: time
});
}
});
});
}
});
}
};
<file_sep>/Source/public/scripts/index.js
(function(){
const config = {
apiKey: "<KEY>",
authDomain: "fcdklive.firebaseapp.com",
databaseURL: "https://fcdklive.firebaseio.com",
projectId: "fcdklive",
storageBucket: "fcdklive.appspot.com",
messagingSenderId: "665462413870"
};
firebase.initializeApp(config);
const db = firebase.database().ref('/content');
const content = document.getElementById('content');
db.orderByChild('time').on('child_added', function(snap, prev){
var item = snap.val();
content.innerHTML = '<p><a id=\'' + snap.getKey() + '\' href=\'' + item.url + '\'>' + item.title + '</a> <span>' + item.time + ' ' + moment([2007, 0, 29]).fromNow() + '</span></p>' + content.innerHTML;
})
}());
|
e928ccc42b9d6efbbb960f29e2364c4f6e78dfdd
|
[
"Markdown",
"JavaScript"
] | 4
|
Markdown
|
Vladik/fcdk.live
|
5d28bfb89f37b994ddd862b27cd903970a2aaa95
|
21f3f62c698fc1c403e4ae5ec61adb3a8dfb1711
|
refs/heads/master
|
<file_sep># This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
Post.create ([
{title: 'Mt. Dandenong', body: "Climbs include: Devils Elbow, 1 in 20, The Cresent, The Wall, Sky High" },
{title: 'Kinglake', body: "7.2km climb, 349m ascent, 4.8% avg gradient" },
{title: 'Mt. Macedon', body: "Gisborne side: 9.1km climb, 491m ascent, 5.4% avg gradient. Woodend side: 11.0km climb, 424m ascent, 3.9% avg gradient" },
{title: 'Skenes Creek', body: "9.2km climb, 489m ascent, 5.1% avg gradient" },
{title: 'Arthurs Seat', body: "3.0km climb, 208m ascent, 8.1% avg gradient" },
{title: 'Lake Mountain', body: "21.3km climb, 908m ascent, 4.3% avg gradient" },
{title: 'Dinner Plain', body: "42.2km climb, 943m ascent, 2.2% avg gradient" },
{title: 'Mt. Buffalo', body: "20.9km climb, 1013m ascent, 4.8% avg gradient" },
{title: 'Mt. Buller', body: "16.8km climb, 985m ascent, 5.9% avg gradient" },
{title: 'Falls Creek', body: "Mt. Beauty side: 29.8km climb, 1164m ascent, 3.9% avg gradient. Omeo side: 23.4km climb, 980m ascent, 4.2% avg gradient." },
{title: '<NAME>', body: "30.8km climb, 1279m ascent, 4.2% avg gradient" },
{title: 'Mt. Baw Baw', body: "Victoria's steepest Climb: 12.5km climb, 962m ascent, 7.7% avg gradient"}
])<file_sep>[<img src="http://cloudcyclist.herokuapp.com/assets/logo-a140535167bc25333e28adac5059ea8d.svg" title="Check it out"/>](http://cloudcyclist.herokuapp.com)
Cloud cyclist is a work in progress bike blog that will be worked on in stages.
[Check out Cloudcyclist](http://cloudcyclist.herokuapp.com)
###Stage 1
1. Create a Post and Comment functionality
2. Seed a database to be used as a starting point
###Technologies used
* [Devise](https://github.com/plataformatec/devise): Devise is a flexible authentication solution for Rails based on Warden.
* [Sass](https://github.com/rails/sass-rails): This gem provides official integration for Ruby on Rails projects with the Sass stylesheet language
Stage 2
-------
* Exciting features to come...
Suggestions?
--------------
* Better way to do something
* Desired features
* [Contact me](mailto:<EMAIL>)
|
ecdf22f4586b6aa6140d595182604225f55132ee
|
[
"Markdown",
"Ruby"
] | 2
|
Ruby
|
drej2k/Bike_Blog
|
34a56c58f2ecc5f575e62afce218a69b70cda527
|
a58ba5f4fba1d6f8ab0ae1706b4b927448e50b09
|
refs/heads/master
|
<file_sep># make dir in weekly wit year-month-day-week
mkdir /mnt/data/mssql-backup/weekly/$(date +%Y-%m-%d-%W)-bookit
# copy files
cp /mnt/data/bookit-mssql/* /mnt/data/mssql-backup/weekly/$(date +%Y-%m-%d-%W)-bookit
mkdir /mnt/data/mssql-backup/weekly/$(date +%Y-%m-%d-%W)-sso
cp -r /mnt/data/jpproject-mysql/* /mnt/data/mysql-backup/weekly/$(date +%Y-%m-%d-%W)-sso
exit 0
<file_sep># remove last week
rm -rf /mnt/data/mssql-backup/daily/$(date --date='4 week ago' +%W)
rm -rf /mnt/data/msyql-backup/daily/$(date --date='4 week ago' +%W)
exit 0
<file_sep>mkdir /mnt/data/mssql-backup/daily/$(date +%W)
mkdir /mnt/data/mysql-backup/daily/$(date +%W)
exit 0
<file_sep>FROM ubuntu:16.04
RUN apt-get update
RUN apt-get install -y apt-utils curl apt-transport-https ca-certificates
RUN curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add -
RUN curl https://packages.microsoft.com/config/ubuntu/16.04/prod.list | tee /etc/apt/sources.list.d/msprod.list
RUN apt-get update
RUN ACCEPT_EULA=Y apt-get install -y mssql-tools unixodbc-dev
RUN echo 'export PATH="$PATH:/opt/mssql-tools/bin"' >>/etc/bash.bashrc
WORKDIR /usr/src/app
CMD ["/bin/bash" ]
<file_sep>mkdir /mnt/data/mssql-backup/daily/$(date +%W)/$(date +%Y-%m-%d_%H-%M)-Bookit
cp /mnt/data/bookit-mssql/* /mnt/data/mssql-backup/daily/$(date +%W)/$(date +%Y-%m-%d_%H-%M)-Bookit
exit 0
<file_sep>mkdir /mnt/data/mssql-backup/weekly
mkdir /mnt/data/mssql-backup/daily
mkdir /mnt/data/mysql-backup/weekly
mkdir /mnt/data/mysql-backup/daily
exit 0
<file_sep>for dir in ./$1/*; do
if [ ! "$dir" = "./$1/original-backup" ]; then
echo ${dir}
rm -rf $dir
fi
done
exit 0
<file_sep>mkdir /mnt/data/mysql-backup/daily/$(date +%W)/$(date +%Y-%m-%d_%H-%M)-sso
cp -r /mnt/data/jpproject-mysql/* /mnt/data/mysql-backup/daily/$(date +%W)/$(date +%Y-%m-%d_%H-%M)-sso
exit 0
|
e44d778df859c1835956e68dc74a2e00e103ad79
|
[
"Dockerfile",
"Shell"
] | 8
|
Shell
|
Ilger/backup-scripts
|
aa7fc63ef40675f3e5c7246014dc0db4d9a89a98
|
4974009b15ee72cccb40f7eeff4651c2bf7028c3
|
refs/heads/master
|
<repo_name>bstahler123/selfiemyparty<file_sep>/assets/js/project.js
$(".services").click(function() {
event.preventDefault()
$(".contact").removeClass("active");
$(".services").addClass("active");
$(".gallery").removeClass("active");
$('html, body').animate({
scrollTop: $("#section1").offset().top
}, 1500);
});
$(".contact").click(function() {
event.preventDefault()
$(".contact").addClass("active");
$(".services").removeClass("active");
$(".gallery").removeClass("active");
$('html, body').animate({
scrollTop: $("#contact-container").offset().top
}, 1500);
});
$(".gallery").click(function() {
event.preventDefault()
$(".contact").removeClass("active");
$(".services").removeClass("active");
$(".gallery").addClass("active");
$('html, body').animate({
scrollTop: $("#gallery").offset().top
}, 1500);
});
$(".home").click(function() {
event.preventDefault()
$(".home").addClass("active");
$(".contact").removeClass("active");
$(".services").removeClass("active");
$(".gallery").removeClass("active");
$('html, body').animate({
scrollTop: $("#carousel-example-generic").offset().top
}, 1500);
});
|
e4585ae8849736548ccb8c4ca131e499eaaaa839
|
[
"JavaScript"
] | 1
|
JavaScript
|
bstahler123/selfiemyparty
|
7aef4cac0028a1d29454305ea0a195d448e31fe8
|
67aa81fab88c75aa5b0c34d63799841154c177d5
|
refs/heads/master
|
<repo_name>OnePaaS/auth-server<file_sep>/src/main/scripts/get_jwt_token.sh
#!/bin/zsh
# echo $CLIENT_ID
# echo $CLIENT_SECRET
# echo $CLIENT_USERNAME
# echo $CLIENT_PASSWORD
# echo ''
curl -s $CLIENT_ID:$CLIENT_SECRET@$AUTHWEB_URL/oauth/token \
-d grant_type=password \
-d username=$CLIENT_USERNAME \
-d password=$<PASSWORD>
<file_sep>/src/main/scripts/gen_jwt_key_store.sh
# export GOBLIIP_STOREPASS=<PASSWORD>
# export GOBLIIP_KEYPASS=<PASSWORD>
# export GOBLIIP_KEYALIAS=authServerKey
keytool -genkeypair -alias $GOBLIIP_KEYALIAS -keyalg RSA \
-dname "CN=Gobliip,OU=gobliip-auth,O=Gobliip,L=Guatemala City,S=Guatemala,C=GT" \
-keypass $GOBLIIP_KEYPASS -keystore ../resources/jwt.jks -storepass $GOBLIIP_STOREPASS<file_sep>/CHANGELOG.md
0.0.1
-----
- First relase get tokens for subscribed users on behalf of applications
<file_sep>/src/main/resources/db/migration/V2_1__seed_admin_user.sql
INSERT INTO users (username, password, enabled) VALUES ('admin','<PASSWORD>',1);
INSERT INTO authorities (username, authority) VALUES ('admin','ROLE_ADMIN'),('admin','ROLE_USER');
<file_sep>/src/main/resources/db/migration/V1_1__seed_oauth_client_details.sql
INSERT INTO oauth_client_details (
client_id,
resource_ids,
client_secret,
scope,
authorized_grant_types,
web_server_redirect_uri,
authorities,
access_token_validity,
refresh_token_validity,
additional_information,
autoapprove
) VALUES (
'acme',
'',
'acmesecret',
'openid',
'authorization_code,refresh_token,<PASSWORD>',
'',
'',
NULL,
NULL,
'{}',
''
);
|
94c59fe9de6b87d4f155c18a6f065fe2d52195a7
|
[
"Markdown",
"SQL",
"Shell"
] | 5
|
Shell
|
OnePaaS/auth-server
|
c4abb541e7b13acca0a981a2dd1035c05819f14f
|
36ee28b882d48b2a0f7e1d08d21b47d1cad478ec
|
refs/heads/master
|
<file_sep>
#Mihai
#install.packages("FactoMineR") & install.packages("factoextra")
library(FactoMineR)
library(factoextra)
library(dplyr)
library(tidyr)
library(mlbench)
library(caret)
library(corrplot)
library(caretEnsemble)
library(rpart)
library(rattle)
setwd("~/Documents/UNCC/ITCS6162_KDD/DataProcessingandModeling")
#loan.data <- read.csv(file="application_train.csv", header=TRUE, sep=",")
loan.data.all <- read.csv(file="./all/application_train_all.csv", header=TRUE, sep=",")
loan.data.all2.no.na <-na.omit(loan.data.all[ , colSums(is.na(loan.data.all)) <100])
#standardize selected columns
out_col <- c(8,9,10,16,17,18,19,20,44)
for(i in 1:length(out_col)){
loan.data.all2.no.na[,out_col[i]] <- (loan.data.all2.no.na[,out_col[i]] - mean(loan.data.all2.no.na[,out_col[i]]))/sd(loan.data.all2.no.na[,out_col[i]])
}
#outliers removing
for(i in 1:length(out_col)){
loan.data.all2.no.na <- loan.data.all2.no.na[!(loan.data.all2.no.na[,out_col[i]] > 3) ,]
}
#write.csv(loan.data.all2.no.na, 'all/training.all.no.na.csv', row.names=FALSE)
loan.data.all2.no.na <- read.csv(file="./all/training.all.no.na.csv", header=TRUE, sep=",")
test.data <- read.csv(file="./all/application_test.csv", header=TRUE, sep=",")
#take a random sample of size 3000
loan.data.all2.no.na <- loan.data.all2.no.na[sample(1:nrow(loan.data.all2.no.na), 1000,
replace=FALSE),]
options(warn=-1)
suppressWarnings()
#saving the ones
target.one <- loan.data.all2.no.na[loan.data.all2.no.na$TARGET==1,]
#how many samples have target 1
sum(target.one$TARGET)
#saving zeros
target.zero <- loan.data.all2.no.na[loan.data.all2.no.na$TARGET==0,]
#how many zeros
sum(!target.zero$TARGET)
#clustering zeros
classes <- sapply(target.zero, class)
num.loan <- target.zero[,classes=="numeric"]
num.loan$SK_ID_CURR <- target.zero$SK_ID_CURR
num.loan$TARGET <- target.zero$TARGET
head(num.loan,1)
df <- na.omit(num.loan) #just to make sure NA omit
df2.scale<-na.omit(num.loan)
omit.columns <- c("SK_ID_CURR","TARGET")
m <- apply(df2.scale[,-which(names(df2.scale) %in% omit.columns)], 2, mean)
s <- apply(df2.scale[,-which(names(df2.scale) %in% omit.columns)], 2, sd)
#classes <- sapply(df, class)
#z<- scale(df[,classes=="numeric"], m, s)
df2.scale[,-which(names(df2.scale) %in% omit.columns)] <- lapply(df2.scale[,-which(names(df2.scale) %in% omit.columns)], function(x) c(scale(x), m, s))
z<- scale(df[,-which(names(df2.scale) %in% omit.columns)], m, s)
head(df2.scale,1)
# Scree Plot for k-means and selecting the number of clusters
#there are 3 obvious clusters
wss <- (nrow(df2.scale[,-which(names(df2.scale) %in% omit.columns)])-1)*sum(apply(df2.scale[,-which(names(df2.scale) %in% omit.columns)],2,var))
for (i in 2:20) wss[i] <- sum(kmeans(df2.scale[,-which(names(df2.scale) %in% omit.columns)], centers=i)$withinss)
plot(1:20, wss, type="b", xlab="Number of Clusters", ylab="Within groups sum of squares")
# K-means clustering
kc<-kmeans(df2.scale[,-which(names(df2.scale) %in% omit.columns)],3)
#we see that the ratio between_SS values and total_SS values is: 25.4%
kc
kc$cluster
kc$centers
#Determine which Id belongs to which cluster and add this data
# to the df2.scale in form of cluster number:1, 2, or 3 per each id
out <- cbind(df2.scale, Cluster.Num = kc$cluster)
head(out,1)
plot(out[,c("AMT_CREDIT","Cluster.Num")])
plot(out[,"Cluster.Num"], (out[, "AMT_INCOME_TOTAL"]))
#there are 0 unavailable values for credit clusters since we removed the NA info at the begining
sum(is.na(out$Cluster.Num))
#there are 0 duplicate credit records
sum(duplicated(out$SK_ID_CURR))
#adding the credit cluster data to the training data too:
target.zero.wCluster <- cbind(target.zero, Cluster.Num = NA) #create column
for (row in 1:nrow(out)) {
SK_ID <- out[row, "SK_ID_CURR"]
SK_ID
#update column
target.zero.wCluster[target.zero.wCluster$SK_ID_CURR==SK_ID, "Cluster.Num"] <- out[out$SK_ID_CURR==SK_ID, "Cluster.Num"]
}
head(target.zero.wCluster)
#loan.data.all.wClusterCredit["SK_ID_CURR"==100083, "Cluster.Num"] <- out["SK_ID_CURR"==100083, "Credit.Cluster.Num"]
cluster.training.set <- na.omit(target.zero.wCluster)
sum(cluster.training.set$TARGET==1)
sum(cluster.training.set$TARGET==0)
#uncheck the following to save the ones and zeros
#write.csv(target.zero.wCluster, 'all/target.zero.wCluster.csv', row.names=FALSE)
#write.csv(target.one, 'all/target.one.csv', row.names=FALSE)
###############################################
# ensure the results are repeatable
set.seed(7)
# calculate correlation matrix
correlationMatrix <- cor(target.zero[,classes=="numeric"])#3:64
# summarize the correlation matrix
print(correlationMatrix)
# find attributes that are highly corrected (ideally >0.75)
highlyCorrelated <- findCorrelation(correlationMatrix, cutoff=0.5)
# print indexes of highly correlated attributes
print(highlyCorrelated) #AMT_ANNUITY/AMT_CREDIT
corrplot(correlationMatrix, method=c('number'),title='correlation matrix',diag=T)
#Rank features by importance using the caret r packageR
# prepare training scheme
loan.data.all2.no.na$TARGET<-as.factor(loan.data.all2.no.na$TARGET)
d <- loan.data.all2.no.na[,classes=="numeric" || classes=="integer" || classes=="double"]
control <- trainControl(method="repeatedcv", number=3)#, repeats=3)
# train the model
model <- train(TARGET~., data=d[,c(2:64)], method="lvq", preProcess="scale", trControl=control)
# estimate variable importance
importance <- varImp(model, scale=FALSE)
# summarize importance
print(importance)
# plot importance
plot(importance)
##Feature selection (dimensionality reduction) with PCA
classes <- sapply(loan.data.all2.no.na, class)
loan.data.numeric <- loan.data.all2.no.na[,classes=="numeric"]
#loan.data.complete <- complete.cases(loan.data.all[,classes=="numeric"])
loan.data.complete <- na.omit(loan.data.numeric) #!is.na(loan.data.numeric))
m.pca <- apply(loan.data.complete, 2, mean)
s.pca <- apply(loan.data.complete, 2, sd)
z.pca <- scale(loan.data.complete, m.pca, s.pca)
#we observe 65 principal components with 26 PCs over 85% contributing to the
#variability we see in the sample
l.pca <- prcomp(z.pca)#, center = TRUE, scale. = TRUE)
summary.pca <- summary(l.pca)
#head(l.pca)
#str(l.pca)
#distance <- dist(z.pca)
#str(distance)
#percentage of variance captured by PCA
pca_pr <- round(100*summary.pca$importance[2, ], digits = 1)
pca_pr
#axis labels
pc_lab <- paste0(names(pca_pr), " (", pca_pr, "%)")
pc_lab
#pca biplot
biplot(l.pca, cex = c(0.8, 1), col = c("grey40", "deeppink2"), xlab = pc_lab[1], ylab = pc_lab[2])
#PCA with MLBench
preprocParam <- preProcess(loan.data.numeric, method=c("center", "scale", "pca"))
# summarize preprocessed
print(preprocParam)
# transform the data
tran <- predict(preprocParam, loan.data.all2.no.na)
# summarize the transformed dataset
summary(tran)
## Feature selection with unsupervised Multiple Correspondence Analysis (MCA)
theme_set(theme_bw(12))
nfactors <- apply(loan.data.all2.no.na, 2, function(x) nlevels(as.factor(x)))
nfactors
head(loan.data.all2.no.na[,c(2:5)])
col.selected <- c(3:6, 11:15, 27, 31, 39:43)
loan.selected <- select(loan.data.all2.no.na, col.selected)
mca <- MCA(loan.selected, graph = FALSE)
#length(loan.data.all2.no.na)
# summary of the model
summary(mca)
summary(loan.selected)
#visualize the dataset
dev.off()
gather(loan.selected) %>% ggplot(aes(value)) + facet_wrap("key", scales = "free") + geom_bar() + theme(axis.text.x = element_text(angle = 45, hjust = 1, size = 3))
# visualize MCA
plot.MCA(mca)
plot(mca, invisible=c("ind"), habillage = "quali", cex=0.5)
#income type occupation type
## Supervised feature selection with Caret
# prepare training scheme
control <- trainControl(method="repeatedcv", number=3)#, repeats=3)
# train the model
loan.data.all2.no.na$TARGET<-as.factor(loan.data.all2.no.na$TARGET)
model <- train(TARGET~., data=loan.data.all2.no.na[,c(2:64)], method="lvq", preProcess="scale", trControl=control)#, ntree=50
# estimate variable importance
importance <- varImp(model, scale=FALSE)
# summarize importance
print(importance)
# plot importance
par(cex.lab=2)
dev.off()
plot.new()
axis(2,cex.axis=1, cex.lab=1)
plot(importance, cex.names=0.1, cex.lab=1, cex.axis=1) #cex=1
##Supervised Recursive Feature Elimination (RFE)
control <- rfeControl(functions=rfFuncs, method="cv", number=3)
# run the RFE algorithm
#results <- rfe(loan.data.all2.no.na[,c(2:10)], loan.data.all2.no.na[,c(1)], sizes=c(2:10), rfeControl=control)
results <- rfe(loan.d[,c(2:10)], loan.data.all2.no.na[,c(1)], sizes=c(2:10), rfeControl=control)
# summarize the results
print(results)
# list the chosen features
predictors(results)
# plot the results
plot(results, type=c("g", "o"))
#creating levels
#str(loan.data.all2.no.na)
#int.numerical <- loan.data.all2.no.na[, classes=='integer']
#creating factors out of the integer
for(i in 1:length(loan.data.all2.no.na)){
if(class(loan.data.all2.no.na[,i])=='integer'){
loan.data.all2.no.na[,i] <- as.factor(loan.data.all2.no.na[,i])
}
}
# creating 3 level categorical variables from numerical using
# lower, medium and upper quartile
#checking the categories for each variable
nfactors <- apply(loan.data.all2.no.na, 2, function(x) nlevels(as.factor(x)))
nfactors
#ensure the categories per variable are at least 2
loan.data.all2.no.na <- loan.data.all2.no.na[,!(nfactors<=1)]
# Stacking ensemble
#ensuring the TARGET has valid category names YES and NO not 0 and 1
levels(loan.data.all2.no.na$TARGET) <- c("NO", "YES")
levels(loan.data.all2.no.na$TARGET)
#control <- trainControl(method="repeatedcv", number=10, repeats=3, savePredictions=TRUE, classProbs=TRUE)
control <- trainControl(method="repeatedcv", number=3, savePredictions=TRUE, classProbs=TRUE)
alg <- c('rpart', 'knn')# 'lda', 'svmRadial', 'glm'
set.seed(7)
models <- caretList(TARGET~., data=loan.data.all2.no.na[,2:4], trControl=control, methodList=alg)
r <- resamples(models)
summary(r)
dotplot(r)
# correlation
modelCor(r)
splom(r)
# stack using glm
stackControl <- trainControl(method="repeatedcv", number=3, repeats=3, savePredictions=TRUE, classProbs=TRUE)#
set.seed(7)
stack.glm <- caretStack(models, method='rpart', metric="Accuracy", trControl=stackControl)
print(stack.glm)
# stack using random forest
set.seed(7)
stack.rf <- caretStack(models, method="rf", metric="Accuracy", trControl=stackControl)
print(stack.rf)
## Ensamble bagging CART and Random Forest
control <- trainControl(method="repeatedcv", number=2, repeats=2)#cv
metric <- "Accuracy"
# Bagged CART
set.seed(7)
#dataset<-na.omit(cluster.training.set)
fit.treebag <- train(TARGET~., data=loan.data.all2.no.na[,1:5], method="treebag", metric=metric, trControl=control)
# Random Forest
set.seed(7)
fit.rf <- train(TARGET~., data=loan.data.all2.no.na[,1:5], method="rf", metric=metric, trControl=control, ntree=100)
# summarize results
bagging_results <- resamples(list(treebag=fit.treebag, rf=fit.rf))
summary(bagging_results)
dotplot(bagging_results)
##Simply rpart
loan.data.all2.no.na <- read.csv(file="./all/training.all.no.na.csv", header=TRUE, sep=",")
#-----
table(loan.data.all2.no.na$CODE_GENDER)
loan.data.all2.no.na[, CODE_GENDER=="F"]
value0 <- loan.data.all2.no.na[loan.data.all2.no.na$TARGET==0,]
value1 <- loan.data.all2.no.na[loan.data.all2.no.na$TARGET==1,]
value0.balance <- value0[sample(1:nrow(value0), nrow(value1),
replace=FALSE),]
data.balanced <- rbind(value0.balance,value1)
prop.table(table(loan.data.all2.no.na$TARGET,loan.data.all2.no.na$CODE_GENDER)/100)
table(loan.data.all2.no.na$TARGET,loan.data.all2.no.na$NAME_CONTRACT_TYPE)/100
table(loan.data.all2.no.na$TARGET,loan.data.all2.no.na$FLAG_OWN_CAR)/100
#rpart the decision tree
loan.tree <- rpart(TARGET ~ ., data = data.balanced, method = "class")
# Visualize the decision tree using plot() and text()
plot(loan.tree)
text(loan.tree)
# Load in the packages to build a fancy plot
#needs rattle
fancyRpartPlot(loan.tree)
##Kaggle: - Preparing the solutions and CSV file for the submission
# Making predictions on the test set
my_prediction <- predict(loan.tree, newdata = test.data, type = "class")
my_solution <- data.frame(SK_ID_CURR = test.data$SK_ID_CURR, TARGET = my_prediction)
nrow(my_solution)
write.csv(my_solution, file = "group5.csv", row.names = FALSE)
<file_sep>#July 31, 2018 KDD Class UNC Charlotte
#Team Members:
# <NAME>
# <NAME>
# <NAME>
# <NAME>
#load libraries
if(!require(missForest)) install.packages("missForest",repos = "http://cran.us.r-project.org")
if(!require(VIM)) install.packages("VIM",repos = "http://cran.us.r-project.org")
if(!require(mice)) install.packages("mice",repos = "http://cran.us.r-project.org")
if(!require(corrplot)) install.packages("corrplot",repos = "http://cran.us.r-project.org")
if(!require(scales)) install.packages("scales",repos = "http://cran.us.r-project.org")
if(!require(tidyr)) install.packages("tidyr",repos = "http://cran.us.r-project.org")
library(missForest)
library(VIM)
library(ggplot2)
library(plyr)
library(e1071)
library(mice)
library(corrplot)
library(tidyr)
library(scales)
#load data files
setwd("~/Documents/UNCC/ITCS6162_KDD/DataProcessingandModeling")
#read all CSVs
filenames <- list.files(path = "./all/", full.names=TRUE)
#all.csv <- lapply(filenames,function(i){
# read.csv(i, header=FALSE, skip=4)
#})
#loan.data <- read.csv(file="application_train.csv", header=TRUE, sep=",")
loan.data.all <- read.csv(file="./all/application_train_all.csv", header=TRUE, sep=",")
ccard <- read.csv(file="all/credit_card_balance.csv", header = TRUE, sep=",")
previous.application <- read.csv(file="all/previous_application.csv", header = TRUE, sep=",")
POS.CASH.balance <- read.csv(file="all/POS_CASH_balance.csv", header = TRUE, sep=",")
installments.payments <- read.csv(file="all/installments_payments.csv", header = TRUE, sep=",")
bureau <- read.csv(file="all/bureau.csv", header = TRUE, sep=",")
bureau.balance <- read.csv(file="all/bureau_balance.csv", header = TRUE, sep=",")
#attach(loan.data)
attach(loan.data.all)
attach(ccard)
source("outlierscript.R")
total1 <- merge(loan.data.all, ccard, by=c("SK_ID_CURR"))
write.csv(total1, 'all/total1.csv', row.names=FALSE)
total1 <- read.csv(file="all/total1.csv", header = TRUE, sep=",")
prev1 <- merge(previous.application, POS.CASH.balance, by=c("SK_ID_PREV"))
colnames(prev1)[2] <- 'SK_ID_CURR'
write.csv(prev1, 'all/prev1.csv', row.names=FALSE)
prev1 <- na.omit(prev1)
prev1 <- read.csv(file="all/prev1.csv", header = TRUE, sep=",")
prev2 <- merge(prev1, installments.payments, by=c("SK_ID_PREV"))
prev2 <- prev2[, !(names(prev2)=='SK_ID_CURR.y')]
prev2 <- prev2[, !(names(prev2)=='NAME_CONTRACT_STATUS.y')]
colnames(prev2)[2] <- 'SK_ID_CURR'
colnames(prev2)[17] <- 'NAME_CONTRACT_STATUS'
write.csv(prev2, 'all/prev2.csv', row.names=FALSE)
prev2 <- read.csv(file="all/prev2.csv", header = TRUE, sep=",")
#prev3 <- merge(prev2, ccard, by=c("SK_ID_PREV"))
#write.csv(prev3, 'all/prev3.csv', row.names=FALSE)
total1 <- read.csv(file="all/total1.csv", header = TRUE, sep=",")
total2 <- merge(prev2, total1, by=c("SK_ID_CURR"))
total2 <- total2[, !(names(total2)=='NAME_CONTRACT_STATUS.y')]
colnames(total2)[17] <- 'NAME_CONTRACT_STATUS'
total2 <- total2[, !(names(total2)=='NAME_CONTRACT_TYPE.y')]
colnames(total2)[3] <- 'NAME_CONTRACT_TYPE'
write.csv(total2, 'all/total2.csv', row.names=FALSE)
bureau.merged <- merge(bureau.balance, bureau, by=c("SK_ID_BUREAU"))
write.csv(bureau.merged, 'all/bureau.merged.csv', row.names=FALSE)
total2 <- read.csv(file="all/total2.csv", header = TRUE, sep=",")
total2<-na.omit(total2)
head(table(total2$SK_ID_CURR),10)
bureau.merged <- read.csv(file="all/bureau.merged.csv", header = TRUE, sep=",")
bureau.merged <- na.omit(bureau.merged)
total3 <- merge(total2, bureau.merged, by=c("SK_ID_CURR"))
write.csv(total3, 'all/total3.csv', row.names=FALSE)
total3 <- read.csv(file="all/total3.csv", header = TRUE, sep=",")
#use summary to get information on attributes
summary(loan.data)
names(loan.data)
#Missing Values - analyze missing values in the data
sapply(loan.data, function(x) sum(is.na(x)))
missing<- loan.data[!complete.cases(loan.data),]; missing
complete.cases(loan.data) != is.na(loan.data)
sum(table(which(loan.data == ''))) #find how many missing values are there
sum(sapply(loan.data, function(x) sum(is.na(x))))
#using mice:
library(missForest)
library(VIM)
mice_plot <- aggr(loan.data, col=c('navyblue','yellow'),
numbers=TRUE, sortVars=TRUE,
labels=names(loan.data), cex.axis=.7,
gap=3, ylab=c("Missing data","Pattern"))
#Box plot
library(plyr)
#install.packages("ggplot2")
library(ggplot2)
#install.packages("e1071")
library(e1071)
#install.packages("mice")
library(mice)
amt_income <- loan.data$AMT_INCOME_TOTAL
amt_credit <- loan.data$AMT_CREDIT
hist(amt_income) #histogram
hist(amt_credit)
boxplot(loan.data$AMT_INCOME_TOTAL,data=loan.data, main="Income Data",
xlab="Income", ylab="Income")
boxplot(loan.data$AMT_CREDIT,data=loan.data, main="Credit Data",
xlab="Credit", ylab="Credit")
#display amt credit
bp <- ggplot(loan.data, aes(x=AMT_CREDIT, y=AMT_INCOME_TOTAL, group=loan.data$CNT_CHILDREN)) +
geom_boxplot(fill="red", alpha=0.2) +
xlab("AMT CREDIT")+ylab("AMT INCOME")
bp <- bp + scale_x_continuous(trans='log2') +
scale_y_continuous(trans='log2')
bp
ggplot(loan.data, aes(x = as.factor(loan.data$CNT_CHILDREN), fill = CNT_CHILDREN==1, color=loan.data$AMT_INCOME_TOTAL)) +
geom_density(alpha = .3)
ggplot(loan.data[loan.data$AMT_INCOME_TOTAL<100000,], aes(x = AMT_INCOME_TOTAL/10000, fill = as.factor(CNT_CHILDREN))) +
geom_density(alpha = .3)
ggplot(loan.data, aes(x = as.factor(loan.data$CNT_CHILDREN), fill = AMT_CREDIT)) +
geom_density(alpha = .3)
ggplot(loan.data, aes(x = as.factor(loan.data$CNT_CHILDREN), fill = AMT_CREDIT)) +
geom_density(alpha = .3)
#display amt income
#using CNT Children since it has discrete integer values to deal with continuous values and separate the groups
bp <- ggplot(loan.data, aes(x="", y=AMT_CREDIT, group=loan.data$CNT_CHILDREN)) +
geom_boxplot(fill="blue", alpha=0.2) +
xlab("CNT CHILDREN")+ylab("AMT CREDIT")
bp <- bp + scale_y_continuous(trans='log2')
bp
par(mar=c(1,1,1,1))
outlierKD(loan.data, AMT_INCOME_TOTAL)
outlierKD(loan.data, AMT_CREDIT)
#flag variables
#loan.data["NAME_FAMILY_STATUS"] <- 0
loan.data$NAME_FAMILY_STATUS <- loan.data$NAME_FAMILY_STATUS > 0
loan.data$NAME_FAMILY_STATUS
loan.data$flag_s_not_m <- 0
loan.data$flag_m <- 0
loan.data$flag_c_m <- 0
loan.data$flag_w <- 0
loan.data$flag_s <- 0
#flag family status
loan.data$flag_s_not_m[loan.data$NAME_FAMILY_STATUS == 'Single / not married'] <- 1
#check field
loan.data$flag_s_not_m
#continue for all other fields
loan.data$flag_m[loan.data$NAME_FAMILY_STATUS == 'Married'] <- 1
#check field
loan.data$flag_m
loan.data$flag_c_m[loan.data$NAME_FAMILY_STATUS == 'Civil Marriage'] <- 1
#check field
loan.data$flag_c_m
loan.data$flag_w[loan.data$NAME_FAMILY_STATUS == 'Widow'] <- 1
#check field
loan.data$flag_w
loan.data$flag_s[loan.data$NAME_FAMILY_STATUS == 'Separated'] <- 1
#check field
loan.data$flag_s
count(loan.data, 'flag_s_not_m')
count(loan.data, 'flag_m')
count(loan.data, 'flag_c_m')
count(loan.data, 'flag_w')
count(loan.data, 'flag_s')
#Z-Score Standardization.
loan.data$zscore.income <- (loan.data$AMT_INCOME_TOTAL - mean(loan.data$AMT_INCOME_TOTAL))/sd(loan.data$AMT_INCOME_TOTAL)
loan.data$zscore.income
loan.data$zscore.credit <- (loan.data$AMT_CREDIT - mean(loan.data$AMT_CREDIT))/sd(loan.data$AMT_CREDIT)
loan.data$zscore.credit
income_skew <- (3*(mean(loan.data$AMT_INCOME_TOTAL)-median(loan.data$AMT_INCOME_TOTAL))) / sd(loan.data$AMT_INCOME_TOTAL)
income_skew
credit_skew <- (3*(mean(loan.data$AMT_CREDIT)-median(loan.data$AMT_CREDIT))) / sd(loan.data$AMT_CREDIT)
credit_skew
skewincome = loan.data$zscore.income
skewa = skewness(skewincome) #skewness fc.
skewa
skewcredit = loan.data$zscore.credit
skewa = skewness(skewcredit) #skewness fc
skewa
outlierKD(loan.data, zscore.income)
loan.data$zscore.credit <- (loan.data$AMT_CREDIT - mean(loan.data$AMT_CREDIT))/sd(loan.data$AMT_CREDIT)
loan.data$zscore.credit
skewcredit = loan.data$zscore.credit
skewa = skewness(skewcredit) #skewness fc
skewa
#a more manual approach
amt_credit_sd <- sd(loan.data$AMT_CREDIT)
amt_credit_mean <- mean(loan.data$AMT_CREDIT)
amt_credit_sd
amt_credit_mean
zscore.amt_credit <- (loan.data$AMT_CREDIT - amt_credit_mean) / amt_credit_sd
outlierKD(loan.data, zscore.credit)
#Remove outliers
clean.data <- loan.data[! (zscore.amt_credit > 3) ,]
# and use invert square, we get normal distribution
invert_sq_amt_credit = 1 / sqrt(clean.data$AMT_CREDIT)
qqnorm(invert_sq_amt_credit,
datax = TRUE,
col = "red",
ylim = c(0.0007441199, 0.004714045),
main = "Normal Q-Q Plot of Cleaned Inverted amount credit")
qqline(invert_sq_amt_credit,
col = "blue",
datax = TRUE)
# Use binning to discretize AMT_TOTAL_INCOME
# into five bins named A through E with A being the lowest
# and E being the highest - name the new attribute CAT_AMT_TOTAL_INCOME
loan.data$CAT_AMT_TOTAL_INCOME[loan.data$AMT_INCOME_TOTAL > 0 & loan.data$AMT_INCOME_TOTAL <= 100000 ] <- "A"
loan.data$CAT_AMT_TOTAL_INCOME[loan.data$AMT_INCOME_TOTAL > 100000 & loan.data$AMT_INCOME_TOTAL <= 150000 ] <- "B"
loan.data$CAT_AMT_TOTAL_INCOME[loan.data$AMT_INCOME_TOTAL > 150000 & loan.data$AMT_INCOME_TOTAL <= 200000 ] <- "C"
loan.data$CAT_AMT_TOTAL_INCOME[loan.data$AMT_INCOME_TOTAL > 200000 & loan.data$AMT_INCOME_TOTAL <= 250000 ] <- "D"
loan.data$CAT_AMT_TOTAL_INCOME[loan.data$AMT_INCOME_TOTAL > 250000 ] <- "E"
#Use MICE to impute appropriate values for
#the missing values in CNT_CHILDREN (note: the actual value in
#each case was 0)
#install.packages("mice")
#library(mice)
md.pattern(loan.data)
dataframe_children <- as.data.frame(CNT_CHILDREN)
#note maxit is low due to time for processing can be higher
imputed_Data <- mice(loan.data, m=1, maxit = 2, method = 'cart', seed = 500)
imputed_Data$imp$CNT_CHILDREN
summary(imputed_Data)
densityplot(imputed_Data)
completedData <- complete(imputed_Data,1)
sapply(completedData, function(x) sum(is.na(x)))
#Contingency table
table(loan.data$NAME_FAMILY_STATUS,loan.data$NAME_HOUSING_TYPE)
count(loan.data,vars = c("NAME_FAMILY_STATUS","NAME_HOUSING_TYPE"))
#PCA
classes <- sapply(loan.data.all, class)
loan.data.numeric <- loan.data.all[,classes=="numeric"]
#loan.data.complete <- complete.cases(loan.data.all[,classes=="numeric"])
loan.data.complete <- na.omit(loan.data.numeric) #!is.na(loan.data.numeric))
m.pca <- apply(loan.data.complete, 2, mean)
s.pca <- apply(loan.data.complete, 2, sd)
z.pca <- scale(loan.data.complete, m.pca, s.pca)
#we observe 65 principal components with 26 PCs over 85% contributing to the
#variability we see in the sample
l.pca <- prcomp(z.pca, center = TRUE, scale. = TRUE)
summary(l.pca)
head(l.pca)
str(l.pca)
distance <- dist(z.pca)
str(distance)
#K-means clustering
#standardize numeric values
classes <- sapply(loan.data.all, class)
num.loan <- loan.data.all[,classes=="numeric"]
num.loan$SK_ID_CURR <- loan.data.all$SK_ID_CURR
num.loan$TARGET <- loan.data.all$TARGET
head(num.loan,1)
df <- na.omit(num.loan)
df2.scale<-na.omit(num.loan)
m <- apply(df2.scale[,-c(66, 67)], 2, mean)
s <- apply(df2.scale[,-c(66, 67)], 2, sd)
#classes <- sapply(df, class)
#z<- scale(df[,classes=="numeric"], m, s)
df2.scale[,-c(66,67)] <- lapply(df2.scale[,-c(66, 67)], function(x) c(scale(x), m, s))
z<- scale(df[,-c(66, 67)], m, s)
head(df2.scale,1)
distance.euclidian <- dist(df2.scale[,-c(66,67)], method="euclidian")
#install.packages("corrplot")
library("corrplot")
str(distance.euclidian)
rand.sample.vect<-sample(1:100, 10)
#corrplot(as.matrix(distance.euclidian), is.corr = FALSE, method="color")
#identifying correlation between individual samples
round(as.matrix(distance.euclidian)[1:6, 1:6], 1)
resp.correlation <- cor(t(z), method="pearson")
distance.correlation <- as.dist(1-resp.correlation)
round(as.matrix(distance.correlation)[1:6, 1:6], 1)
# Scree Plot for k-means and selecting the number of clusters
#there are 3 obvious clusters
wss <- (nrow(df2.scale[,-c(66,67)])-1)*sum(apply(df2.scale[,-c(66,67)],2,var))
for (i in 2:20) wss[i] <- sum(kmeans(df2.scale[,-c(66,67)], centers=i)$withinss)
plot(1:20, wss, type="b", xlab="Number of Clusters", ylab="Within groups sum of squares")
# K-means clustering
kc<-kmeans(df2.scale[,-c(66,67)],3)
#we see that the ratio between_SS values and total_SS values is: 25.4%
kc
kc$cluster
kc$centers
#Determine which Id belongs to which cluster and add this data
# to the df2.scale in form of cluster number:1, 2, or 3 per each id
out <- cbind(df2.scale, Credit.Cluster.Num = kc$cluster)
head(out,1)
plot(out[,c("AMT_CREDIT","Credit.Cluster.Num")])
plot(out[,"Credit.Cluster.Num"], (out[, "AMT_INCOME_TOTAL"]))
#there are 0 unavailable values for credit clusters since we removed the NA info at the begining
sum(is.na(out$Credit.Cluster.Num))
#there are 0 duplicate credit records
sum(duplicated(out$SK_ID_CURR))
#adding the credit cluster data to the training data too:
loan.data.all.wClusterCredit <- cbind(loan.data.all, Credit.Cluster.Num = NA) #create column
for (row in 1:nrow(out)) {
SK_ID <- out[row, "SK_ID_CURR"]
SK_ID
#update column
loan.data.all.wClusterCredit[loan.data.all.wClusterCredit$SK_ID_CURR==SK_ID, "Credit.Cluster.Num"] <- out[out$SK_ID_CURR==SK_ID, "Credit.Cluster.Num"]
}
head(loan.data.all.wClusterCredit)
#loan.data.all.wClusterCredit["SK_ID_CURR"==100083, "Credit.Cluster.Num"] <- out["SK_ID_CURR"==100083, "Credit.Cluster.Num"]
#CLusters for training only:
#K-means clustering
#standardize numeric values
#df.no.na.col <- sapply(names(loan.data.all), function(x){if(sum(is.na(loan.data.all[,x]))>100){drop(loan.data.all, rm(,x))}})
#df.no.na.col <- sapply(names(loan.data.all), function(x){(colSums(is.na(loan.data.all[,x]))>100)})
#loan.data.all <- na.omit(loan.data.all[df.no.na.col])
#loan.data.all2<-na.omit(loan.data.all[df.no.na.col])
setwd("~/Documents/UNCC/ITCS6162_KDD/DataProcessingandModeling")
#loan.data <- read.csv(file="application_train.csv", header=TRUE, sep=",")
loan.data.all <- read.csv(file="./all/application_train_all.csv", header=TRUE, sep=",")
loan.data.all2.no.na <-na.omit(loan.data.all[ , colSums(is.na(loan.data.all)) <100])
classes <- sapply(loan.data.all, class)
num.loan <- loan.data.all[,classes=="numeric"]
num.loan$SK_ID_CURR <- loan.data.all$SK_ID_CURR
num.loan$TARGET <- loan.data.all$TARGET
head(num.loan,1)
df <- na.omit(num.loan)
df2.scale<-na.omit(num.loan)
m <- apply(df2.scale[,-c(66, 67)], 2, mean)
s <- apply(df2.scale[,-c(66, 67)], 2, sd)
#classes <- sapply(df, class)
#z<- scale(df[,classes=="numeric"], m, s)
df2.scale[,-c(66,67)] <- lapply(df2.scale[,-c(66, 67)], function(x) c(scale(x), m, s))
z<- scale(df[,-c(66, 67)], m, s)
head(df2.scale,1)
distance.euclidian <- dist(df2.scale[,-c(66,67)], method="euclidian")
#install.packages("corrplot")
library("corrplot")
str(distance.euclidian)
# Scree Plot for k-means and selecting the number of clusters
#there are 3 obvious clusters
wss <- (nrow(df2.scale[,-c(66,67)])-1)*sum(apply(df2.scale[,-c(66,67)],2,var))
for (i in 2:20) wss[i] <- sum(kmeans(df2.scale[,-c(66,67)], centers=i)$withinss)
plot(1:20, wss, type="b", xlab="Number of Clusters", ylab="Within groups sum of squares")
# K-means clustering
kc<-kmeans(df2.scale[,-c(66,67)],3)
#we see that the ratio between_SS values and total_SS values is: 25.4%
kc
kc$cluster
kc$centers
#Determine which Id belongs to which cluster and add this data
# to the df2.scale in form of cluster number:1, 2, or 3 per each id
out <- cbind(df2.scale, Cluster.Num = kc$cluster)
head(out,1)
plot(out[,c("AMT_CREDIT","Cluster.Num")])
plot(out[,"Cluster.Num"], (out[, "AMT_INCOME_TOTAL"]))
#there are 0 unavailable values for credit clusters since we removed the NA info at the begining
sum(is.na(out$Cluster.Num))
#there are 0 duplicate credit records
sum(duplicated(out$SK_ID_CURR))
#adding the credit cluster data to the training data too:
loan.data.all.wCluster <- cbind(loan.data.all, Cluster.Num = NA) #create column
for (row in 1:nrow(out)) {
SK_ID <- out[row, "SK_ID_CURR"]
SK_ID
#update column
loan.data.all.wCluster[loan.data.all.wCluster$SK_ID_CURR==SK_ID, "Cluster.Num"] <- out[out$SK_ID_CURR==SK_ID, "Cluster.Num"]
}
head(loan.data.all.wCluster)
#loan.data.all.wClusterCredit["SK_ID_CURR"==100083, "Credit.Cluster.Num"] <- out["SK_ID_CURR"==100083, "Credit.Cluster.Num"]
cluster.training.set <- na.omit(loan.data.all.wCluster)
sum(cluster.training.set$TARGET==1)
sum(cluster.training.set$TARGET==0)
# Load libraries
#install.packages('mlbench') & install.packages('caret') & install.packages('caretEnsemble')
library(mlbench)
library(caret)
library(caretEnsemble)
# Example of Bagging algorithms
control <- trainControl(method="cv", number=10)#, repeats=3)#cv
seed <- 7
metric <- "Accuracy"
# Bagged CART
set.seed(seed)
dataset<-na.omit(cluster.training.set)
fit.treebag <- train(as.factor(TARGET)~., data=dataset, method="treebag", metric=metric, trControl=control)
# Random Forest
set.seed(seed)
fit.rf <- train(as.factor(TARGET)~., data=dataset, method="rf", metric=metric, trControl=control, ntree=100)
# summarize results
bagging_results <- resamples(list(treebag=fit.treebag, rf=fit.rf))
summary(bagging_results)
dotplot(bagging_results)
<file_sep>---
title: " Home Loan credit risk prediction: DataPreparation and Modeling"
author: "Group 5: <NAME>, <NAME>, <NAME>, <NAME>"
date: "8/8/2018"
output:
html_document:
toc: true
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## Summary:
- Preprocessing: missing values, standardization, outliers
- Features selection: supervised, unsupervised
- Ensemble methods for bagging and stacking: rf, CART
```{r librar, include = FALSE}
#install.packages("FactoMineR") & install.packages("factoextra")
library(FactoMineR)
library(factoextra)
library(dplyr)
library(tidyr)
library(mlbench)
library(caret)
library(corrplot)
library(caretEnsemble)
library(rpart)
library(rattle)
setwd("~/Documents/UNCC/ITCS6162_KDD/DataProcessingandModeling")
```
Files are read from application train and merged csv files
```{r read_file, include = FALSE}
#loan.data <- read.csv(file="application_train.csv", header=TRUE, sep=",")
loan.data.all <- read.csv(file="./all/application_train_all.csv", header=TRUE, sep=",")
```
Omitting columns with large numbers of NA values
```{r omit, include = FALSE}
loan.data.all2.no.na <-na.omit(loan.data.all[ , colSums(is.na(loan.data.all)) <100])
```
##Standardize selected columns
```{r stand, include = FALSE}
out_col <- c(8,9,10,16,17,18,19,20,44)
for(i in 1:length(out_col)){
loan.data.all2.no.na[,out_col[i]] <- (loan.data.all2.no.na[,out_col[i]] - mean(loan.data.all2.no.na[,out_col[i]]))/sd(loan.data.all2.no.na[,out_col[i]])
}
```
##Outliers removing
```{r outl, include = FALSE}
for(i in 1:length(out_col)){
loan.data.all2.no.na <- loan.data.all2.no.na[!(loan.data.all2.no.na[,out_col[i]] > 3) ,]
}
```
##Saving and reading the processed files
```{r saving, include = FALSE}
#write.csv(loan.data.all2.no.na, 'all/training.all.no.na.csv', row.names=FALSE)
loan.data.all2.no.na <- read.csv(file="./all/training.all.no.na.csv", header=TRUE, sep=",")
test.data <- read.csv(file="./all/application_test.csv", header=TRUE, sep=",")
```
##Taking a random sample of size 1000
Manageable sample for testing algorithms
```{r samp, include=FALSE}
loan.data.all2.no.na <- loan.data.all2.no.na[sample(1:nrow(loan.data.all2.no.na), 1000, replace=FALSE),]
#options(warn=-1)
#suppressWarnings()
```
##Balancing the dataset and segreggating the zero targets from the 1 target samples
```{r balance, include=FALSE}
#saving the ones
target.one <- loan.data.all2.no.na[loan.data.all2.no.na$TARGET==1,]
#how many samples have target 1
sum(target.one$TARGET)
#saving zeros
target.zero <- loan.data.all2.no.na[loan.data.all2.no.na$TARGET==0,]
#how many zeros
sum(!target.zero$TARGET)
```
##Clustering zeros
Applying Scaling to numeric classes without the Target and the SK_CURR_ID
```{r scale, include=FALSE}
classes <- sapply(target.zero, class)
num.loan <- target.zero[,classes=="numeric"]
num.loan$SK_ID_CURR <- target.zero$SK_ID_CURR
num.loan$TARGET <- target.zero$TARGET
head(num.loan,1)
df <- na.omit(num.loan) #just to make sure NA omit
df2.scale<-na.omit(num.loan)
omit.columns <- c("SK_ID_CURR","TARGET")
m <- apply(df2.scale[,-which(names(df2.scale) %in% omit.columns)], 2, mean)
s <- apply(df2.scale[,-which(names(df2.scale) %in% omit.columns)], 2, sd)
#classes <- sapply(df, class)
#z<- scale(df[,classes=="numeric"], m, s)
df2.scale[,-which(names(df2.scale) %in% omit.columns)] <- lapply(df2.scale[,-which(names(df2.scale) %in% omit.columns)], function(x) c(scale(x), m, s))
z<- scale(df[,-which(names(df2.scale) %in% omit.columns)], m, s)
head(df2.scale,1)
```
##Scree Plot for k-means and selecting the number of clusters
- there are 3 obvious clusters
```{r scree}
wss <- (nrow(df2.scale[,-which(names(df2.scale) %in% omit.columns)])-1)*sum(apply(df2.scale[,-which(names(df2.scale) %in% omit.columns)],2,var))
for (i in 2:20) wss[i] <- sum(kmeans(df2.scale[,-which(names(df2.scale) %in% omit.columns)], centers=i)$withinss)
```
```{r pres, echo=FALSE}
plot(1:20, wss, type="b", xlab="Number of Clusters", ylab="Within groups sum of squares")
```
##K-means clustering
```{r k-means}
kc<-kmeans(df2.scale[,-which(names(df2.scale) %in% omit.columns)],3)
#we see that the ratio between_SS values and total_SS values is: 25.4%
str(kc)
head(kc$cluster,2)
head(kc$centers,2)
```
##Determine which Id belongs to which cluster and add this data to the df2.scale in form of cluster number:1, 2, or 3 per each id
```{r clust, include=FALSE}
out <- cbind(df2.scale, Cluster.Num = kc$cluster)
head(out,1)
```
```{r plotcreditincome, echo=FALSE}
plot(out[,c("AMT_CREDIT","Cluster.Num")])
plot(out[,"Cluster.Num"], (out[, "AMT_INCOME_TOTAL"]))
```
```{r saveclust, include=FALSE}
#there are 0 unavailable values for credit clusters since we removed the NA info at the begining
sum(is.na(out$Cluster.Num))
#there are 0 duplicate credit records
sum(duplicated(out$SK_ID_CURR))
#adding the credit cluster data to the training data too:
target.zero.wCluster <- cbind(target.zero, Cluster.Num = NA) #create column
for (row in 1:nrow(out)) {
SK_ID <- out[row, "SK_ID_CURR"]
SK_ID
#update column
target.zero.wCluster[target.zero.wCluster$SK_ID_CURR==SK_ID, "Cluster.Num"] <- out[out$SK_ID_CURR==SK_ID, "Cluster.Num"]
}
head(target.zero.wCluster)
#loan.data.all.wClusterCredit["SK_ID_CURR"==100083, "Cluster.Num"] <- out["SK_ID_CURR"==100083, "Credit.Cluster.Num"]
cluster.training.set <- na.omit(target.zero.wCluster)
sum(cluster.training.set$TARGET==1)
sum(cluster.training.set$TARGET==0)
```
```{r save_clust, include=FALSE}
#uncheck the following to save the ones and zeros
#write.csv(target.zero.wCluster, 'all/target.zero.wCluster.csv', row.names=FALSE)
#write.csv(target.one, 'all/target.one.csv', row.names=FALSE)
```
##Correlation matrix for most variables
AMT_ANNUITY/AMT_CREDIT are highly correlated
```{r correl}
# ensure the results are repeatable
set.seed(7)
# calculate correlation matrix
correlationMatrix <- cor(target.zero[,classes=="numeric"])#3:64
# summarize the correlation matrix
print(correlationMatrix)
# find attributes that are highly corrected (ideally >0.75)
highlyCorrelated <- findCorrelation(correlationMatrix, cutoff=0.5)
# print indexes of highly correlated attributes
print(highlyCorrelated) #
```
```{r correlplot, echo=FALSE}
corrplot(correlationMatrix, method=c('number'),title='correlation matrix',diag=T)
```
##Rank features by importance using the caret r packageR supervised feature selection
```{r caretrank, include=FALSE}
# prepare training scheme
loan.data.all2.no.na$TARGET<-as.factor(loan.data.all2.no.na$TARGET)
d <- loan.data.all2.no.na[,classes=="numeric" || classes=="integer" || classes=="double"]
control <- trainControl(method="repeatedcv", number=3)#, repeats=3)
# train the model
model <- train(TARGET~., data=d[,c(2:64)], method="lvq", preProcess="scale", trControl=control)
```
```{r printimport}
# estimate variable importance
importance <- varImp(model, scale=FALSE)
# summarize importance
print(importance)
```
```{r plotimportance, echo=FALSE}
# plot importance
plot(importance)
```
##Feature selection (dimensionality reduction) with PCA
```{r pca,include=FALSE}
classes <- sapply(loan.data.all2.no.na, class)
loan.data.numeric <- loan.data.all2.no.na[,classes=="numeric"]
#loan.data.complete <- complete.cases(loan.data.all[,classes=="numeric"])
loan.data.complete <- na.omit(loan.data.numeric) #!is.na(loan.data.numeric))
m.pca <- apply(loan.data.complete, 2, mean)
s.pca <- apply(loan.data.complete, 2, sd)
z.pca <- scale(loan.data.complete, m.pca, s.pca)
#we observe principal components with 26 PCs over 85% contributing to the
#variability we see in the sample
l.pca <- prcomp(z.pca)#, center = TRUE, scale. = TRUE)
```
```{r sumpca}
summary.pca <- summary(l.pca)
#head(l.pca)
#str(l.pca)
#distance <- dist(z.pca)
#str(distance)
#percentage of variance captured by PCA
pca_pr <- round(100*summary.pca$importance[2, ], digits = 1)
pca_pr
#axis labels
pc_lab <- paste0(names(pca_pr), " (", pca_pr, "%)")
pc_lab
```
##PCA biplot
```{r bipl, echo=FALSE}
biplot(l.pca, cex = c(0.8, 1), col = c("grey40", "deeppink2"), xlab = pc_lab[1], ylab = pc_lab[2])
```
##PCA with MLBench
```{r pca_mlbench}
preprocParam <- preProcess(loan.data.numeric, method=c("center", "scale", "pca"))
# summarize preprocessed
print(preprocParam)
# transform the data
tran <- predict(preprocParam, loan.data.all2.no.na)
# summarize the transformed dataset
summary(tran)
```
## Feature selection with unsupervised Multiple Correspondence Analysis (MCA)
income type occupation type contribute to overall variability
```{r mca, include=FALSE}
theme_set(theme_bw(12))
nfactors <- apply(loan.data.all2.no.na, 2, function(x) nlevels(as.factor(x)))
nfactors
head(loan.data.all2.no.na[,c(2:5)])
col.selected <- c(3:6, 11:15, 27, 31, 39:43)
loan.selected <- select(loan.data.all2.no.na, col.selected)
```
```{r mcasum}
mca <- MCA(loan.selected, graph = FALSE)
#length(loan.data.all2.no.na)
# summary of the model
summary(mca)
summary(loan.selected)
```
##Visualize the dataset
```{r plotmca, echo=FALSE}
#dev.off()
gather(loan.selected) %>% ggplot(aes(value)) + facet_wrap("key", scales = "free") + geom_bar() + theme(axis.text.x = element_text(angle = 45, hjust = 1, size = 3))
```
## Visualize MCA
```{r plotmca2, echo=FALSE}
plot.MCA(mca)
plot(mca, invisible=c("ind"), habillage = "quali", cex=0.5)
```
## Supervised feature selection with Caret
prepare training scheme
```{r caret, include=FALSE}
control <- trainControl(method="repeatedcv", number=3)#, repeats=3)
# train the model
loan.data.all2.no.na$TARGET<-as.factor(loan.data.all2.no.na$TARGET)
model <- train(TARGET~., data=loan.data.all2.no.na[,c(2:64)], method="lvq", preProcess="scale", trControl=control)#, ntree=50
# estimate variable importance
importance <- varImp(model, scale=FALSE)
```
## Summarize importance Caret feature selection
```{r imp}
print(importance)
```
## Plot importance
```{r plotimp, echo=FALSE}
#par(cex.lab=2)
#dev.off()
#plot.new()
#axis(2,cex.axis=1, cex.lab=1)
plot(importance, cex.names=0.1, cex.lab=1, cex.axis=1) #cex=1
```
##Supervised Recursive Feature Elimination (RFE)
supervised model
```{r rfe, include=FALSE}
control <- rfeControl(functions=rfFuncs, method="cv", number=3)
# run the RFE algorithm
#results <- rfe(loan.data.all2.no.na[,c(2:10)], loan.data.all2.no.na[,c(1)], sizes=c(2:10), rfeControl=control)
results <- rfe(loan.data.all2.no.na[,c(2:10)], loan.data.all2.no.na[,c(1)], sizes=c(2:10), rfeControl=control)
```
## Summarize the results
```{r resrfe}
print(results)
# list the chosen features
predictors(results)
```
## Plot the results
```{r plotrfe, echo=FALSE}
plot(results, type=c("g", "o"))
```
##Creating levels
```{r levl, include=FALSE}
#str(loan.data.all2.no.na)
#int.numerical <- loan.data.all2.no.na[, classes=='integer']
#creating factors out of the integer
for(i in 1:length(loan.data.all2.no.na)){
if(class(loan.data.all2.no.na[,i])=='integer'){
loan.data.all2.no.na[,i] <- as.factor(loan.data.all2.no.na[,i])
}
}
# creating 3 level categorical variables from numerical using
# lower, medium and upper quartile
```
##Checking the categories for each variable
```{r categ, include=FALSE}
nfactors <- apply(loan.data.all2.no.na, 2, function(x) nlevels(as.factor(x)))
nfactors
#ensure the categories per variable are at least 2
loan.data.all2.no.na <- loan.data.all2.no.na[,!(nfactors<=1)]
#ensuring the TARGET has valid category names YES and NO not 0 and 1
levels(loan.data.all2.no.na$TARGET) <- c("NO", "YES")
levels(loan.data.all2.no.na$TARGET)
```
## Stacking ensemble
```{r stack, include=FALSE}
#control <- trainControl(method="repeatedcv", number=10, repeats=3, savePredictions=TRUE, classProbs=TRUE)
control <- trainControl(method="repeatedcv", number=3, savePredictions=TRUE, classProbs=TRUE)
alg <- c('rpart', 'knn')# 'lda', 'svmRadial', 'glm'
set.seed(7)
models <- caretList(TARGET~., data=loan.data.all2.no.na[,2:4], trControl=control, methodList=alg)
r <- resamples(models)
```
```{r stackens}
summary(r)
```
```{r dotplot, echo=FALSE}
dotplot(r)
```
## Correlation stacking ensemble
```{r plotr}
modelCor(r)
splom(r)
```
## Stack using glm
```{r glm, include=FALSE}
#stackControl <- trainControl(method="repeatedcv", number=3, repeats=3, savePredictions=TRUE, classProbs=TRUE)#
#set.seed(7)
#stack.glm <- caretStack(models, method='rpart', metric="Accuracy", trControl=stackControl)
#print(stack.glm)
```
## Stack using Random Forest
```{r rf, include=FALSE}
set.seed(7)
#stack.rf <- caretStack(models, method="rf", metric="Accuracy", trControl=stackControl)
#print(stack.rf)
```
## Ensamble bagging CART and Random Forest
```{r cartr, include=FALSE}
control <- trainControl(method="repeatedcv", number=3, repeats=3)#cv
metric <- "Accuracy"
# Bagged CART
set.seed(7)
#dataset<-na.omit(cluster.training.set)
fit.treebag <- train(TARGET~., data=loan.data.all2.no.na[,1:5], method="treebag", metric=metric, trControl=control)
# Random Forest
set.seed(7)
fit.rf <- train(TARGET~., data=loan.data.all2.no.na[,1:4], method="rf", metric=metric, trControl=control, ntree=10)#100 #1:5
```
## Summarize results Bagged CART and Random Forest
```{r plotCARTrfres}
bagging_results <- resamples(list(treebag=fit.treebag, rf=fit.rf))
summary(bagging_results)
dotplot(bagging_results)
```
##Simply rpart (submitted to Kaggle)
Needs improvement and balancing of several predictors
```{r prepdatacsv, include=FALSE}
loan.data.all2.no.na <- read.csv(file="./all/training.all.no.na.csv", header=TRUE, sep=",")
table(loan.data.all2.no.na$CODE_GENDER)
value0 <- loan.data.all2.no.na[loan.data.all2.no.na$TARGET==0,]
value1 <- loan.data.all2.no.na[loan.data.all2.no.na$TARGET==1,]
value0.balance <- value0[sample(1:nrow(value0), nrow(value1),
replace=FALSE),]
data.balanced <- rbind(value0.balance,value1)
```
```{r modelrpart}
#rpart the decision tree
loan.tree <- rpart(TARGET ~ ., data = data.balanced, method = "class")
# Visualize the decision tree using plot() and text()
plot(loan.tree)
text(loan.tree)
```
```{r fancyrparplot, echo=FALSE}
fancyRpartPlot(loan.tree)#needs rattle
```
##Kaggle: - Preparing the solutions and CSV file for the submission
# Making predictions on the test set
```{r Kagglepredictions}
my_prediction <- predict(loan.tree, newdata = test.data, type = "class")
my_solution <- data.frame(SK_ID_CURR = test.data$SK_ID_CURR, TARGET = my_prediction)
nrow(my_solution)
write.csv(my_solution, file = "group5.csv", row.names = FALSE)
```
## Pifalls:
* merging data before or after feature selection/dimensionality reduction
* dealing with NA values: column wise or drop sample
* dealing with outliers for numerical variables
## Conclusion:
* The dataset presents challanges due to a large variaty of data types: numerical and categorical
* Relational tables are not easy to deal with in R
* Ensemble methods can play a crucial role in increasing the Accuracy of prediction
* Kaggle entry: Number: 5765 Team.Group5 MihMehe Shourya 0.562 with one submission rpart only
<file_sep>---
title: " Home Loan credit risk prediction: DataPreparation and Modeling"
author: "Group 5: <NAME>, <NAME>, <NAME>, <NAME>"
date: "August 1, 2018"
output:
html_document:
toc: true
---
##Including all the libraries
```{r dataload, echo=TRUE,message=FALSE}
if(!require(missForest)) install.packages("missForest",repos = "http://cran.us.r-project.org")
if(!require(VIM)) install.packages("VIM",repos = "http://cran.us.r-project.org")
if(!require(mice)) install.packages("mice",repos = "http://cran.us.r-project.org")
if(!require(corrplot)) install.packages("corrplot",repos = "http://cran.us.r-project.org")
if(!require(scales)) install.packages("scales",repos = "http://cran.us.r-project.org")
if(!require(tidyr)) install.packages("tidyr",repos = "http://cran.us.r-project.org")
library(missForest)
library(VIM)
library(ggplot2)
library(plyr)
library(e1071)
library(mice)
library(corrplot)
library(tidyr)
library(scales)
```
##Loading the datasets
```{r}
loan.data <- read.csv(file="application_train.csv", header=TRUE, sep=",")
loan.data.all <- read.csv(file="application_train_all.csv", header=TRUE, sep=",")
ccard <- read.csv(file="credit_card_balance.csv", header = TRUE, sep=",")
attach(loan.data)
attach(loan.data.all)
attach(ccard)
summary(loan.data)
source("outlierscript.R")
```
##Missing Values
```{r}
sapply(loan.data, function(x) sum(is.na(x)))
missing<- loan.data[!complete.cases(loan.data),]; head(missing)
#complete.cases(loan.data) != is.na(loan.data)
sum(table(which(loan.data == ''))) #find how many missing values are there
sum(sapply(loan.data, function(x) sum(is.na(x))))
#Using mice
mice_plot <- aggr(loan.data, col=c('navyblue','yellow'),
numbers=TRUE, sortVars=TRUE,
labels=names(loan.data), cex.axis=.7,
gap=3, ylab=c("Missing data","Pattern"))
```
##Box plot
```{r}
amt_income <- loan.data$AMT_INCOME_TOTAL
amt_credit <- loan.data$AMT_CREDIT
hist(amt_income) #histogram
hist(amt_credit)
boxplot(loan.data$AMT_INCOME_TOTAL,data=loan.data, main="Income Data",
xlab="Income", ylab="Income")
boxplot(loan.data$AMT_CREDIT,data=loan.data, main="Credit Data",
xlab="Credit", ylab="Credit")
#display amt credit
bp <- ggplot(loan.data, aes(x=AMT_CREDIT, y=AMT_INCOME_TOTAL, group=loan.data$CNT_CHILDREN)) +
geom_boxplot(fill="red", alpha=0.2) +
xlab("AMT CREDIT")+ylab("AMT INCOME")
bp <- bp + scale_x_continuous(trans='log2') +
scale_y_continuous(trans='log2')
bp
ggplot(loan.data, aes(x = as.factor(loan.data$CNT_CHILDREN), fill = CNT_CHILDREN==1, color=loan.data$AMT_INCOME_TOTAL)) +
geom_density(alpha = .3)
ggplot(loan.data[loan.data$AMT_INCOME_TOTAL<100000,], aes(x = AMT_INCOME_TOTAL/10000, fill = as.factor(CNT_CHILDREN))) +
geom_density(alpha = .3)
ggplot(loan.data, aes(x = as.factor(loan.data$CNT_CHILDREN), fill = AMT_CREDIT)) +
geom_density(alpha = .3)
ggplot(loan.data, aes(x = as.factor(loan.data$CNT_CHILDREN), fill = AMT_CREDIT)) +
geom_density(alpha = .3)
#display amt income
#using CNT Children since it has discrete integer values to deal with continuous values and separate the groups
bp <- ggplot(loan.data, aes(x="", y=AMT_CREDIT, group=loan.data$CNT_CHILDREN)) +
geom_boxplot(fill="blue", alpha=0.2) +
xlab("CNT CHILDREN")+ylab("AMT CREDIT")
bp <- bp + scale_y_continuous(trans='log2')
bp
par(mar=c(1,1,1,1))
outlierKD(loan.data, AMT_INCOME_TOTAL)
outlierKD(loan.data, AMT_CREDIT)
```
##Flag variables
flag variables for the NAME_FAMILY_STATUS categorical attribute
```{r}
loan.data$NAME_FAMILY_STATUS <- loan.data$NAME_FAMILY_STATUS > 0
#loan.data$NAME_FAMILY_STATUS
loan.data$flag_s_not_m <- 0
loan.data$flag_m <- 0
loan.data$flag_c_m <- 0
loan.data$flag_w <- 0
loan.data$flag_s <- 0
#flag family status
loan.data$flag_s_not_m[loan.data$NAME_FAMILY_STATUS == 'Single / not married'] <- 1
#check field
#loan.data$flag_s_not_m
#continue for all other fields
loan.data$flag_m[loan.data$NAME_FAMILY_STATUS == 'Married'] <- 1
#check field
#loan.data$flag_m
loan.data$flag_c_m[loan.data$NAME_FAMILY_STATUS == 'Civil Marriage'] <- 1
#check field
#loan.data$flag_c_m
loan.data$flag_w[loan.data$NAME_FAMILY_STATUS == 'Widow'] <- 1
#check field
#loan.data$flag_w
loan.data$flag_s[loan.data$NAME_FAMILY_STATUS == 'Separated'] <- 1
#check field
#loan.data$flag_s
count(loan.data, 'flag_s_not_m')
count(loan.data, 'flag_m')
count(loan.data, 'flag_c_m')
count(loan.data, 'flag_w')
count(loan.data, 'flag_s')
```
##Z-Score Standardization
```{r}
loan.data$zscore.income <- (loan.data$AMT_INCOME_TOTAL - mean(loan.data$AMT_INCOME_TOTAL))/sd(loan.data$AMT_INCOME_TOTAL)
#loan.data$zscore.income
loan.data$zscore.credit <- (loan.data$AMT_CREDIT - mean(loan.data$AMT_CREDIT))/sd(loan.data$AMT_CREDIT)
#loan.data$zscore.credit
income_skew <- (3*(mean(loan.data$AMT_INCOME_TOTAL)-median(loan.data$AMT_INCOME_TOTAL))) / sd(loan.data$AMT_INCOME_TOTAL)
income_skew
credit_skew <- (3*(mean(loan.data$AMT_CREDIT)-median(loan.data$AMT_CREDIT))) / sd(loan.data$AMT_CREDIT)
credit_skew
skewincome = loan.data$zscore.income
skewa = skewness(skewincome) #skewness fc.
skewa
skewcredit = loan.data$zscore.credit
skewa = skewness(skewcredit) #skewness fc
skewa
#Outliers using the Z-Score values
outlierKD(loan.data, zscore.income)
loan.data$zscore.credit <- (loan.data$AMT_CREDIT - mean(loan.data$AMT_CREDIT))/sd(loan.data$AMT_CREDIT)
#loan.data$zscore.credit
skewcredit = loan.data$zscore.credit
skewa = skewness(skewcredit) #skewness fc
skewa
amt_credit_sd <- sd(loan.data$AMT_CREDIT)
amt_credit_mean <- mean(loan.data$AMT_CREDIT)
amt_credit_sd
amt_credit_mean
zscore.amt_credit <- (loan.data$AMT_CREDIT - amt_credit_mean) / amt_credit_sd
#Analyze AMT_CREDIT for Outliers using the Z-Score values
outlierKD(loan.data, zscore.credit)
#Remove outliers from AMT CREDIT
clean.data <- loan.data[! (zscore.amt_credit > 3) ,]
# and use invert square, we get normal distribution
invert_sq_amt_credit = 1 / sqrt(clean.data$AMT_CREDIT)
qqnorm(invert_sq_amt_credit,
datax = TRUE,
col = "red",
ylim = c(0.0007441199, 0.004714045),
main = "Normal Q-Q Plot of Cleaned Inverted amount credit")
qqline(invert_sq_amt_credit,
col = "blue",
datax = TRUE)
```
##Binning
Use binning to discretize AMT_TOTAL_INCOME into five bins named A through E with A being the lowest and E being the highest - name the new attribute CAT_AMT_TOTAL_INCOME
```{r}
loan.data$CAT_AMT_TOTAL_INCOME[loan.data$AMT_INCOME_TOTAL > 0 & loan.data$AMT_INCOME_TOTAL <= 100000 ] <- "A"
loan.data$CAT_AMT_TOTAL_INCOME[loan.data$AMT_INCOME_TOTAL > 100000 & loan.data$AMT_INCOME_TOTAL <= 150000 ] <- "B"
loan.data$CAT_AMT_TOTAL_INCOME[loan.data$AMT_INCOME_TOTAL > 150000 & loan.data$AMT_INCOME_TOTAL <= 200000 ] <- "C"
loan.data$CAT_AMT_TOTAL_INCOME[loan.data$AMT_INCOME_TOTAL > 200000 & loan.data$AMT_INCOME_TOTAL <= 250000 ] <- "D"
loan.data$CAT_AMT_TOTAL_INCOME[loan.data$AMT_INCOME_TOTAL > 250000 ] <- "E"
```
##Use MICE to impute appropriate values for the missing values
CNT_CHILDREN (note: the actual value in each case was 0)
```{r}
# md.pattern(loan.data)
# dataframe_children <- as.data.frame(CNT_CHILDREN)
# #note maxit is low due to time for processing can be higher
# imputed_Data <- mice(loan.data, m=1, maxit = 2, method = 'cart', seed = 500)
# imputed_Data$imp$CNT_CHILDREN
# summary(imputed_Data)
# densityplot(imputed_Data)
# completedData <- complete(imputed_Data,1)
# sapply(completedData, function(x) sum(is.na(x)))
```
##Contingency table
```{r}
table(loan.data$NAME_FAMILY_STATUS,loan.data$NAME_HOUSING_TYPE)
#get a count of the n way frequency for pairs
count(loan.data,vars = c("NAME_FAMILY_STATUS","NAME_HOUSING_TYPE"))
```
##PCA
```{r}
classes <- sapply(loan.data.all, class)
loan.data.numeric <- loan.data.all[,classes=="numeric"]
#loan.data.complete <- complete.cases(loan.data.all[,classes=="numeric"])
loan.data.complete <- na.omit(loan.data.numeric) #!is.na(loan.data.numeric))
m.pca <- apply(loan.data.complete, 2, mean)
s.pca <- apply(loan.data.complete, 2, sd)
z.pca <- scale(loan.data.complete, m.pca, s.pca)
#we observe 65 principal components with 26 PCs over 85% contributing to the
#variability we see in the sample
l.pca <- prcomp(z.pca, center = TRUE, scale. = TRUE)
summary(l.pca)
head(l.pca)
str(l.pca)
distance <- dist(z.pca)
str(distance)
```
##K-means clustering
standardize numeric values
```{r}
classes <- sapply(loan.data.all, class)
num.loan <- loan.data.all[,classes=="numeric"]
num.loan$SK_ID_CURR <- loan.data.all$SK_ID_CURR
num.loan$TARGET <- loan.data.all$TARGET
head(num.loan,1)
df <- na.omit(num.loan)
df2.scale<-na.omit(num.loan)
m <- apply(df2.scale[,-c(66, 67)], 2, mean)
s <- apply(df2.scale[,-c(66, 67)], 2, sd)
#classes <- sapply(df, class)
#z<- scale(df[,classes=="numeric"], m, s)
df2.scale[,-c(66,67)] <- lapply(df2.scale[,-c(66, 67)], function(x) c(scale(x), m, s))
z<- scale(df[,-c(66, 67)], m, s)
head(df2.scale,1)
distance.euclidian <- dist(df2.scale[,-c(66,67)], method="euclidian")
str(distance.euclidian)
rand.sample.vect<-sample(1:100, 10)
#corrplot(as.matrix(distance.euclidian), is.corr = FALSE, method="color")
#identifying correlation between individual samples
round(as.matrix(distance.euclidian)[1:6, 1:6], 1)
resp.correlation <- cor(t(z), method="pearson")
distance.correlation <- as.dist(1-resp.correlation)
round(as.matrix(distance.correlation)[1:6, 1:6], 1)
# Scree Plot for k-means and selecting the number of clusters
#there are 3 obvious clusters
wss <- (nrow(df2.scale[,-c(66,67)])-1)*sum(apply(df2.scale[,-c(66,67)],2,var))
for (i in 2:20) wss[i] <- sum(kmeans(df2.scale[,-c(66,67)], centers=i)$withinss)
plot(1:20, wss, type="b", xlab="Number of Clusters", ylab="Within groups sum of squares")
# K-means clustering
kc<-kmeans(df2.scale[,-c(66,67)],3)
#we see that the ratio between_SS values and total_SS values is: 25.4%
kc
#kc$cluster
kc$centers
#Determine which Id belongs to which cluster and add this data
# to the df2.scale in form of cluster number:1, 2, or 3 per each id
out <- cbind(df2.scale, Credit.Cluster.Num = kc$cluster)
head(out,1)
plot(out[,c("AMT_CREDIT","Credit.Cluster.Num")])
plot(out[,"Credit.Cluster.Num"], (out[, "AMT_INCOME_TOTAL"]))
#there are 0 unavailable values for credit clusters since we removed the NA info at the begining
sum(is.na(out$Credit.Cluster.Num))
#there are 0 duplicate credit records
sum(duplicated(out$SK_ID_CURR))
#adding the credit cluster data to the training data too:
loan.data.all.wClusterCredit <- cbind(loan.data.all, Credit.Cluster.Num = NA) #create column
for (row in 1:nrow(out)) {
SK_ID <- out[row, "SK_ID_CURR"]
SK_ID
#update column
loan.data.all.wClusterCredit[loan.data.all.wClusterCredit$SK_ID_CURR==SK_ID, "Credit.Cluster.Num"] <- out[out$SK_ID_CURR==SK_ID, "Credit.Cluster.Num"]
}
head(loan.data.all.wClusterCredit)
#loan.data.all.wClusterCredit["SK_ID_CURR"==100083, "Credit.Cluster.Num"] <- out["SK_ID_CURR"==100083, "Credit.Cluster.Num"]
```
##Modeling Plan
As part of the modeling plan we took the following steps:
* Ran Univariate and Bivariate Statistics (Check the distributions of the variables we intend to use, as well as bivariate relationships among all variables that might go into the model)
* Dropped nonsignificant control variables
* Checked for and resolve data issues
* Checked for Multicollinearity
* Outliers and influential points
* Dealt with Missing data
* Created new flag variables for categorical variables
* We will use PCA to uncover correlations and further make decisions to include the variables in the model based on the results
* Further, we will standardize the values to avoid an increased influence from some of the variables will larger range
* We anticipate that some of our models will be greatly influence by the distribution of input variables so we will detect skew values and transform the data accordingly
* In order to identify which explanatory variables we think would be good indicators or predictors of the potential risk of a loan: likelihood of default (higher risk) versus paid in full (lower risk), we can calculate the percent of the total number of loans that are classified as defaults.
* The predictor target is given as credit risk and thus we will use a supervised approach
* Further we will use cross-validation with k=5 to prepare the data for training and testing the models
* We will employ at least two fundamentally different approaches:
1. A pipeline with logistic regression and random forest, and
2. A black box approach: RNN with logistic regression
* To create models we can use, logistic regression as the response variable (Target) follows a binomial distribution. The reasons why Logistic regression is better suited to credit risk analysis are:
+ The independent variable (NAME_CONTRACT_TYPE, AMT_INCOME, etc.) are categorical in nature. Categories make better predictors in this analysis than actual value.
+ The end result has to be in probability or percentage (like customer A is x% likely to default on the given credit), which is not possible with linear regression model since its values vary between -infinity and +infinity.
* For model selection, we can select the model with the least residual error. We can use different cut offs to decide if a loan should be granted or not.
* RNN: we will construct a neural network with an input layer of dimension N = number of input variables and 1 hidden layer and a single output neuron corresponding to the output classifier variable for 2 outcomes: Yes=1 credit risk and No=0 credit risk.
* We will monitor the ROC for the performance of our models
* We will compare the accuracy of classification between the RNN approach and random forest approach and determine the advantages and disadvantages for using either one or the other
* We will also construct a decision tree based on the given inputs that can streamline the decision process of approving/ declining credit to a particular customer.
|
25a47a477b34eac221f6fdc75f91336846d27e1e
|
[
"R",
"RMarkdown"
] | 4
|
R
|
mmehedin/Project-KDD-6162
|
0ded8d9e8d4279502ae28905db4f5fb05af3ab68
|
d52fb4ca1879afb03a0f7310bebdaed5b5e69449
|
refs/heads/master
|
<repo_name>peterelsayeh/ccr<file_sep>/index.php
<html>
<<<<<<< HEAD
=======
<head>
<link rel="stylesheet" type="text/css" href="/css/style.css" />
</head>
>>>>>>> 240ea17... adding css2
<body>
<?php
echo "Written using PHP! Hepp!";
# read the credentials file
$string = file_get_contents($_ENV['CRED_FILE'], false);
if ($string == false) {
die('FATAL: Could not read credentials file');
}
# the file contains a JSON string, decode it and return an associative array
$creds = json_decode($string, true);
# use credentials to set the configuration for your Add-on
# replace ADDON_NAME and PARAMETER with Add-on specific values
$config = array(
'hostname' => $creds['MYSQLS']['MYSQLS_HOSTNAME'],
'password' => $<PASSWORD>['<PASSWORD>']['<PASSWORD>'],
'username' => $creds['MYSQLS']['MYSQLS_USERNAME'],
'db' => $creds['MYSQLS']['MYSQLS_DATABASE'],
);
$con = mysql_connect($config['hostname'],$config['username'],$config['password']);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db($config['db'], $con);
mysql_query("INSERT INTO logic_table (email, score) VALUES ('hejAThejsan.com', 12)");
mysql_close($con);
?>
</body>
</html>
|
992628591e34e8823c9a3bfc5a241153b7e3de7a
|
[
"PHP"
] | 1
|
PHP
|
peterelsayeh/ccr
|
f4815103af94b15a7ad67b2337be72251feecba9
|
721d7f91d8178160352c653322d78deed17ac7b5
|
refs/heads/master
|
<repo_name>bombazook/meander<file_sep>/spec/spec_helper.rb
require 'bundler/setup'
require 'simplecov'
SimpleCov.start do
add_filter "/spec/"
end
require 'meander'
require 'byebug'
Dir[File.join(__dir__, 'shared/**/*.rb')].each { |entry| require entry }
RSpec.configure do |config|
# Enable flags like --only-failures and --next-failure
config.example_status_persistence_file_path = '.rspec_status'
config.expect_with :rspec do |c|
c.syntax = :expect
end
config.order = 'random'
end
<file_sep>/lib/meander/plain.rb
# frozen_string_literal: true
require 'thor/core_ext/hash_with_indifferent_access'
require_relative 'common_methods'
module Meander
##
# == Brief
# This class is a sugar filled version of HashWithIndifferentAccess
#
# It supports key-based method_name calling and value block evaluation
# == Configuration
# You can set class that will be applied to newly assigned values
# require 'active_support/core_ext/hash'
# class MyClass < Meander::Plain
# cover_class = HashWithIndifferentAccess
# end
#
# m = MyClass.new
# m[:a] = {}
# m[:a].class # => ActiveSupport::HashWithIndifferentAccess
# == Usage
# === Key based method_name evaluation
# m = Meander::Plain.new({:a => 1})
# m.a # => 1
# === New value assignment
# n = Meander::Plain.new
# n.a = 1
# n.a # => 1
# === Block values evaluation
# k = Meander::Plain.new({config: nil})
# k.config do |k|
# k.path = "some_config_path.yml"
# end
# k.config.path # => "some_config_path.yml"
class Plain < ::Thor::CoreExt::HashWithIndifferentAccess
include CommonMethods
def initialize(val = {})
val ||= {}
super(val)
end
def []=(key, value)
if value.is_a?(Hash) && !value.is_a?(self.class.cover_class)
super(key, self.class.cover_class.new(value))
else
super
end
end
def method_missing(method_name, *args, &block)
method_name = method_name.to_s
if new_key_method? method_name
key_name = method_name.gsub(/=$/, '')
send :[]=, key_name, *args, &block
elsif block_given?
val = self[method_name]
val = {} unless self.class.hash_or_cover_class?(val)
send :[]=, method_name, val
yield(self[method_name])
elsif key?(method_name)
self[method_name]
else
super
end
end
def respond_to_missing?(method_name, include_private = false)
new_key_method?(method_name) || key?(method_name) || super
end
end
end
<file_sep>/spec/meander/plain_spec.rb
require 'spec_helper'
RSpec.describe Meander::Plain do
it_behaves_like 'common meander'
end
<file_sep>/lib/meander.rb
# frozen_string_literal: true
require_relative 'meander/version'
require_relative 'meander/common_methods'
require_relative 'meander/plain'
require_relative 'meander/mutable'
module Meander # :nodoc:
end
<file_sep>/spec/shared/common_meander.rb
RSpec.shared_examples 'common meander' do
let(:original_hash) { { x: 1 } }
let(:original_config) { described_class.new(original_hash) }
let(:config_copy) { described_class.new(original_config) }
describe '#merge!' do
it 'doesnt change original hash values' do
config_copy.merge! :x => 2, 'test' => 3
expect(original_config[:x]).to be_eql(1)
end
it 'doesnt set new values to original hash' do
config_copy.merge! :x => 2, 'test' => 3
expect(original_config['test']).to be_nil
end
end
describe '#[]= and #[]' do
it 'doesnt change original hash values' do
config_copy['test'] = 2
config_copy[:x] = 3
expect(original_config[:x]).to be_eql(1)
end
it 'doesnt set new values to original hash' do
config_copy['test'] = 2
config_copy[:x] = 3
expect(original_config['test']).to be_nil
end
it 'covers child hash by cover_class' do
config_copy[:x] = { z: 1 }
expect(config_copy[:x]).to be_kind_of(config_copy.class.cover_class)
end
it 'behaves like hash_with_indifferent_access' do
expect(original_config['x']).to be(1)
end
it 'allows not string nor symbol keys' do
original_hash[1] = 1
expect { original_config[1] }.not_to raise_exception
end
context 'true-false values' do
let(:original_hash) { { x: true } }
it 'changes value even if it doesnt true in boolean expression' do
config_copy[:x] = false
expect(config_copy.x).to be_eql(false)
end
end
end
describe '#initialize' do
context 'without arguments' do
let(:original_config) { described_class.new }
it 'creates object with empty keys list' do
expect(original_config.keys).to be_empty
end
end
context 'nil argument' do
let(:original_hash) { nil }
let(:original_config) { described_class.new(original_hash) }
it 'creates object with empty keys list' do
expect(original_config.keys).to be_empty
end
end
end
describe '#method_missing' do
it 'doesnt change original hash values' do
config_copy.x = 2
config_copy.y = 1
expect(original_config[:x]).to be_eql(1)
end
it 'doesnt set new values to original hash' do
config_copy.x = 2
config_copy.y = 1
expect(original_config[:y]).to be_nil
end
it 'allows to access key value by method' do
expect(original_config.x).to be_eql 1
end
it 'doesnt create method with _some_name_= key' do
original_config[:z=] = 3
original_config.z = 4
expect(original_config.z).to be_eql(4)
end
it 'creates new value if block given' do
original_config.z { |z| z.x = 1 }
expect(original_config.z.x).to be_eql 1
end
it 'calls original method_missing if no values set' do
expect(original_config).to receive(:[])
original_config.non_exist
end
context 'original key already has some value' do
it 'overrides this value' do
original_config.x { |x| x.x = 1 }
expect(original_config.x.x).to be_eql 1
end
end
end
describe '#key?' do
it 'true if value was changed' do
config_copy.y = 2
expect(config_copy.key?(:y)).to be_eql true
end
it 'true if original hash has this value' do
config_copy.y = 2
expect(config_copy.key?(:x)).to be_eql true
end
it 'false if no such key in exact hash or original one' do
config_copy.y = 2
expect(config_copy.key?(:z)).to be_eql false
end
context 'different type keys' do
let(:original_hash) { { :x => 1, 'y' => 2 } }
it 'true if original one had symbol key but argument is string' do
expect(original_config.key?('x')).to be_eql true
end
it 'true if original one had string key but argument is symbol' do
expect(original_config.key?(:y)).to be_eql true
end
end
end
describe '#keys' do
it 'converts to_s keys of both current and super hash' do
original_config[:y] = 2
expect(original_config.keys).to include('x', 'y')
end
end
end
<file_sep>/lib/meander/version.rb
# frozen_string_literal: true
module Meander
VERSION = '0.2'
end
<file_sep>/spec/shared/deep_merge_support.rb
shared_examples 'support deep_merge' do
let(:original_hash) { { x: { y: { z: 1 } } } }
shared_examples 'common deep_merge' do
it 'adds new key to subhash' do
expect(merged_config.x.y.yo).to be_eql(2)
end
it 'keeps original key in subhash' do
expect(merged_config.x.y.z).to be_eql(1)
end
it 'makes subhash covered with described class' do
expect(merged_config.x.y).to be_instance_of(described_class)
end
it 'keeps merged_config mutable' do
merged_config
original_hash[:p] = 1
expect(merged_config.p).to be_eql(1)
end
end
context 'external merge' do
let(:merged_config) { original_config.deep_merge(x: { y: { yo: 2 } }) }
it_behaves_like 'common deep_merge'
end
context 'internal merge' do
let(:merged_config) { original_config.deep_merge!(x: { y: { yo: 2 } }) }
it_behaves_like 'common deep_merge'
end
context 'altered keys support' do
let(:original_hash) { {} }
let(:merging_config) do
config = described_class.new(a: 1)
config.b = 2
config
end
let(:merged_config) { original_config.deep_merge(merging_config) }
it 'adds both own keys and original keys under deep_merge' do
expect(merged_config.keys).to include('a', 'b')
end
end
context 'empty original config' do
let(:original_hash) { {} }
it 'does not alter original_hash' do
original_config.deep_merge(some: :hash)
expect(original_config.keys).to be_empty
end
end
end
<file_sep>/README.md
# Meander
[](https://travis-ci.org/bombazook/meander)
[](https://badge.fury.io/rb/meander)
## WAT
Just another ruby Hash extension
Hashie clone with a bit more sugar
Best for configuration storage
Natively supports:
- default values
- key-based accessor methods
- block-based dsl-like value access
- stores updates in separate hash
- performs well with Hashie deep_merge extension
## Usage
[Meander::Plain](http://www.rubydoc.info/gems/meander/Meander/Plain)
[Meander::Mutable](http://www.rubydoc.info/gems/meander/Meander/Mutable)
## License
The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
<file_sep>/spec/meander/hashie_deep_merge_support_spec.rb
require 'spec_helper'
require 'hashie'
class HashieDeepMergeSupport < Meander::Mutable
include ::Hashie::Extensions::DeepMerge
end
RSpec.describe HashieDeepMergeSupport do
it_behaves_like 'common meander' do
it_behaves_like 'mutable meander' do
it_behaves_like 'support deep_merge'
end
end
end
<file_sep>/lib/meander/common_methods.rb
# frozen_string_literal: true
module Meander
module CommonMethods # :nodoc:
module ClassMethods # :nodoc:
def hash_or_cover_class?(value)
value.is_a?(Hash) || value.is_a?(cover_class)
end
end
def self.included(base)
base.extend ClassMethods
class << base
attr_writer :cover_class
def cover_class
@cover_class ||= self
end
end
end
private
def new_key_method?(method_name)
/=$/.match?(method_name)
end
end
end
<file_sep>/lib/meander/mutable.rb
# frozen_string_literal: true
require_relative 'plain'
require 'delegate'
require 'forwardable'
module Meander
##
# This class is a mutable version of Meander::Plain
#
# All keys you alter will be keep up to date if dependend objects updated
# == Usage
# === Nesting value updates
# a = {}
# m = Meander::Mutable.new(a)
# a['key'] = 1
# m.key # => 1
# === Value overloading
# a = {}
# m = Meander::Mutable.new(a)
# m.key = 1
# m.key # => 1
# a # => {}
# === Deep value overloading
# a = {a: {b: {c: 1}}}
# m = Meander::Mutable.new(a)
# m.a.b.merge!({d: 2})
# m.a.b.c # => 1
# m.a.b.d # => 2
# a # => {a: {b: {c: 1}}}
# a[:a][:b][:c] = 3
# m.a.b.c # => 3
# ==== Notice
# Meander::Mutable support multiple object references
# a = {a: 1}
# m = Meander::Mutable.new(a)
# b = {b: 2}
# m.merge!(b)
# a[:a] = 3
# b[:b] = 4
# m.a # => 3 # Value is up to date
# m.b # => 4 # This value is also up to date
# You can also initialize Meander::Mutable with multiple nested hashes
# a = {a: 1}
# b = {b: 2}
# m = Meander::Mutable.new(a, b)
# a[:a] = 3
# b[:b] = 4
# m.a # => 3 # Value is up to date
# m.b # => 4 # This value is also up to date
class Mutable < ::Thor::CoreExt::HashWithIndifferentAccess
include CommonMethods
include Enumerable
def self.own_keys_cover_class
klass = self
@own_keys_cover_class ||= Class.new(Plain) do
self.cover_class = klass
end
end
def initialize(required = {}, *args)
__setobj__(required, *args)
@own_keys = self.class.own_keys_cover_class.new
end
def __getobj__
@delegate
end
def __setobj__(*args)
@delegate = []
@delegate += args
@delegate
end
def merge!(hsh)
@delegate ||= []
@delegate.unshift hsh
end
def key?(key)
@own_keys.key?(key) || delegated_key?(key)
end
def dup
self.class.new(*__getobj__)
end
def each(*args, &block)
return enum_for(:each) unless block_given?
deep_call.each { |i| i.each(*args, &block) }
end
def keys
map { |k, _| convert_key(k) }
end
def [](key)
val = nil
if @own_keys.key? key
val = @own_keys[key]
else
val = get_delegated_value(key)
if val.is_a?(Hash)
val = self.class.new(val)
self[key] = val
end
end
val
end
def respond_to_missing?(method_name, include_private = false)
@own_keys.respond_to?(method_name) || delegated_key?(method_name) || super
end
def method_missing(method_name, *args, &block)
if @own_keys.respond_to?(method_name) || block_given?
@own_keys.send method_name, *args, &block
elsif delegated_key?(method_name)
self[method_name]
else
super
end
end
def kind_of?(klass)
(self.class.cover_class == klass) || __getobj__.all?(klass)
end
alias is_a? kind_of?
extend Forwardable
def_delegators :@own_keys, :[]=
private
def deep_call(origin: self)
stack = []
if origin.is_a?(Array)
stack.unshift(*origin)
origin = stack.pop
end
Enumerator.new do |yielder|
while origin
own_keys = origin.instance_variable_get(:@own_keys)
if own_keys
yielder.yield own_keys
stack.unshift(*origin.__getobj__)
origin = stack.pop
else
yielder.yield origin
origin = stack.empty? ? nil : stack.pop
end
end
self
end
end
def delegated_key?(key)
key = convert_key(key)
deep_call(origin: __getobj__).any? do |i|
i.keys.any? { |k| convert_key(k) == key }
end
end
def get_delegated_value(key)
value = nil
key = convert_key(key)
deep_call(origin: __getobj__).detect do |i|
i.keys.any? { |k| convert_key(k) == key && value = i[k] }
end
value
end
end
end
<file_sep>/spec/meander/mutable_spec.rb
require 'spec_helper'
RSpec.describe Meander::Mutable do
context "single target" do
include_examples 'common meander'
include_examples 'mutable meander'
end
context 'multiple targets' do
include_examples 'common meander' do
let(:second_hash) { { second_target: 1 } }
let(:original_config) { described_class.new(original_hash, second_hash) }
include_examples 'mutable meander'
it "has second target set" do
expect(original_config).to respond_to(:second_target)
end
it "support multiple mutable targets" do
original_hash[:x] = 2
second_hash[:second_target] = 3
expect(original_config.x).to be_eql(2)
expect(original_config.second_target).to be_eql(3)
end
end
end
end
<file_sep>/spec/shared/mutable_meander.rb
shared_examples 'mutable meander' do
describe '#[]= and #[]' do
it 'changes higher level hash response if original one changed' do
original_config
original_hash[:x] = 2
expect(original_config[:x]).to be_eql 2
end
context 'nested hash object' do
let(:original_hash) { { x: {} } }
it 'makes new object cover after underlying key assignment' do
subhash = { y: 2 }
original_config[:x][:y] = subhash
subhash[:z] = 3
expect(original_config[:x][:y][:z]).to be_eql(3)
end
it 'covers new object after second level underlying key assignment' do
subhash = { y: 2 }
subhash2 = { f: 4 }
original_config[:x][:y] = subhash
subhash[:z] = 3
original_config[:x][:y][:z] = subhash2
expect(original_config[:x][:y][:z][:f]).to be_eql(4)
end
end
end
describe '#method_missing' do
context 'nested hash object' do
let(:original_hash) { { x: {} } }
it 'makes new object cover after underlying key assignment' do
subhash = { y: 2 }
original_config.x.y = subhash
subhash[:z] = 3
expect(original_config.x.y.z).to be_eql(3)
end
it 'covers new object after second level underlying key assignment' do
subhash = { y: 2 }
subhash2 = { f: 4 }
original_config.x.y = subhash
subhash[:z] = 3
original_config.x.y.z = subhash2
expect(original_config.x.y.z.f).to be_eql(4)
end
end
end
context 'nested hash' do
let(:original_hash) { { x: { y: 1 } } }
it 'creates higher level hash if accessing key not declared' do
config_copy[:x][:y] = 2
expect(original_config[:x][:y]).to be_eql(1)
end
end
describe '.some_key=' do
it 'does not break [] with false value' do
original_config.y = false
config_copy[:y] = true
expect(config_copy[:y]).to be_eql(true)
end
it 'does not break method_missing with false value' do
original_config.y = false
config_copy[:y] = true
expect(config_copy.y).to be_eql(true)
end
end
end
|
9b43e56c3db233a3a4531a504911fab89f473a38
|
[
"Markdown",
"Ruby"
] | 13
|
Ruby
|
bombazook/meander
|
3352ca3d4cceb8672f917dd1ae6c458bf551183a
|
321e553448ceabd805d36ac6637016a6f4c0f1d5
|
refs/heads/master
|
<repo_name>cobr123/VirtaMarketAnalyzer<file_sep>/src/main/java/ru/VirtaMarketAnalyzer/data/ServiceAtCity.java
package ru.VirtaMarketAnalyzer.data;
import com.google.gson.annotations.SerializedName;
import java.util.Map;
/**
* Created by cobr123 on 25.02.16.
*/
public final class ServiceAtCity {
@SerializedName("ci")
final private String countryId;
@SerializedName("ri")
final private String regionId;
@SerializedName("ti")
final private String townId;
@SerializedName("v")
final private long volume;
@SerializedName("p")
final private double price;
@SerializedName("sc")
final private int subdivisionsCnt;
@SerializedName("cc")
final private long companiesCnt;
@SerializedName("mdi")
final private double marketDevelopmentIndex;
@SerializedName("pbs")
final private Map<String, Double> percentBySpec;
/*spec, prodictID, stats*/
@SerializedName("rbs")
final private Map<String, Map<String, ServiceSpecRetail>> retailBySpec;
/*spec, prodictID, stats calc*/
@SerializedName("cbs")
final private Map<String, ServiceSpecRetail> retailCalcBySpec;
@SerializedName("wi")
final private double wealthIndex;
@SerializedName("itr")
final private double incomeTaxRate;
@SerializedName("ar")
final private double areaRent;
public ServiceAtCity(final String countryId, final String regionId, final String townId,
final long volume, final double price, final int subdivisionsCnt, final long companiesCnt,
final double marketDevelopmentIndex, final Map<String, Double> percentBySpec,
final double wealthIndex, final double incomeTaxRate,
final Map<String, Map<String, ServiceSpecRetail>> retailBySpec,
final Map<String, ServiceSpecRetail> retailCalcBySpec,
final double areaRent
) {
this.countryId = countryId;
this.regionId = regionId;
this.townId = townId;
this.volume = volume;
this.price = price;
this.subdivisionsCnt = subdivisionsCnt;
this.companiesCnt = companiesCnt;
this.marketDevelopmentIndex = marketDevelopmentIndex;
this.percentBySpec = percentBySpec;
this.wealthIndex = wealthIndex;
this.incomeTaxRate = incomeTaxRate;
this.retailBySpec = retailBySpec;
this.retailCalcBySpec = retailCalcBySpec;
this.areaRent = areaRent;
}
public String getCountryId() {
return countryId;
}
public String getRegionId() {
return regionId;
}
public String getTownId() {
return townId;
}
public long getVolume() {
return volume;
}
public double getPrice() {
return price;
}
public int getSubdivisionsCnt() {
return subdivisionsCnt;
}
public long getCompaniesCnt() {
return companiesCnt;
}
public double getMarketDevelopmentIndex() {
return marketDevelopmentIndex;
}
public Map<String, Double> getPercentBySpec() {
return percentBySpec;
}
public double getWealthIndex() {
return wealthIndex;
}
public double getIncomeTaxRate() {
return incomeTaxRate;
}
public Map<String, Map<String, ServiceSpecRetail>> getRetailBySpec() {
return retailBySpec;
}
public Map<String, ServiceSpecRetail> getRetailCalcBySpec() {
return retailCalcBySpec;
}
public double getAreaRent() {
return areaRent;
}
}
<file_sep>/src/main/java/ru/VirtaMarketAnalyzer/parser/ManufactureListParser.java
package ru.VirtaMarketAnalyzer.parser;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.VirtaMarketAnalyzer.data.Manufacture;
import ru.VirtaMarketAnalyzer.data.ManufactureSize;
import ru.VirtaMarketAnalyzer.main.Wizard;
import ru.VirtaMarketAnalyzer.scrapper.Downloader;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
/**
* Created by cobr123 on 18.05.2015.
*/
final public class ManufactureListParser {
private static final Logger logger = LoggerFactory.getLogger(ManufactureListParser.class);
public static Manufacture getManufacture(final String host, final String realm, final String id) throws IOException {
final Optional<Manufacture> opt = getManufactures(host, realm).stream()
.filter(v -> v.getId().equals(id)).findFirst();
if (!opt.isPresent()) {
throw new IllegalArgumentException("Не найдено производство с id '" + id + "'");
}
return opt.get();
}
public static List<Manufacture> getManufactures(final String host, final String realm) throws IOException {
final String lang = (Wizard.host.equals(host) ? "ru" : "en");
final String url = host + "api/" + realm + "/main/unittype/browse?lang=" + lang;
final List<Manufacture> list = new ArrayList<>();
try {
final String json = Downloader.getJson(url);
final Gson gson = new Gson();
final Type mapType = new TypeToken<Map<String, Map<String, Object>>>() {
}.getType();
final Map<String, Map<String, Object>> mapOfUnitTypes = gson.fromJson(json, mapType);
for (final Map.Entry<String, Map<String, Object>> entry : mapOfUnitTypes.entrySet()) {
final Map<String, Object> unitType = entry.getValue();
final String id = unitType.get("id").toString();
final String caption = unitType.get("name").toString();
final String manufactureCategory = unitType.get("industry_name").toString();
final int workplacesCount = Integer.parseInt(unitType.get("labor_max").toString());
final int maxEquipment = Integer.parseInt(unitType.get("equipment_max").toString());
final int buildingDurationWeeks = Integer.parseInt(unitType.get("building_time").toString());
final List<ManufactureSize> sizes = new ArrayList<>();
sizes.add(new ManufactureSize(workplacesCount, maxEquipment, buildingDurationWeeks));
list.add(new Manufacture(id, manufactureCategory, caption, sizes));
}
} catch (final Exception e) {
logger.error(url + "&format=debug");
throw e;
}
return list;
}
}<file_sep>/src/main/java/ru/VirtaMarketAnalyzer/data/TechReport.java
package ru.VirtaMarketAnalyzer.data;
import com.google.gson.annotations.SerializedName;
/**
* Created by cobr123 on 05.05.2017.
*/
final public class TechReport {
@SerializedName("unit_type_id")
final private String unitTypeID;
@SerializedName("unit_type_symbol")
final private String unitTypeSymbol;
@SerializedName("unit_type_name")
final private String unitTypeName;
@SerializedName("level")
final private int level;
@SerializedName("price")
final private double price;
@SerializedName("status")
final private int status;
public TechReport(
final String unitTypeID
, final String unitTypeSymbol
, final String unitTypeName
, final int level
, final double price
, final int status
) {
this.unitTypeID = unitTypeID;
this.unitTypeSymbol = unitTypeSymbol;
this.unitTypeName = unitTypeName;
this.level = level;
this.price = price;
this.status = status;
}
public String getUnitTypeID() {
return unitTypeID;
}
public String getUnitTypeSymbol() {
return unitTypeSymbol;
}
public String getUnitTypeName() {
return unitTypeName;
}
public int getLevel() {
return level;
}
public double getPrice() {
return price;
}
public int getStatus() {
return status;
}
}
<file_sep>/src/main/java/ru/VirtaMarketAnalyzer/parser/ServiceAtCityParser.java
package ru.VirtaMarketAnalyzer.parser;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.VirtaMarketAnalyzer.data.*;
import ru.VirtaMarketAnalyzer.main.Utils;
import ru.VirtaMarketAnalyzer.main.Wizard;
import ru.VirtaMarketAnalyzer.scrapper.Downloader;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.*;
import java.util.stream.Collectors;
/**
* Created by cobr123 on 26.02.16.
*/
public final class ServiceAtCityParser {
private static final Logger logger = LoggerFactory.getLogger(ServiceAtCityParser.class);
private static ServiceSpecRetail addRetailStatByProduct(final String host, final String realm, final String productID, final City city) {
try {
final TradeAtCity tac = CityParser.get(Wizard.host, realm, city, ProductInitParser.getTradingProduct(host, realm, productID)).build();
return new ServiceSpecRetail(tac.getLocalPrice(), tac.getLocalQuality(), tac.getShopPrice(), tac.getShopQuality());
} catch (final Exception e) {
logger.error("Ошибка: ", e);
}
return null;
}
private static Map<String, ServiceSpecRetail> getRetailStat(final String host, final String realm
, final UnitTypeSpec spec
, final City city
, final Set<String> tradingProductsId
) {
final Map<String, ServiceSpecRetail> stat = new HashMap<>();
if (tradingProductsId.contains(spec.getEquipment().getId())) {
stat.put(spec.getEquipment().getId(), addRetailStatByProduct(host, realm, spec.getEquipment().getId(), city));
}
spec.getRawMaterials()
.stream()
.forEach(mat -> {
if (tradingProductsId.contains(mat.getId())) {
stat.put(mat.getId(), addRetailStatByProduct(host, realm, mat.getId(), city));
} else {
//на реалме fast в рознице нет товара 'Прохладительные напитки', а в расходниках сервиса есть
stat.put(mat.getId(), new ServiceSpecRetail(0, 0, 0, 0));
// logger.error("tradingProductsId не содержит id '" + mat.getId() + "', realm = " + realm);
}
});
return stat;
}
private static ServiceSpecRetail calcBySpec(final String realm, final UnitTypeSpec spec, final Map<String, ServiceSpecRetail> stat) {
try {
// logger.info("spec.getRawMaterials().size() = {}", spec.getRawMaterials().size());
// logger.info("stat.containsKey(spec.getEquipment()) = {}", stat.containsKey(spec.getEquipment().getId()));
if (spec.getRawMaterials().size() > 0) {
final double localPrice = spec.getRawMaterials()
.stream()
.mapToDouble(mat -> stat.get(mat.getId()).getLocalPrice() * mat.getQuantity())
.sum();
final double localQuality = spec.getRawMaterials()
.stream()
.mapToDouble(mat -> stat.get(mat.getId()).getLocalQuality())
.average().orElse(0);
final double shopPrice = spec.getRawMaterials()
.stream()
.mapToDouble(mat -> stat.get(mat.getId()).getShopPrice() * mat.getQuantity())
.sum();
final double shopQuality = spec.getRawMaterials()
.stream()
.mapToDouble(mat -> stat.get(mat.getId()).getShopQuality())
.average().orElse(0);
return new ServiceSpecRetail(localPrice, localQuality, shopPrice, shopQuality);
} else if (stat.containsKey(spec.getEquipment().getId())) {
final ServiceSpecRetail serviceSpecRetail = stat.get(spec.getEquipment().getId());
final double localPrice = serviceSpecRetail.getLocalPrice();
final double localQuality = serviceSpecRetail.getLocalQuality();
final double shopPrice = serviceSpecRetail.getShopPrice();
final double shopQuality = serviceSpecRetail.getShopQuality();
return new ServiceSpecRetail(localPrice, localQuality, shopPrice, shopQuality);
}
} catch (final Exception e) {
logger.error("stat.size() = " + stat.size());
for (final RawMaterial mat : spec.getRawMaterials()) {
logger.error("('" + mat.getCaption() + "', stat.containsKey('" + mat.getId() + "') = " + stat.containsKey(mat.getId()));
}
logger.error("spec.getCaption() = " + spec.getCaption() + ", spec.getRawMaterials().size() = " + spec.getRawMaterials().size() + ", realm = " + realm, e);
}
return new ServiceSpecRetail(0, 0, 0, 0);
}
public static ServiceAtCity get(
final String host
, final String realm
, final City city
, final UnitType service
, final List<Region> regions
, final Set<String> tradingProductsId
, final List<RentAtCity> rents
) throws IOException {
final ServiceMetrics serviceMetrics = getServiceMetrics(host, realm, city, service);
final Map<String, Double> percentBySpec = getPercentBySpec(host, realm, city, service);
final double incomeTaxRate = (regions == null) ? 0 : regions.stream().filter(r -> r.getId().equals(city.getRegionId())).findFirst().get().getIncomeTaxRate();
final Map<String, Map<String, ServiceSpecRetail>> retailBySpec = new HashMap<>();
final Map<String, ServiceSpecRetail> retailCalcBySpec = new HashMap<>();
service.getSpecializations().forEach(spec -> {
final Map<String, ServiceSpecRetail> stat = getRetailStat(host, realm, spec, city, tradingProductsId);
retailCalcBySpec.put(spec.getCaption(), calcBySpec(realm, spec, stat));
//в retailBySpec только расходники, оборудование не включаем
stat.remove(spec.getEquipment().getId());
retailBySpec.put(spec.getCaption(), stat);
});
final double areaRent = rents.stream()
.filter(r -> r.getCityId().equalsIgnoreCase(city.getId()))
.filter(r -> r.getUnitTypeImgSrc().equalsIgnoreCase(service.getUnitTypeImgSrc()))
.findAny()
.get()
.getAreaRent();
return new ServiceAtCity(city.getCountryId()
, city.getRegionId()
, city.getId()
, serviceMetrics.getSales()
, serviceMetrics.getPrice()
, serviceMetrics.getUnitCount()
, serviceMetrics.getCompanyCount()
, Utils.round2(serviceMetrics.getRevenuePerRetail() * 100.0)
, percentBySpec
, city.getWealthIndex()
, incomeTaxRate
, retailBySpec
, retailCalcBySpec
, areaRent
);
}
public static List<ServiceAtCity> get(
final String host
, final String realm
, final List<City> cities
, final UnitType service
, final List<Region> regions
, final List<RentAtCity> rents
) throws IOException {
//получаем список доступных розничных товаров
final Set<String> tradingProductsId = ProductInitParser.getTradingProducts(host, realm).stream().map(Product::getId).collect(Collectors.toSet());
return cities.parallelStream().map(city -> {
try {
return get(host, realm, city, service, regions, tradingProductsId, rents);
} catch (final Exception e) {
logger.error(e.getLocalizedMessage(), e);
}
return null;
})
.filter(Objects::nonNull)
.collect(Collectors.toList());
}
private static ServiceMetrics getServiceMetrics(final String host, final String realm, final City city, final UnitType service) throws IOException {
//TODO: &produce_id=422835
final String url = host + "api/" + realm + "/main/marketing/report/service/metrics?geo=" + city.getGeo() + "&unit_type_id=" + service.getId();
try {
final String json = Downloader.getJson(url);
if ("false".equalsIgnoreCase(json)) {
// если запрос возвращает false значит не было продаж в этом городе в этот ход
return new ServiceMetrics("", 0, 0, 0, 0, 0, "", "", "");
}
final Gson gson = new Gson();
final Type mapType = new TypeToken<Map<String, Object>>() {
}.getType();
final Map<String, Object> mapOfMetrics = gson.fromJson(json, mapType);
final String name = mapOfMetrics.get("name").toString();
final String symbol = mapOfMetrics.get("symbol").toString();
final String specialization = mapOfMetrics.get("specialization").toString();
if (mapOfMetrics.get("turn_id") == null) {
logger.trace("Не найден turn_id. {}&format=debug", url);
logger.trace("{}{}/main/globalreport/marketing?geo={}&unit_type_id={}#by-service", host, realm, city.getGeo(), service.getId());
return new ServiceMetrics("", 0, 0, 0, 0, 0, name, symbol, specialization);
} else {
final String turnId = mapOfMetrics.get("turn_id").toString();
final double price = Double.parseDouble(mapOfMetrics.get("price").toString());
final long sales = Long.parseLong(mapOfMetrics.get("sales").toString());
final int unitCount = Integer.parseInt(mapOfMetrics.get("unit_count").toString());
final int companyCount = Integer.parseInt(mapOfMetrics.get("company_count").toString());
final double revenuePerRetail = Double.parseDouble(mapOfMetrics.get("revenue_per_retail").toString());
return new ServiceMetrics(turnId, price, sales, unitCount, companyCount, revenuePerRetail, name, symbol, specialization);
}
} catch (final Exception e) {
logger.error(url + "&format=debug");
throw e;
}
}
private static Map<String, Double> getPercentBySpec(final String host, final String realm, final City city, final UnitType service) throws IOException {
final Map<String, Double> percentBySpec = new HashMap<>();
//TODO: &produce_id=422835
final String url = host + "api/" + realm + "/main/marketing/report/service/specializations?geo=" + city.getGeo() + "&unit_type_id=" + service.getId();
try {
final String json = Downloader.getJson(url);
final Gson gson = new Gson();
final Type mapType = new TypeToken<Map<String, Map<String, Object>>>() {
}.getType();
final Map<String, Map<String, Object>> mapOfMetrics = gson.fromJson(json, mapType);
for (final Map.Entry<String, Map<String, Object>> entry : mapOfMetrics.entrySet()) {
final Map<String, Object> metrics = entry.getValue();
final String caption = metrics.get("name").toString();
final double marketPerc = Double.parseDouble(metrics.get("market_size").toString());
percentBySpec.put(caption, marketPerc);
}
} catch (final Exception e) {
logger.error(url + "&format=debug");
throw e;
}
return percentBySpec;
}
}
<file_sep>/src/main/java/ru/VirtaMarketAnalyzer/data/City.java
package ru.VirtaMarketAnalyzer.data;
import com.google.gson.annotations.SerializedName;
import java.util.List;
/**
* Created by cobr123 on 25.04.2015.
*/
public final class City {
@SerializedName("ci")
final private String countryId;
@SerializedName("ri")
final private String regionId;
@SerializedName("i")
final private String id;
@SerializedName("c")
final private String caption;
@SerializedName("wi")
final private double wealthIndex;
@SerializedName("ei")
final private double educationIndex;
@SerializedName("as")
final private double averageSalary;
@SerializedName("d")
final private int demography;
@SerializedName("p")
final private int population;
//названия спонсируемых мэром продуктовых категорий
@SerializedName("mb")
final private List<String> mayoralBonuses;
public City(final String countryId, final String regionId
, final String id, final String caption
, final double wealthIndex, final double educationIndex
, final double averageSalary, final int demography
, final int population, final List<String> mayoralBonuses
) {
this.countryId = countryId;
this.regionId = regionId;
this.id = id;
this.caption = caption;
this.wealthIndex = wealthIndex;
this.educationIndex = educationIndex;
this.averageSalary = averageSalary;
this.demography = demography;
this.population = population;
this.mayoralBonuses = mayoralBonuses;
}
public City(final City city, final int demography) {
this.countryId = city.countryId;
this.regionId = city.regionId;
this.id = city.id;
this.caption = city.caption;
this.wealthIndex = city.wealthIndex;
this.educationIndex = city.educationIndex;
this.averageSalary = city.averageSalary;
this.demography = demography;
this.population = city.population;
this.mayoralBonuses = city.mayoralBonuses;
}
public String getRegionId() {
return regionId;
}
public String getId() {
return id;
}
public String getCountryId() {
return countryId;
}
public String getCaption() {
return caption;
}
public double getWealthIndex() {
return wealthIndex;
}
public double getEducationIndex() {
return educationIndex;
}
public double getAverageSalary() {
return averageSalary;
}
public int getDemography() {
return demography;
}
public int getPopulation() {
return population;
}
public String getGeo() {
return getCountryId() + "/" + getRegionId() + "/" + getId();
}
}
<file_sep>/src/main/java/ru/VirtaMarketAnalyzer/parser/TechMarketAskParser.java
package ru.VirtaMarketAnalyzer.parser;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.VirtaMarketAnalyzer.data.*;
import ru.VirtaMarketAnalyzer.main.Utils;
import ru.VirtaMarketAnalyzer.main.Wizard;
import ru.VirtaMarketAnalyzer.scrapper.Downloader;
import java.io.IOException;
import java.lang.reflect.Type;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static java.util.stream.Collectors.toList;
/**
* Created by cobr123 on 20.03.16.
*/
final public class TechMarketAskParser {
private static final Logger logger = LoggerFactory.getLogger(TechMarketAskParser.class);
private static final Pattern tech_lvl_pattern = Pattern.compile("/globalreport/technology/(\\d+)/(\\d+)/target_market_summary/");
public static void main(String[] args) throws IOException {
final String realm = "olga";
final List<TechLicenseLvl> askWoBidTechLvl = getLicenseAskWoBid(Wizard.host, realm);
// logger.info(Utils.getPrettyGson(askWoBidTechLvl));
for (final TechLicenseLvl tl : askWoBidTechLvl) {
//https://virtonomica.ru/olga/main/globalreport/technology/2423/10/target_market_summary/21-03-2016/ask
if (tl.getTechId().equals("2423") && tl.getLvl() == 10) {
logger.info(Utils.getPrettyGson(tl));
}
//https://virtonomica.ru/olga/main/globalreport/technology/423140/2/target_market_summary/21-03-2016/ask
if (tl.getTechId().equals("423140") && tl.getLvl() == 2) {
logger.info(Utils.getPrettyGson(tl));
}
//https://virtonomica.ru/olga/main/globalreport/technology/1906/7/target_market_summary/21-03-2016/ask
if (tl.getTechId().equals("1906") && tl.getLvl() == 7) {
logger.info(Utils.getPrettyGson(tl));
}
break;
}
logger.info("askWoBidTechLvl.size() = {}", askWoBidTechLvl.size());
final List<TechUnitType> techList = TechListParser.getTechUnitTypes(Wizard.host, realm);
logger.info("techList.size() = {}", techList.size());
System.out.println(Utils.getPrettyGson(getTech(Wizard.host, realm, techList)));
}
public static List<TechLicenseLvl> getLicenseAskWoBid(final String host, final String realm) throws IOException {
final DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
final String dateStr = df.format(new Date());
final String url1 = host + realm + "/main/globalreport/technology_target_market/total?old";
final List<TechLicenseLvl> techIdAsks = getAskTechLicense(url1);
// logger.info(Utils.getPrettyGson(techIdAsks));
logger.info("techIdAsks.size() = {}, realm = {}", techIdAsks.size(), realm);
final List<TechLicenseLvl> licenseAskWoBid = new ArrayList<>();
for (final TechLicenseLvl techIdAsk : techIdAsks) {
//https://virtonomica.ru/olga/main/globalreport/technology/2427/31/target_market_summary/2016-03-21/ask
final String url2 = host + realm + "/main/globalreport/technology/" + techIdAsk.getTechId() + "/" + techIdAsk.getLvl() + "/target_market_summary/" + dateStr + "/ask?old";
// logger.info("url2 = {}", url2);
final List<TechLicenseAskBid> techAsks = getTechLicenseAskBids(url2);
// logger.info(Utils.getPrettyGson(techAsks));
// logger.info("techAsks.size() = {}", techAsks.size());
//https://virtonomica.ru/olga/main/globalreport/technology/2427/31/target_market_summary/2016-03-21/bid
final String url3 = host + realm + "/main/globalreport/technology/" + techIdAsk.getTechId() + "/" + techIdAsk.getLvl() + "/target_market_summary/" + dateStr + "/bid?old";
// logger.info("url3 = {}", url3);
final List<TechLicenseAskBid> techBids = getTechLicenseAskBids(url3);
// logger.info(Utils.getPrettyGson(techBids));
// logger.info("techBids.size() = {}", techBids.size());
if (!techAsks.isEmpty() && techBids.isEmpty()) {
licenseAskWoBid.add(new TechLicenseLvl(techIdAsk, Collections.emptyList()));
} else {
final List<TechLicenseAskBid> tmp = getAskWoBid(techAsks, techBids);
if (!tmp.isEmpty()) {
licenseAskWoBid.add(new TechLicenseLvl(techIdAsk, tmp));
}
}
// throw new IOException("test");
}
logger.info("licenseAskWoBid.size() = {}, realm = {}", licenseAskWoBid.size(), realm);
return licenseAskWoBid;
}
private static List<TechLicenseAskBid> getAskWoBid(final List<TechLicenseAskBid> asks, final List<TechLicenseAskBid> bids) {
//найти спрос без предложения (для цены спроса нет такой же или меньше цены предложения )
//найти спрос без достаточного предложения (для количества спроса нет такого же или больше количества предложения с такой же или меньшей ценой)
return asks.stream()
.map(ask -> {
final int bidQtySum = bids.stream().filter(bid -> ask.getPrice() >= bid.getPrice()).mapToInt(TechLicenseAskBid::getQuantity).sum();
final boolean bidWithGreaterPriceExist = bids.stream().anyMatch(bid -> ask.getPrice() >= bid.getPrice());
if (ask.getQuantity() > bidQtySum) {
return new TechLicenseAskBid(ask.getPrice(), ask.getQuantity() - bidQtySum);
} else if (!bidWithGreaterPriceExist) {
return ask;
}
return null;
})
.filter(Objects::nonNull)
.collect(Collectors.toList());
}
private static List<TechLicenseAskBid> getTechLicenseAskBids(final String url) throws IOException {
final int maxTryCnt = 3;
for (int tryCnt = 1; tryCnt <= maxTryCnt; ++tryCnt) {
final Document doc = Downloader.getDoc(url);
//итоги
final Element table = doc.select("table.list").first();
if (table == null) {
Downloader.invalidateCache(url);
logger.error("На странице '" + url + "' не найдена таблица с классом list");
Utils.waitSecond(3);
continue;
}
//сами ставки\предложения
final Elements priceAndQty = doc.select("table.list > tbody > tr[class]");
return priceAndQty.stream().map(paq -> {
final double price = Utils.toDouble(paq.select("> td:eq(0)").text());
final int quantity = Utils.toInt(paq.select("> td:eq(1)").text());
return new TechLicenseAskBid(price, quantity);
}).collect(toList());
}
return null;
}
private static List<TechLicenseLvl> getAskTechLicense(final String url) throws IOException {
final int maxTryCnt = 3;
// logger.info(url);
// Downloader.invalidateCache(url);
for (int tryCnt = 1; tryCnt <= maxTryCnt; ++tryCnt) {
final Document doc = Downloader.getDoc(url);
final Element table = doc.select("table.list").first();
if (table == null) {
Downloader.invalidateCache(url);
logger.error("На странице '" + url + "' не найдена таблица с классом list");
Utils.waitSecond(3);
continue;
}
final Element footer = doc.select("div.metro_footer").first();
if (footer == null) {
Downloader.invalidateCache(url);
logger.error("На странице '" + url + "' не найден div.metro_footer");
Utils.waitSecond(3);
continue;
}
final Elements asks = doc.select("table.list > tbody > tr > td > a:not(:contains(--))");
//https://virtonomica.ru/olga/main/globalreport/technology/2423/16/target_market_summary/21-03-2016/ask
return asks.stream().map(ask -> {
final Matcher matcher = tech_lvl_pattern.matcher(ask.attr("href"));
if (matcher.find()) {
final String techID = matcher.group(1);
final int lvl = Integer.parseInt(matcher.group(2));
return new TechLicenseLvl(techID, lvl);
}
return null;
}).collect(toList());
}
return null;
}
public static List<TechLvl> getTech(final String host, final String realm, final List<TechUnitType> techList) throws IOException {
return techList.stream()
.map(tl -> {
try {
return getTech(host, realm, tl.getId());
} catch (final Exception e) {
logger.error(e.getLocalizedMessage(), e);
}
return null;
})
.filter(Objects::nonNull)
.flatMap(Collection::stream)
.collect(toList());
}
public static List<TechLvl> getTech(final String host, final String realm, final String unit_type_id) throws IOException {
final String url = host + "api/" + realm + "/main/unittype/technologies?app=virtonomica&format=json&ajax=1&id=" + unit_type_id + "&wrap=0";
try {
final String json = Downloader.getJson(url);
final Gson gson = new Gson();
final Type mapType = new TypeToken<TechReport[]>() {
}.getType();
final TechReport[] arr = gson.fromJson(json, mapType);
return Stream.of(arr)
.map(row -> new TechLvl(row.getUnitTypeID(), row.getLevel(), row.getPrice()))
.collect(toList());
} catch (final IOException e) {
logger.error("url = {}", url);
throw new IOException(e.getLocalizedMessage(), e);
}
}
}
<file_sep>/src/main/java/ru/VirtaMarketAnalyzer/data/MajorSellInCity.java
package ru.VirtaMarketAnalyzer.data;
import com.google.gson.annotations.SerializedName;
/**
* Created by cobr123 on 25.04.2015.
*/
public final class MajorSellInCity {
@SerializedName("s")
private final long shopSize;
@SerializedName("d")
private final String townDistrict;
@SerializedName("v")
private final double sellVolume;
@SerializedName("p")
private final double price;
@SerializedName("q")
private final double quality;
@SerializedName("b")
private final double brand;
final private transient String unitId;
final private transient String countryId;
final private transient String regionId;
final private transient String townId;
final private transient String productId;
public MajorSellInCity(final String productId, final String countryId, final String regionId, final String townId, final String unitId, final long shopSize, final String townDistrict, final double sellVolume, final double price, final double quality, final double brand) {
this.productId = productId;
this.countryId = countryId;
this.regionId = regionId;
this.townId = townId;
this.unitId = unitId;
this.shopSize = shopSize;
this.townDistrict = townDistrict;
this.sellVolume = sellVolume;
this.price = price;
this.quality = quality;
this.brand = brand;
}
public String getProductId() {
return productId;
}
public String getGeo() {
return getCountryId() + "/" + getRegionId() + "/" + getTownId();
}
public String getCountryId() {
return countryId;
}
public String getRegionId() {
return regionId;
}
public String getTownId() {
return townId;
}
public String getUnitId() {
return unitId;
}
public long getShopSize() {
return shopSize;
}
public String getTownDistrict() {
return townDistrict;
}
public double getSellVolume() {
return sellVolume;
}
public double getPrice() {
return price;
}
public double getQuality() {
return quality;
}
public double getBrand() {
return brand;
}
}
<file_sep>/src/main/java/ru/VirtaMarketAnalyzer/data/FileVersion.java
package ru.VirtaMarketAnalyzer.data;
import java.util.Date;
/**
* Created by cobr123 on 09.02.2017.
*/
public final class FileVersion {
private final Date date;
private final String content;
public FileVersion(final Date date, final String content) {
this.date = date;
this.content = content;
}
public Date getDate() {
return date;
}
public String getContent() {
return content;
}
}
<file_sep>/src/main/java/ru/VirtaMarketAnalyzer/data/TechUnitType.java
package ru.VirtaMarketAnalyzer.data;
import com.google.gson.annotations.SerializedName;
/**
* Created by cobr123 on 21.03.2016.
*/
final public class TechUnitType {
@SerializedName("i")
final private String id;
@SerializedName("c")
final private String caption;
public TechUnitType(final String id, final String caption) {
this.id = id;
this.caption = caption;
}
public String getId() {
return id;
}
public String getCaption() {
return caption;
}
}
<file_sep>/src/main/java/ru/VirtaMarketAnalyzer/data/ProductionAboveAverage.java
package ru.VirtaMarketAnalyzer.data;
import com.google.gson.annotations.SerializedName;
import java.util.List;
/**
* Created by r.tabulov on 16.10.2016.
*/
public final class ProductionAboveAverage {
@SerializedName("mi")
final private String manufactureID;
@SerializedName("s")
final private String specialization;
@SerializedName("pi")
final private String productID;
@SerializedName("v")
final private long volume;
@SerializedName("q")
final private double quality;
@SerializedName("c")
final private double cost;
@SerializedName("tl")
final private double techLvl;
@SerializedName("ir")
final private List<ProductRemain> ingredientsRemain;
@SerializedName("mwc")
final private long maxWorkplacesCount;
@SerializedName("ctm")
final private boolean cheaperThenMarket;
public ProductionAboveAverage(final String manufactureID
, final String specialization
, final String productID
, final long volume
, final double quality
, final double cost
, final List<ProductRemain> ingredientsRemain
, final double techLvl
, final long maxWorkplacesCount
, final boolean cheaperThenMarket
) {
this.manufactureID = manufactureID;
this.specialization = specialization;
this.productID = productID;
this.volume = volume;
this.quality = quality;
this.cost = cost;
this.ingredientsRemain = ingredientsRemain;
this.techLvl = techLvl;
this.maxWorkplacesCount = maxWorkplacesCount;
this.cheaperThenMarket = cheaperThenMarket;
}
public String getManufactureID() {
return manufactureID;
}
public String getSpecialization() {
return specialization;
}
public String getProductID() {
return productID;
}
public long getVolume() {
return volume;
}
public double getQuality() {
return quality;
}
public double getCost() {
return cost;
}
public double getTechLvl() {
return techLvl;
}
public List<ProductRemain> getIngredientsRemain() {
return ingredientsRemain;
}
public long getMaxWorkplacesCount() {
return maxWorkplacesCount;
}
public boolean isCheaperThenMarket() {
return cheaperThenMarket;
}
}
<file_sep>/src/main/java/ru/VirtaMarketAnalyzer/data/RawMaterial.java
package ru.VirtaMarketAnalyzer.data;
import com.google.gson.annotations.SerializedName;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
/**
* Created by cobr123 on 06.04.2016.
*/
public final class RawMaterial {
@SerializedName("pc")
final private String productCategory;
@SerializedName("s")
final private String imgUrl;
@SerializedName("i")
final private String id;
@SerializedName("c")
final private String caption;
@SerializedName("q")
final private double quantity;
public RawMaterial(final String productCategory, final String imgUrl, final String id, final String caption, final double quantity) {
this.productCategory = productCategory;
this.imgUrl = imgUrl;
this.id = id;
this.caption = caption;
this.quantity = quantity;
}
public RawMaterial(final Product product, final double quantity) {
this.productCategory = product.getProductCategory();
this.imgUrl = product.getImgUrl();
this.id = product.getId();
this.caption = product.getCaption();
this.quantity = quantity;
}
@Override
public int hashCode() {
return new HashCodeBuilder()
.append(productCategory)
.append(imgUrl)
.append(id)
.append(caption)
.toHashCode();
}
@Override
public boolean equals(final Object obj) {
if (obj instanceof RawMaterial) {
final RawMaterial other = (RawMaterial) obj;
return new EqualsBuilder()
.append(productCategory, other.productCategory)
.append(imgUrl, other.imgUrl)
.append(id, other.id)
.append(caption, other.caption)
.isEquals();
} else {
return false;
}
}
public String getImgUrl() {
return imgUrl;
}
public String getId() {
return id;
}
public String getCaption() {
return caption;
}
public String getProductCategory() {
return productCategory;
}
public double getQuantity() {
return quantity;
}
}
<file_sep>/README.md
[](https://lgtm.com/projects/g/cobr123/VirtaMarketAnalyzer/alerts/) [](https://lgtm.com/projects/g/cobr123/VirtaMarketAnalyzer/context:java)
# VirtaMarketAnalyzer
<file_sep>/src/main/java/ru/VirtaMarketAnalyzer/parser/CityInitParser.java
package ru.VirtaMarketAnalyzer.parser;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.VirtaMarketAnalyzer.data.Country;
import ru.VirtaMarketAnalyzer.data.Region;
import ru.VirtaMarketAnalyzer.main.Wizard;
import ru.VirtaMarketAnalyzer.scrapper.Downloader;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
/**
* Created by cobr123 on 24.04.2015.
*/
public final class CityInitParser {
private static final Logger logger = LoggerFactory.getLogger(CityInitParser.class);
public static Region getRegion(final String host, final String realm, final String id) throws IOException {
final Optional<Region> regionOpt = getRegions(host, realm).stream().filter(region -> region.getId().equals(id)).findFirst();
if (!regionOpt.isPresent()) {
throw new IllegalArgumentException("Не найден регион с id '" + id + "'");
}
return regionOpt.get();
}
public static List<Region> getRegions(final String host, final String realm) throws IOException {
final String lang = (Wizard.host.equals(host) ? "ru" : "en");
final String url = host + "api/" + realm + "/main/geo/region/browse?lang=" + lang;
final List<Region> list = new ArrayList<>();
try {
final String json = Downloader.getJson(url);
final Gson gson = new Gson();
final Type mapType = new TypeToken<Map<String, Map<String, Object>>>() {
}.getType();
final Map<String, Map<String, Object>> mapOfRegions = gson.fromJson(json, mapType);
for (final Map.Entry<String, Map<String, Object>> entry : mapOfRegions.entrySet()) {
final Map<String, Object> region = entry.getValue();
final String country_id = region.get("country_id").toString();
final String id = region.get("id").toString();
final String caption = region.get("name").toString();
final double incomeTaxRate = Double.parseDouble(region.get("tax").toString());
list.add(new Region(country_id, id, caption, incomeTaxRate));
}
} catch (final Exception e) {
logger.error(url + "&format=debug");
throw e;
}
return list;
}
public static List<Country> getCountries(final String host, final String realm) throws IOException {
final String lang = (Wizard.host.equals(host) ? "ru" : "en");
final String url = host + "api/" + realm + "/main/geo/country/browse?lang=" + lang;
final List<Country> list = new ArrayList<>();
try {
final String json = Downloader.getJson(url);
final Gson gson = new Gson();
final Type mapType = new TypeToken<Map<String, Map<String, Object>>>() {
}.getType();
final Map<String, Map<String, Object>> mapOfCountry = gson.fromJson(json, mapType);
for (final Map.Entry<String, Map<String, Object>> entry : mapOfCountry.entrySet()) {
final Map<String, Object> country = entry.getValue();
final String id = country.get("id").toString();
final String caption = country.get("name").toString();
list.add(new Country(id, caption));
}
} catch (final Exception e) {
logger.error(url + "&format=debug");
throw e;
}
return list;
}
}<file_sep>/src/main/java/ru/VirtaMarketAnalyzer/data/Manufacture.java
package ru.VirtaMarketAnalyzer.data;
import com.google.gson.annotations.SerializedName;
import java.util.List;
/**
* Created by cobr123 on 18.05.2015.
*/
final public class Manufacture {
@SerializedName("i")
final private String id;
@SerializedName("mc")
private String manufactureCategory;
@SerializedName("c")
final private String caption;
@SerializedName("ms")
final private List<ManufactureSize> sizes;
public Manufacture(final String id,final String manufactureCategory,final String caption, final List<ManufactureSize> sizes) {
this.id = id;
this.manufactureCategory = manufactureCategory;
this.caption = caption;
this.sizes = sizes;
}
public String getId() {
return id;
}
public String getManufactureCategory() {
return manufactureCategory;
}
public void setManufactureCategory(final String manufactureCategory) {
this.manufactureCategory = manufactureCategory;
}
public String getCaption() {
return caption;
}
public List<ManufactureSize> getSizes() {
return sizes;
}
}
<file_sep>/src/main/java/ru/VirtaMarketAnalyzer/parser/ServiceInitParser.java
package ru.VirtaMarketAnalyzer.parser;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.VirtaMarketAnalyzer.data.Product;
import ru.VirtaMarketAnalyzer.data.RawMaterial;
import ru.VirtaMarketAnalyzer.data.UnitType;
import ru.VirtaMarketAnalyzer.data.UnitTypeSpec;
import ru.VirtaMarketAnalyzer.main.Wizard;
import ru.VirtaMarketAnalyzer.scrapper.Downloader;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
/**
* Created by cobr123 on 25.02.16.
*/
public final class ServiceInitParser {
private static final Logger logger = LoggerFactory.getLogger(ServiceInitParser.class);
public static UnitType getServiceUnitType(final String host, final String realm, final String id) throws IOException {
final Optional<UnitType> opt = getServiceUnitTypes(host, realm).stream()
.filter(v -> v.getId().equals(id)).findFirst();
if (!opt.isPresent()) {
throw new IllegalArgumentException("Не найден сервис с id '" + id + "'");
}
return opt.get();
}
public static List<UnitType> getServiceUnitTypes(final String host, final String realm) throws IOException {
final String lang = (Wizard.host.equals(host) ? "ru" : "en");
final String url = host + "api/" + realm + "/main/unittype/browse?lang=" + lang;
final List<UnitType> list = new ArrayList<>();
try {
final String json = Downloader.getJson(url);
final Gson gson = new Gson();
final Type mapType = new TypeToken<Map<String, Map<String, Object>>>() {
}.getType();
final Map<String, Map<String, Object>> mapOfUnitTypes = gson.fromJson(json, mapType);
for (final Map.Entry<String, Map<String, Object>> entry : mapOfUnitTypes.entrySet()) {
final Map<String, Object> unitType = entry.getValue();
if ("service_light".equalsIgnoreCase(unitType.get("kind").toString())
|| "educational".equalsIgnoreCase(unitType.get("kind").toString())
|| "restaurant".equalsIgnoreCase(unitType.get("kind").toString())
|| "repair".equalsIgnoreCase(unitType.get("kind").toString())
|| "medicine".equalsIgnoreCase(unitType.get("kind").toString())
|| "it".equalsIgnoreCase(unitType.get("kind").toString())
) {
final String id = unitType.get("id").toString();
final String caption = unitType.get("name").toString();
final String imgUrl = "/img/unit_types/" + unitType.get("symbol").toString() + ".gif";
list.add(new UnitType(id, caption, imgUrl, getServiceSpecs(host, realm, id)));
}
}
} catch (final Exception e) {
Downloader.invalidateCache(url);
logger.error(url + "&format=debug");
throw e;
}
return list;
}
public static List<UnitTypeSpec> getServiceSpecs(final String host, final String realm, final String unit_type_id) throws IOException {
final String lang = (Wizard.host.equals(host) ? "ru" : "en");
final String url = host + "api/" + realm + "/main/unittype/produce?id=" + unit_type_id + "&lang=" + lang;
final List<UnitTypeSpec> list = new ArrayList<>();
try {
final String json = Downloader.getJson(url);
final Gson gson = new Gson();
final Type mapType = new TypeToken<Map<String, Map<String, Object>>>() {
}.getType();
final Map<String, Map<String, Object>> mapOfUnitTypes = gson.fromJson(json, mapType);
for (final Map.Entry<String, Map<String, Object>> entry : mapOfUnitTypes.entrySet()) {
final Map<String, Object> unitType = entry.getValue();
final String id = unitType.get("id").toString();
final String caption = unitType.get("name").toString();
final String equipment_product_id = unitType.get("equipment_product_id").toString();
list.add(new UnitTypeSpec(id, caption, getProduct(host, realm, equipment_product_id), getRawMaterials(host, realm, unitType)));
}
} catch (final Exception e) {
Downloader.invalidateCache(url);
logger.error(url + "&format=debug");
throw e;
}
return list;
}
private static Product getProduct(final String host, final String realm, final String id) throws IOException {
return ProductInitParser.getManufactureProduct(host, realm, id);
}
private static List<RawMaterial> getRawMaterials(final String host, final String realm, final Map<String, Object> unitType) throws IOException {
final List<RawMaterial> rawMaterials = new ArrayList<>();
final Object inputObj = unitType.get("input");
if (inputObj != null && !(inputObj instanceof ArrayList)) {
final Map<String, Object> inputList = (Map<String, Object>) inputObj;
for (final Map.Entry<String, Object> entry : inputList.entrySet()) {
final Map<String, Object> input = (Map<String, Object>) entry.getValue();
final Product product = getProduct(host, realm, input.get("id").toString());
final double quantity = Double.parseDouble(input.get("qty").toString());
rawMaterials.add(new RawMaterial(product, quantity));
}
}
return rawMaterials;
}
private static String removeCurlyBraces(final String line) {
return line.substring(1, line.length() - 1);
}
}
<file_sep>/src/main/java/ru/VirtaMarketAnalyzer/data/TechLicenseAskBid.java
package ru.VirtaMarketAnalyzer.data;
import com.google.gson.annotations.SerializedName;
/**
* Created by cobr123 on 21.03.2016.
*/
final public class TechLicenseAskBid {
@SerializedName("p")
final private double price;
@SerializedName("q")
final private int quantity;
public TechLicenseAskBid(final Double price, final int quantity) {
this.price = price;
this.quantity = quantity;
}
public Double getPrice() {
return price;
}
public int getQuantity() {
return quantity;
}
}
<file_sep>/src/main/java/ru/VirtaMarketAnalyzer/main/Utils.java
package ru.VirtaMarketAnalyzer.main;
import com.google.gson.ExclusionStrategy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import org.apache.commons.compress.archivers.zip.ZipFile;
import org.apache.commons.compress.utils.SeekableInMemoryByteChannel;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.function.Supplier;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* Created by cobr123 on 25.04.2015.
*/
public final class Utils {
private static final Logger logger = LoggerFactory.getLogger(Utils.class);
private static final Pattern fraction_pattern = Pattern.compile("^\\d+(\\.\\d+)?/\\d+(\\.\\d+)?$");
public static String getDir() {
String dir = System.getProperty("java.io.tmpdir");
if (dir.charAt(dir.length() - 1) != File.separatorChar) {
dir += File.separator;
}
return dir + "VirtaMarketAnalyzer" + File.separator;
}
public static void writeToGson(final String path, final Object obj) throws IOException {
logger.trace(path);
Utils.writeFile(path, getGson(obj));
}
public static void writeToGsonZip(final String path, final Object obj) throws IOException {
logger.trace(path);
Utils.writeToZip(path, obj);
final File file = new File(path);
if (file.exists()) {
file.deleteOnExit();
}
}
public static void writeToZip(final String path, final Object obj) throws IOException {
final File file = Utils.mkdirs(path + ".zip");
try (final ZipOutputStream out = new ZipOutputStream(Files.newOutputStream(file.toPath()))) {
final ZipEntry e = new ZipEntry(new File(path).getName());
out.putNextEntry(e);
final byte[] data = getGson(obj).getBytes();
out.write(data, 0, data.length);
out.closeEntry();
}
}
public static String readFromZip(final String path, final ByteArrayOutputStream os) throws IOException {
try (final ZipFile zipFile = new ZipFile(new SeekableInMemoryByteChannel(os.toByteArray()))) {
return IOUtils.toString(zipFile.getInputStream(zipFile.getEntry(path)), StandardCharsets.UTF_8);
}
}
public static void writeToGson(final String path, final Object obj, final ExclusionStrategy es) throws IOException {
logger.trace(path);
Utils.writeFile(path, getGson(obj, es));
}
public static String getGson(final Object obj) {
final Gson gson = new Gson();
return gson.toJson(obj);
}
public static String getGson(final Object obj, final ExclusionStrategy es) {
final Gson gson = new GsonBuilder().setExclusionStrategies(es).create();
return gson.toJson(obj);
}
public static String getPrettyGson(final Object obj) {
final Gson gson = new GsonBuilder().setPrettyPrinting().create();
return gson.toJson(obj);
}
public static File mkdirs(final String path) {
final File file = new File(path);
if (!file.exists()) {
final File dir = new File(file.getParent());
if (!dir.exists()) {
dir.mkdirs();
}
}
return file;
}
public static void writeFile(final String path, final String content)
throws IOException {
final File file = Utils.mkdirs(path);
FileUtils.writeStringToFile(file, content, "UTF-8");
}
public static String readFile(final String path) throws IOException {
return new String(Files.readAllBytes(Paths.get(path)), StandardCharsets.UTF_8);
}
public static String clearNumber(final String text) {
if (text.equals("-")) {
return "";
} else if (text.toUpperCase().contains("E-") || text.toUpperCase().contains("E+")) {
return text.replace("$", "").replace("+", "").replace("*", "").replace("%", "").replace("©", "").replaceAll("\\s+", "").trim();
} else {
return text.replace("$", "").replace("+", "").replace("*", "").replace("%", "").replace("©", "").replaceAll("\\p{L}+\\.?", "").replaceAll("\\p{InCyrillic}+\\.?", "").replaceAll("\\s+", "").trim();
}
}
public static int doubleToInt(final double num) {
final int res = (int) num;
if (res == num) {
return res;
} else {
throw new IllegalArgumentException("Не удалось преобразовать double \"" + num + "\" в int без потери точности");
}
}
public static double toDouble(final String text) {
try {
final String clear = clearNumber(text);
if (clear.isEmpty() || "-".equals(text)) {
return 0.0;
} else {
final Matcher matcher = fraction_pattern.matcher(clear);
if (matcher.find()) {
final String[] data = clear.split("/");
return Double.parseDouble(data[0]) / Double.parseDouble(data[1]);
} else {
return Double.parseDouble(clear);
}
}
} catch (final Exception e) {
logger.error("Не удалось преобразовать строку \"" + text + "\" в double");
throw e;
}
}
public static long toLong(final String text) {
try {
final String clear = clearNumber(text);
if (clear.isEmpty()) {
return 0;
} else {
return Long.parseLong(clear);
}
} catch (final Exception e) {
logger.error("Не удалось преобразовать строку \"" + text + "\" в long");
throw e;
}
}
public static int toInt(final String text) {
try {
final String clear = clearNumber(text);
if (clear.isEmpty()) {
return 0;
} else {
return Integer.parseInt(clear);
}
} catch (final Exception e) {
logger.error("Не удалось преобразовать строку \"" + text + "\" в int");
throw e;
}
}
public static Date getZeroTimeDate(final Date date) {
final Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTime();
}
public static boolean equalsWoTime(final Date date1, final Date date2) {
return getZeroTimeDate(date1).equals(getZeroTimeDate(date2));
}
public static int daysBetween(final Date date1, final Date date2) {
return (int) ((getZeroTimeDate(date1).getTime() - getZeroTimeDate(date2).getTime()) / (1000 * 60 * 60 * 24));
}
public static String getNextPageHref(final Document doc) {
final Element currPage = doc.select("ul[class=\"pager_list pull-right\"] > li.selected").last();
if (currPage == null || currPage.parent() == null) {
logger.trace("currPage is null");
return "";
}
final Element nextPageLink = currPage.nextElementSibling();
if (nextPageLink != null && "li".equalsIgnoreCase(nextPageLink.nodeName())) {
logger.trace("nextPageLink = " + nextPageLink);
return nextPageLink.select("> a").attr("href");
} else {
logger.trace("nextPageLink is null");
}
return "";
}
public static String getFirstBySep(final String str, final String sep) {
final String[] data = str.split(sep);
return data[0];
}
public static String getLastBySep(final String str, final String sep) {
final String[] data = str.split(sep);
return data[data.length - 1];
}
public static String getLastFromUrl(final String url) {
return getLastBySep(url, "/");
}
public static double round2(final double num) {
return Math.round(num * 100.0) / 100.0;
}
public static <T> T repeatOnErr(final Callable<T> func) throws Exception {
try {
return func.call();
} catch (final Exception e) {
logger.error(e.getLocalizedMessage(), e);
Utils.waitSecond(1);
return func.call();
}
}
private static class Prefix<T> {
final T value;
final Prefix<T> parent;
Prefix(Prefix<T> parent, T value) {
this.parent = parent;
this.value = value;
}
// put the whole prefix into given collection
<C extends Collection<T>> C addTo(C collection) {
if (parent != null)
parent.addTo(collection);
collection.add(value);
return collection;
}
}
private static <T, C extends Collection<T>> Stream<C> comb(
List<? extends Collection<T>> values, int offset, Prefix<T> prefix,
Supplier<C> supplier) {
if (offset == values.size() - 1)
return values.get(offset).stream()
.map(e -> new Prefix<>(prefix, e).addTo(supplier.get()));
return values.get(offset).stream()
.flatMap(e -> comb(values, offset + 1, new Prefix<>(prefix, e), supplier));
}
public static <T, C extends Collection<T>> Stream<C> ofCombinations(
Collection<? extends Collection<T>> values, Supplier<C> supplier) {
if (values.isEmpty())
return Stream.empty();
return comb(new ArrayList<>(values), 0, null, supplier);
}
//максимальное кол-во работающих с заданной квалификацией на предприятиии для заданной квалификации игрока (топ-1)
public static double calcMaxTop1(final double playerQuality, final double workersQuality) {
final double workshopLoads = 50.0;
return Math.floor(workshopLoads * 14.0 * playerQuality * playerQuality / Math.pow(1.4, workersQuality) / 5.0);
}
//квалификация игрока необходимая для данного уровня технологии
public static double calcPlayerQualityForTech(final double techLvl) {
return Math.pow(2.72, Math.log(techLvl) / (1.0 / 3.0)) * 0.0064;
}
//квалификация рабочих необходимая для данного уровня технологии
public static double calcWorkersQualityForTech(final double techLvl) {
return Math.pow(techLvl, 0.8);
}
public static void waitSecond(final long seconds) {
try {
Thread.sleep(seconds * 1000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
public static <T> List<T> toList(String json, Class<T> clazz) {
if (null == json) {
return null;
}
Gson gson = new Gson();
return gson.fromJson(json, new TypeToken<T>() {
}.getType());
}
}
<file_sep>/src/main/java/ru/VirtaMarketAnalyzer/data/ProductRemain.java
package ru.VirtaMarketAnalyzer.data;
import com.google.gson.annotations.SerializedName;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import java.util.Date;
/**
* Created by cobr123 on 20.05.2015.
*/
public final class ProductRemain {
//U - UNLIMITED, L - LIMITED
public enum MaxOrderType {
U, L
}
//Infinity
@SerializedName("cn")
final private String companyName;
@SerializedName("pi")
final private String productID;
@SerializedName("ui")
final private String unitID;
@SerializedName("ci")
final private String countryId;
@SerializedName("ri")
final private String regionId;
@SerializedName("ti")
final private String townId;
@SerializedName("t")
final private long total;
@SerializedName("r")
final private long remain;
@SerializedName("q")
final private double quality;
@SerializedName("p")
final private double price;
@SerializedName("mot")
final private MaxOrderType maxOrderType;
@SerializedName("mo")
final private long maxOrder;
transient private Date date;
public ProductRemain(
final String productID,
final String companyName,
final String unitID,
final String countryId,
final String regionId,
final String townId,
final long total,
final long remain,
final double quality,
final double price,
final MaxOrderType maxOrderType,
final long maxOrder
) {
this.productID = productID;
this.companyName = companyName;
this.unitID = unitID;
this.countryId = countryId;
this.regionId = regionId;
this.townId = townId;
this.total = total;
this.remain = remain;
this.quality = quality;
this.price = price;
this.maxOrderType = maxOrderType;
this.maxOrder = maxOrder;
}
@Override
public int hashCode() {
return new HashCodeBuilder()
.append(productID)
.append(companyName)
.append(unitID)
.append(total)
.append(remain)
.append(quality)
.append(price)
.append(maxOrderType)
.append(maxOrder)
.toHashCode();
}
@Override
public boolean equals(final Object obj) {
if (obj instanceof ProductRemain) {
final ProductRemain other = (ProductRemain) obj;
return new EqualsBuilder()
.append(productID, other.productID)
.append(companyName, other.companyName)
.append(unitID, other.unitID)
.append(total, other.total)
.append(remain, other.remain)
.append(quality, other.quality)
.append(price, other.price)
.append(maxOrderType, other.maxOrderType)
.append(maxOrder, other.maxOrder)
.isEquals();
} else {
return false;
}
}
public String getCompanyName() {
return companyName;
}
public String getProductID() {
return productID;
}
public String getUnitID() {
return unitID;
}
public long getTotal() {
return total;
}
public long getRemain() {
return remain;
}
public double getQuality() {
return quality;
}
public double getPrice() {
return price;
}
public long getMaxOrder() {
return maxOrder;
}
public MaxOrderType getMaxOrderType() {
return maxOrderType;
}
public long getRemainByMaxOrderType() {
return (getMaxOrderType() == MaxOrderType.L && getRemain() > getMaxOrder()) ? getMaxOrder() : getRemain();
}
public Date getDate() {
return date;
}
public void setDate(final Date date) {
this.date = date;
}
public String getCountryId() {
return countryId;
}
public String getRegionId() {
return regionId;
}
public String getTownId() {
return townId;
}
}
<file_sep>/src/main/java/ru/VirtaMarketAnalyzer/data/CityElectricityTariff.java
package ru.VirtaMarketAnalyzer.data;
import com.google.gson.annotations.SerializedName;
/**
* Created by cobr123 on 22.06.2017.
* Тарифы на электроэнергию
*/
final public class CityElectricityTariff {
@SerializedName("ci")
final private String cityId;
//@SerializedName("pc")
//в файл не выгружаем пока что
transient final private String productCategory;
//в файл не выгружаем, т.к. id будет в имени файла
transient final private String productID;
@SerializedName("et")
final private double electricityTariff;
public CityElectricityTariff(final String cityId, final String productCategory, final String productID, final double electricityTariff) {
this.cityId = cityId;
this.productCategory = productCategory;
this.productID = productID;
this.electricityTariff = electricityTariff;
}
public String getCityId() {
return cityId;
}
public String getProductCategory() {
return productCategory;
}
public String getProductID() {
return productID;
}
public double getElectricityTariff() {
return electricityTariff;
}
}
<file_sep>/src/main/java/ru/VirtaMarketAnalyzer/data/ProductHistory.java
package ru.VirtaMarketAnalyzer.data;
import com.google.gson.annotations.SerializedName;
/**
* Created by cobr123 on 16.10.2016.
*/
public final class ProductHistory {
@SerializedName("pi")
final private String productID;
@SerializedName("vp")
final private long volumeProd;
@SerializedName("vc")
final private long volumeCons;
@SerializedName("q")
final private double quality;
@SerializedName("c")
final private double cost;
@SerializedName("av")
final private double assessedValue;
public ProductHistory(
final String productID
, final long volumeProd
, final long volumeCons
, final double quality
, final double cost
, final double assessedValue
) {
this.productID = productID;
this.volumeProd = volumeProd;
this.volumeCons = volumeCons;
this.quality = quality;
this.cost = cost;
this.assessedValue = assessedValue;
}
public String getProductID() {
return productID;
}
public long getVolumeProd() {
return volumeProd;
}
public long getVolumeCons() {
return volumeCons;
}
public double getQuality() {
return quality;
}
public double getCost() {
return cost;
}
public double getAssessedValue() {
return assessedValue;
}
}
<file_sep>/src/main/java/ru/VirtaMarketAnalyzer/ml/RetailAnalyticsHistCompare.java
package ru.VirtaMarketAnalyzer.ml;
import ru.VirtaMarketAnalyzer.data.RetailAnalytics;
import java.util.Comparator;
/**
* Created by cobr123 on 02.03.2016.
*/
public final class RetailAnalyticsHistCompare implements Comparator<RetailAnalytics> {
@Override
public int compare(final RetailAnalytics o1, final RetailAnalytics o2) {
int result = 0;
final int marketIdxCompRes = o1.getMarketIdx().compareTo(o2.getMarketIdx());
if (marketIdxCompRes != 0) {
result = marketIdxCompRes;
} else if (o1.getWealthIndexRounded() < o2.getWealthIndexRounded()) {
result = 1;
} else if (o1.getWealthIndexRounded() > o2.getWealthIndexRounded()) {
result = -1;
} else if (o1.getMarketVolume() < o2.getMarketVolume()) {
result = 1;
} else if (o1.getMarketVolume() > o2.getMarketVolume()) {
result = -1;
} else if (o1.getSellVolumeAsNumber() < o2.getSellVolumeAsNumber()) {
result = 1;
} else if (o1.getSellVolumeAsNumber() > o2.getSellVolumeAsNumber()) {
result = -1;
} else if (o1.getPrice() < o2.getPrice()) {
result = 1;
} else if (o1.getPrice() > o2.getPrice()) {
result = -1;
}
return result;
}
}
<file_sep>/src/main/java/ru/VirtaMarketAnalyzer/data/RetailTrend.java
package ru.VirtaMarketAnalyzer.data;
import com.google.gson.annotations.SerializedName;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Created by cobr123 on 09.02.2017.
*/
public final class RetailTrend {
@SerializedName("d")
final private String dateStr;
@SerializedName("lpr")
final private double localPrice;
@SerializedName("lq")
final private double localQuality;
@SerializedName("spr")
final private double shopPrice;
@SerializedName("sq")
final private double shopQuality;
@SerializedName("v")
final private double volume;
final private transient Date date;
final public static transient DateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
public RetailTrend(
final double localPrice,
final double localQuality,
final double shopPrice,
final double shopQuality,
final Date date,
final double volume
) {
this.date = date;
this.dateStr = dateFormat.format(date);
this.localPrice = localPrice;
this.localQuality = localQuality;
this.shopPrice = shopPrice;
this.shopQuality = shopQuality;
this.volume = volume;
}
public double getLocalPrice() {
return localPrice;
}
public double getLocalQuality() {
return localQuality;
}
public double getShopPrice() {
return shopPrice;
}
public double getShopQuality() {
return shopQuality;
}
public double getVolume() {
return volume;
}
public Date getDate() {
return date;
}
}
<file_sep>/src/main/java/ru/VirtaMarketAnalyzer/main/TrendUpdater.java
package ru.VirtaMarketAnalyzer.main;
import org.apache.commons.lang3.time.StopWatch;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.VirtaMarketAnalyzer.data.*;
import ru.VirtaMarketAnalyzer.ml.RetailSalePrediction;
import ru.VirtaMarketAnalyzer.parser.ProductInitParser;
import ru.VirtaMarketAnalyzer.publish.GitHubPublisher;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import static ru.VirtaMarketAnalyzer.ml.RetailSalePrediction.*;
/**
* Created by cobr123 on 29.09.2017.
*/
final public class TrendUpdater {
private static final Logger logger = LoggerFactory.getLogger(TrendUpdater.class);
public static void main(String[] args) throws IOException, GitAPIException {
updateTrends(Wizard.realms);
}
public static void updateTrends(List<String> realms) throws IOException, GitAPIException {
//обновляем
final Git git = RetailSalePrediction.fetchAndHardReset();
for (final String realm : realms) {
updateTrends(git, realm);
}
//публикуем на сайте
GitHubPublisher.publishTrends(git, realms);
//gc
GitHubPublisher.repackRepository();
}
public static void updateTrends(final Git git, final String realm) throws IOException, GitAPIException {
logger.info("обновляем тренды, {}", realm);
updateAllRetailTrends(git, realm);
updateAllProductRemainTrends(git, realm);
}
private static void updateAllRetailTrends(final Git git, final String realm) throws IOException, GitAPIException {
final String baseDir = Utils.getDir() + Wizard.by_trade_at_cities + File.separator + realm + File.separator;
logger.info("получаем список доступных розничных товаров");
final List<Product> products = ProductInitParser.getTradingProducts(Wizard.host, realm);
logger.info("products.size() = {}, realm = {}", products.size(), realm);
for (int i = 0; i < products.size(); i++) {
final StopWatch watch = new StopWatch();
watch.start();
final Product product = products.get(i);
logger.info("realm = {}, {} / {} собираем данные продаж товаров в городах, {}", realm, i + 1, products.size(), product.getCaption());
final Set<TradeAtCity> set = RetailSalePrediction.getAllTradeAtCity(git, TRADE_AT_CITY_ + product.getId(), realm, product.getId());
final String fileNamePath = baseDir + Wizard.retail_trends + File.separator + product.getId() + ".json";
Utils.writeToGsonZip(fileNamePath, getRetailTrends(new ArrayList<>(set)));
watch.stop();
logger.info("время выполнения: {}, записей сохранено: {}", watch.toString(), set.size());
}
logger.info("запоминаем дату обновления данных");
final DateFormat df = new SimpleDateFormat("dd.MM.yyyy");
Utils.writeToGson(baseDir + Wizard.retail_trends + File.separator + "updateDate.json", new UpdateDate(df.format(new Date())));
}
private static List<RetailTrend> getRetailTrends(final List<TradeAtCity> list) {
return list.stream()
.collect(Collectors.groupingBy((tac) -> RetailTrend.dateFormat.format(tac.getDate())))
.values().stream()
.map(e -> getWeighedRetailTrend(groupByTown(e)))
.sorted(Comparator.comparing(RetailTrend::getDate))
.collect(Collectors.toList());
}
private static List<TradeAtCity> groupByTown(final List<TradeAtCity> list) {
//проверяем что для одного продукта в одном городе только одна запись на дату
return list.stream()
.collect(Collectors.groupingBy(TradeAtCity::getTownId))
.values().stream()
.map(e -> e.stream()
.reduce((f1, f2) -> {
//logger.info("reduce, productID = {}, town = {}, date = {}", f1.getProductId(), f1.getTownCaption(), f1.getDate());
if (f1.getVolume() > f2.getVolume()) {
return f1;
} else {
return f2;
}
}))
.map(Optional::get)
.collect(Collectors.toList());
}
private static RetailTrend getWeighedRetailTrend(final List<TradeAtCity> tradeAtCityList) {
//данные по одному продукту на одну дату
final Date date = tradeAtCityList.get(0).getDate();
final double volume = tradeAtCityList.stream().mapToDouble(TradeAtCity::getVolume).sum();
//=SUMPRODUCT(A2:A3,B2:B3)/SUM(B2:B3)
final double localPrice = tradeAtCityList.stream()
.mapToDouble(tac -> tac.getLocalPrice() * tac.getVolume() / volume).sum();
final double localQuality = tradeAtCityList.stream()
.mapToDouble(tac -> tac.getLocalQuality() * tac.getVolume() / volume).sum();
final double shopPrice = tradeAtCityList.stream()
.mapToDouble(tac -> tac.getShopPrice() * tac.getVolume() / volume).sum();
final double shopQuality = tradeAtCityList.stream()
.mapToDouble(tac -> tac.getShopQuality() * tac.getVolume() / volume).sum();
return new RetailTrend(
Utils.round2(localPrice),
Utils.round2(localQuality),
Utils.round2(shopPrice),
Utils.round2(shopQuality),
date,
volume
);
}
private static void updateAllProductRemainTrends(final Git git, final String realm) throws IOException, GitAPIException {
final String baseDir = Utils.getDir() + Wizard.industry + File.separator + realm + File.separator;
logger.info("получаем список всех доступных товаров и материалов");
final List<Product> materials = ProductInitParser.getManufactureProducts(Wizard.host, realm);
logger.info("materials.size() = {}, realm = {}", materials.size(), realm);
for (int i = 0; i < materials.size(); i++) {
final StopWatch watch = new StopWatch();
watch.start();
final Product material = materials.get(i);
logger.info("realm = {}, {} / {} собираем данные о доступных товарах на оптовом рынке, {}", realm, i + 1, materials.size(), material.getCaption());
final Set<ProductRemain> set = RetailSalePrediction.getAllProductRemains(git, PRODUCT_REMAINS_ + material.getId(), realm, material.getId());
final String fileNamePath = baseDir + Wizard.product_remains_trends + File.separator + material.getId() + ".json";
Utils.writeToGsonZip(fileNamePath, getProductRemainTrends(new ArrayList<>(set)));
watch.stop();
logger.info("время выполнения: {}, записей сохранено: {}", watch.toString(), set.size());
}
logger.info("запоминаем дату обновления данных");
final DateFormat df = new SimpleDateFormat("dd.MM.yyyy");
Utils.writeToGson(baseDir + Wizard.product_remains_trends + File.separator + "updateDate.json", new UpdateDate(df.format(new Date())));
cacheProductRemain.clear();
}
private static List<ProductRemainTrend> getProductRemainTrends(final List<ProductRemain> list) {
return list.stream()
.collect(Collectors.groupingBy((pr) -> RetailTrend.dateFormat.format(pr.getDate())))
.values().stream()
.map(e -> getWeighedProductRemainTrend(groupByUnit(e)))
.sorted(Comparator.comparing(ProductRemainTrend::getDate))
.collect(Collectors.toList());
}
private static List<ProductRemain> groupByUnit(final List<ProductRemain> list) {
//проверяем что для одного продукта в одном подразделении только одна запись на дату
return list.stream()
.collect(Collectors.groupingBy(ProductRemain::getUnitID))
.values().stream()
.map(e -> e.stream()
.reduce((f1, f2) -> {
if (f1.getRemain() > f2.getRemain()) {
return f1;
} else {
return f2;
}
}))
.map(Optional::get)
.collect(Collectors.toList());
}
private static ProductRemainTrend getWeighedProductRemainTrend(final List<ProductRemain> productRemain) {
//данные по одному продукту на одну дату
final Date date = productRemain.get(0).getDate();
final List<ProductRemain> productRemainFiltered = productRemain.stream()
.filter(pr -> pr.getRemain() > 0)
.filter(pr -> pr.getRemain() != Long.MAX_VALUE)
.collect(Collectors.toList());
final double remain = productRemainFiltered.stream()
.mapToDouble(ProductRemain::getRemainByMaxOrderType)
.sum();
//=SUMPRODUCT(A2:A3,B2:B3)/SUM(B2:B3)
final double quality = productRemainFiltered.stream()
.mapToDouble(pr -> pr.getQuality() * pr.getRemainByMaxOrderType() / remain)
.sum();
final double price = productRemainFiltered.stream()
.mapToDouble(pr -> pr.getPrice() * pr.getRemainByMaxOrderType() / remain)
.sum();
//меньше 5% общего объема группируем в одну запись
final List<ProductRemain> productRemainOthersFiltered = productRemainFiltered.stream()
.filter(pr -> pr.getRemainByMaxOrderType() <= remain * 0.05)
.collect(Collectors.toList());
final double totalOthers = productRemainOthersFiltered.stream()
.mapToDouble(ProductRemain::getTotal)
.sum();
final double remainOthers = productRemainOthersFiltered.stream()
.mapToDouble(ProductRemain::getRemainByMaxOrderType)
.sum();
final double qualityOthers = productRemainOthersFiltered.stream()
.mapToDouble(pr -> pr.getQuality() * pr.getRemainByMaxOrderType() / remainOthers)
.sum();
final double priceOthers = productRemainOthersFiltered.stream()
.mapToDouble(pr -> pr.getPrice() * pr.getRemainByMaxOrderType() / remainOthers)
.sum();
final ProductRemainTrendSup others = new ProductRemainTrendSup("", ""
, totalOthers, remainOthers
, Utils.round2(qualityOthers), Utils.round2(priceOthers)
, ProductRemain.MaxOrderType.L, remainOthers);
final List<ProductRemainTrendSup> sup = productRemainFiltered.stream()
.filter(pr -> pr.getRemainByMaxOrderType() > remain * 0.05)
.map(pr -> new ProductRemainTrendSup(
pr.getCompanyName()
, pr.getUnitID()
, pr.getTotal()
, pr.getRemain()
, pr.getQuality()
, pr.getPrice()
, pr.getMaxOrderType()
, pr.getRemainByMaxOrderType()
))
.collect(Collectors.toList());
sup.add(others);
return new ProductRemainTrend(
remain,
Utils.round2(quality),
Utils.round2(price),
date,
sup
);
}
}
<file_sep>/src/main/java/ru/VirtaMarketAnalyzer/data/ManufactureIngredient.java
package ru.VirtaMarketAnalyzer.data;
import com.google.gson.annotations.SerializedName;
/**
* Created by cobr123 on 18.05.2015.
*/
final public class ManufactureIngredient {
@SerializedName("pi")
final private String productID;
@SerializedName("q")
final private Double qty;
@SerializedName("mq")
final private Double minQuality;
public ManufactureIngredient(final String productID, final Double qty,final Double minQuality) {
this.productID = productID;
this.qty = qty;
this.minQuality = minQuality;
}
public String getProductID() {
return productID;
}
public Double getQty() {
return qty;
}
public Double getMinQuality() {
return minQuality;
}
}
<file_sep>/src/main/java/ru/VirtaMarketAnalyzer/parser/ProductRemainParser.java
package ru.VirtaMarketAnalyzer.parser;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.VirtaMarketAnalyzer.data.Product;
import ru.VirtaMarketAnalyzer.data.ProductRemain;
import ru.VirtaMarketAnalyzer.main.Utils;
import ru.VirtaMarketAnalyzer.scrapper.Downloader;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.*;
import static java.util.stream.Collectors.groupingBy;
/**
* Created by cobr123 on 20.05.2015.
*/
public final class ProductRemainParser {
private static final Logger logger = LoggerFactory.getLogger(ProductRemainParser.class);
public static Map<String, List<ProductRemain>> getRemains(final String host, final String realm, final List<Product> materials) throws IOException {
return materials.parallelStream()
.map(material -> {
try {
return getRemains(host, realm, material);
} catch (final Exception e) {
logger.error(e.getLocalizedMessage(), e);
}
return null;
})
.filter(Objects::nonNull)
.flatMap(Collection::stream)
.collect(groupingBy(ProductRemain::getProductID));
}
public static List<ProductRemain> getRemains(final String host, final String realm, final Product material) throws Exception {
return Utils.repeatOnErr(() -> getRemains(host, realm, material, 1));
}
private static List<ProductRemain> getRemains(final String host, final String realm, final Product material, final int page) throws IOException {
// final String lang = (Wizard.host.equals(host) ? "ru" : "en");
final int pageSize = 10_000;
final String url = host + "api/" + realm + "/main/marketing/report/trade/offers?product_id=" + material.getId() + "&pagesize=" + pageSize + "&pagenum=" + page;
final List<ProductRemain> list = new ArrayList<>();
try {
final String json = Downloader.getJson(url);
final Gson gson = new Gson();
final Type mapType = new TypeToken<Map<String, Map<String, Object>>>() {
}.getType();
final Map<String, Map<String, Object>> infoAndDataMap = gson.fromJson(json, mapType);
final Map<String, Object> infoMap = infoAndDataMap.get("info");
final Map<String, Object> dataMap = infoAndDataMap.get("data");
for (final Map.Entry<String, Object> entry : dataMap.entrySet()) {
final Map<String, Object> city = (Map<String, Object>) entry.getValue();
final String productId = city.get("product_id").toString();
final String countryId = city.get("country_id").toString();
final String regionId = city.get("region_id").toString();
final String cityId = city.get("city_id").toString();
String companyName = "";
if (city.get("company_name") != null) {
companyName = city.get("company_name").toString();
}
final String unitID = city.get("unit_id").toString();
long total = 0;
if (city.get("quantity") != null) {
total = Long.parseLong(city.get("quantity").toString());
}
long remain = 0;
if (city.get("free_for_buy") != null) {
remain = Long.parseLong(city.get("free_for_buy").toString());
}
final double quality = Double.parseDouble(city.get("quality").toString());
double price = 0;
if (city.get("price") != null) {
price = Double.parseDouble(city.get("price").toString());
}
long maxOrder = 0;
if (city.get("max_qty") != null) {
maxOrder = Long.parseLong(city.get("max_qty").toString());
}
final ProductRemain.MaxOrderType maxOrderType = (maxOrder > 0) ? ProductRemain.MaxOrderType.L : ProductRemain.MaxOrderType.U;
list.add(new ProductRemain(productId, companyName, unitID, countryId, regionId, cityId, total, remain, quality, price, maxOrderType, maxOrder));
}
final int count = Utils.doubleToInt(Double.parseDouble(infoMap.get("count").toString()));
if (count > pageSize * page) {
list.addAll(getRemains(host, realm, material, page + 1));
}
} catch (final Exception e) {
Downloader.invalidateCache(url);
logger.error(url + "&format=debug");
throw e;
}
return list;
}
}
<file_sep>/src/main/java/ru/VirtaMarketAnalyzer/data/Product.java
package ru.VirtaMarketAnalyzer.data;
import com.google.gson.annotations.SerializedName;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
/**
* Created by cobr123 on 25.04.2015.
*/
public final class Product {
@SerializedName("pc")
final private String productCategory;
@SerializedName("pci")
final private String productCategoryID;
@SerializedName("s")
final private String imgUrl;
@SerializedName("i")
final private String id;
@SerializedName("c")
final private String caption;
@SerializedName("sym")
final private String symbol;
public Product(final String productCategory, final String id, final String caption, final String productCategoryID, final String symbol) {
this.productCategory = productCategory;
this.imgUrl = "/img/products/" + symbol + ".gif";
this.id = id;
this.caption = caption;
this.productCategoryID = productCategoryID;
this.symbol = symbol;
}
@Override
public int hashCode() {
return new HashCodeBuilder()
.append(productCategory)
.append(imgUrl)
.append(id)
.append(caption)
.append(productCategoryID)
.append(symbol)
.toHashCode();
}
@Override
public boolean equals(final Object obj) {
if (obj instanceof Product) {
final Product other = (Product) obj;
return new EqualsBuilder()
.append(productCategory, other.productCategory)
.append(imgUrl, other.imgUrl)
.append(id, other.id)
.append(caption, other.caption)
.append(productCategoryID, other.productCategoryID)
.append(symbol, other.symbol)
.isEquals();
} else {
return false;
}
}
public String getImgUrl() {
return imgUrl;
}
public String getId() {
return id;
}
public String getCaption() {
return caption;
}
public String getProductCategory() {
return productCategory;
}
public String getProductCategoryID() {
return productCategoryID;
}
public String getSymbol() {
return symbol;
}
}
<file_sep>/src/module-info.java
module ru.VirtaMarketAnalyzer {
requires java.base;
requires java.datatransfer;
requires java.desktop;
requires java.logging;
requires java.management;
requires java.naming;
requires java.rmi;
requires java.security.jgss;
requires java.sql;
requires log4j;
requires jsoup;
requires slf4j.api;
exports ru.VirtaMarketAnalyzer.main;
}
<file_sep>/src/main/java/ru/VirtaMarketAnalyzer/data/Region.java
package ru.VirtaMarketAnalyzer.data;
import com.google.gson.annotations.SerializedName;
/**
* Created by cobr123 on 25.04.2015.
*/
public final class Region {
@SerializedName("ci")
final private String countryId;
@SerializedName("i")
final private String id;
@SerializedName("c")
final private String caption;
@SerializedName("itr")
final private double incomeTaxRate;
public Region(final String countryId, final String id, final String caption, final double incomeTaxRate) {
this.countryId = countryId;
this.id = id;
this.caption = caption;
this.incomeTaxRate = incomeTaxRate;
}
public String getId() {
return id;
}
public String getCountryId() {
return countryId;
}
public String getCaption() {
return caption;
}
public double getIncomeTaxRate() {
return incomeTaxRate;
}
}
<file_sep>/src/test/java/ru/VirtaMarketAnalyzer/parser/ManufactureListParserTest.java
package ru.VirtaMarketAnalyzer.parser;
import org.junit.jupiter.api.Test;
import ru.VirtaMarketAnalyzer.data.Manufacture;
import ru.VirtaMarketAnalyzer.data.ProductRecipe;
import ru.VirtaMarketAnalyzer.main.Wizard;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertFalse;
class ManufactureListParserTest {
@Test
void getManufacturesTest() throws IOException {
final String realm = "olga";
final List<Manufacture> manufactures = ManufactureListParser.getManufactures(Wizard.host, realm);
assertFalse(manufactures.isEmpty());
final Map<String, List<ProductRecipe>> productRecipes = ProductRecipeParser.getProductRecipes(Wizard.host, realm, manufactures);
assertFalse(productRecipes.isEmpty());
}
}<file_sep>/src/main/java/ru/VirtaMarketAnalyzer/data/UnitType.java
package ru.VirtaMarketAnalyzer.data;
import com.google.gson.annotations.SerializedName;
import java.util.List;
/**
* Created by cobr123 on 25.02.16.
*/
public final class UnitType {
@SerializedName("i")
final private String id;
@SerializedName("c")
final private String caption;
@SerializedName("iu")
final private String imgUrl;
@SerializedName("s")
final private List<UnitTypeSpec> specializations;
public UnitType(final String id, final String caption, final String imgUrl, final List<UnitTypeSpec> specializations) {
this.id = id;
this.caption = caption;
this.imgUrl = imgUrl;
this.specializations = specializations;
}
public String getId() {
return id;
}
public String getCaption() {
return caption;
}
public String getImgUrl() {
return imgUrl;
}
public List<UnitTypeSpec> getSpecializations() {
return specializations;
}
public String getUnitTypeImgSrc() {
if (imgUrl.equalsIgnoreCase("/img/unit_types/restaurant.gif")) {
return imgUrl;
} else if (imgUrl.equalsIgnoreCase("/img/unit_types/repair.gif")) {
return imgUrl;
} else {
return "/img/unit_types/service_light.gif";
}
}
}
<file_sep>/src/main/java/ru/VirtaMarketAnalyzer/ml/LinearRegressionSummary.java
package ru.VirtaMarketAnalyzer.ml;
/**
* Created by cobr123 on 16.03.2017.
*/
public final class LinearRegressionSummary {
private final String productID;
private final double correlationCoefficient;
private final double meanAbsoluteError;
private final double rootMeanSquaredError;
private final double relativeAbsoluteError;
private final double rootRelativeSquaredError;
private final double numInstances;
public LinearRegressionSummary(String productID, double correlationCoefficient, double meanAbsoluteError, double rootMeanSquaredError, double relativeAbsoluteError, double rootRelativeSquaredError, double numInstances) {
this.productID = productID;
this.correlationCoefficient = correlationCoefficient;
this.meanAbsoluteError = meanAbsoluteError;
this.rootMeanSquaredError = rootMeanSquaredError;
this.relativeAbsoluteError = relativeAbsoluteError;
this.rootRelativeSquaredError = rootRelativeSquaredError;
this.numInstances = numInstances;
}
public String getProductID() {
return productID;
}
public double getCorrelationCoefficient() {
return correlationCoefficient;
}
public double getMeanAbsoluteError() {
return meanAbsoluteError;
}
public double getRootMeanSquaredError() {
return rootMeanSquaredError;
}
public double getRelativeAbsoluteError() {
return relativeAbsoluteError;
}
public double getRootRelativeSquaredError() {
return rootRelativeSquaredError;
}
public double getNumInstances() {
return numInstances;
}
}
<file_sep>/run_trend_update.sh
export dayOfMonth=$(date +%d)
export vma_github_remotepath=https://github.com/cobr123/cobr123.github.com.git
export vma_github_token=
export vma_login=
export vma_password=
rm -rf ./tmp/VirtaMarketAnalyzer/virtonomic*
java -Djava.util.Arrays.useLegacyMergeSort=true -Djava.net.preferIPv4Stack=true -Djava.io.tmpdir=./tmp -Xmx12G -Dfile.encoding=utf-8 -cp ./target/VirtaMarketAnalyzer-jar-with-dependencies.jar ru.VirtaMarketAnalyzer.main.TrendUpdater > ./logs/log_$dayOfMonth.txt 2> ./logs/log_err_$dayOfMonth.txt
<file_sep>/src/test/java/ru/VirtaMarketAnalyzer/parser/ProductRecipeParserTest.java
package ru.VirtaMarketAnalyzer.parser;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.VirtaMarketAnalyzer.data.Manufacture;
import ru.VirtaMarketAnalyzer.data.ProductRecipe;
import ru.VirtaMarketAnalyzer.main.Utils;
import ru.VirtaMarketAnalyzer.main.Wizard;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static java.util.stream.Collectors.toList;
import static org.junit.jupiter.api.Assertions.*;
class ProductRecipeParserTest {
private static final Logger logger = LoggerFactory.getLogger(ProductRecipeParserTest.class);
@Test
void getProductRecipesTest() throws IOException {
final String host = Wizard.host;
final String realm = "olga";
//Лекарственное пчеловодство
final Manufacture manufacture = ManufactureListParser.getManufacture(host, realm, "423140");
final List<Manufacture> manufactures = new ArrayList<>();
manufactures.add(manufacture);
final Map<String, List<ProductRecipe>> recipes = ProductRecipeParser.getProductRecipes(host, realm, manufactures);
assertEquals("Лекарственное пчеловодство", recipes.get("423153").get(0).getSpecialization());
assertEquals(0.3, recipes.get("423153").get(0).getInputProducts().stream().filter(p -> p.getProductID().equals("423139")).collect(toList()).get(0).getQty());
assertEquals(0.0, recipes.get("423153").get(0).getInputProducts().stream().filter(p -> p.getProductID().equals("423139")).collect(toList()).get(0).getMinQuality());
// 10 маточного молочка
assertEquals(10.0, recipes.get("423153").get(0).getResultProducts().stream().filter(p -> p.getProductID().equals("423153")).collect(toList()).get(0).getResultQty());
assertEquals(50.0, recipes.get("423153").get(0).getResultProducts().stream().filter(p -> p.getProductID().equals("423153")).collect(toList()).get(0).getProdBaseQty());
//Модификатор качества для маточного молочка 0%
assertEquals(0.0, recipes.get("423153").get(0).getResultProducts().stream().filter(p -> p.getProductID().equals("423153")).collect(toList()).get(0).getQualityBonusPercent());
// 15 меда
assertEquals(15.0, recipes.get("423153").get(0).getResultProducts().stream().filter(p -> p.getProductID().equals("423151")).collect(toList()).get(0).getResultQty());
assertEquals(75.0, recipes.get("423153").get(0).getResultProducts().stream().filter(p -> p.getProductID().equals("423151")).collect(toList()).get(0).getProdBaseQty());
//Модификатор качества для меда -20%
assertEquals(-20.0, recipes.get("423153").get(0).getResultProducts().stream().filter(p -> p.getProductID().equals("423151")).collect(toList()).get(0).getQualityBonusPercent());
assertEquals(1, recipes.get("423153").size());
assertEquals(5.0, recipes.get("423153").get(0).getEquipmentPerWorker());
assertEquals(0.1, recipes.get("423153").get(0).getEnergyConsumption());
assertEquals("423138", recipes.get("423153").get(0).getEquipment().getId());
assertEquals(1, recipes.get("423153").get(0).getInputProducts().size());
assertEquals(2, recipes.get("423153").get(0).getResultProducts().size());
assertEquals(1, recipes.get("423153").get(0).getResultProducts().stream().filter(p -> p.getProductID().equals("423153")).collect(toList()).size());
assertEquals(1, recipes.get("423153").get(0).getResultProducts().stream().filter(p -> p.getProductID().equals("423151")).collect(toList()).size());
assertFalse(Utils.getGson(recipes.get("423153")).isEmpty());
}
@Test
void getGsonTest() throws IOException {
final String host = Wizard.host;
final String realm = "olga";
final List<Manufacture> manufactures = ManufactureListParser.getManufactures(host, realm);
assertFalse(manufactures.isEmpty());
final Map<String, List<ProductRecipe>> productRecipes = ProductRecipeParser.getProductRecipes(host, realm, manufactures);
assertFalse(productRecipes.isEmpty());
for (final Map.Entry<String, List<ProductRecipe>> entry : productRecipes.entrySet()) {
try {
assertFalse(Utils.getGson(entry.getValue()).isEmpty());
} catch (final Exception e) {
final Gson gson = new GsonBuilder().serializeSpecialFloatingPointValues().create();
logger.error("entry.getKey = {}\n{}", entry.getKey(), gson.toJson(entry.getValue()));
throw e;
}
}
}
}<file_sep>/src/main/java/ru/VirtaMarketAnalyzer/data/Transport.java
package ru.VirtaMarketAnalyzer.data;
import com.google.gson.annotations.SerializedName;
/**
* Created by cobr123 on 29.06.2017.
*/
public final class Transport {
//в файл не выгружаем, т.к. id будет в имени файла
transient final private String productID;
@SerializedName("ci")
final private String cityToId;
@SerializedName("d")
final private int distance;
@SerializedName("do")
final private double deliverOne;
@SerializedName("mce")
final private double minCostExport;
@SerializedName("tce")
final private double totalCostExport;
@SerializedName("mci")
final private double minCostImport;
@SerializedName("tci")
final private double totalCostImport;
@SerializedName("i")
final private String imgSrc;
public Transport(final String cityToId, final String productID
, final int distance, final double deliverOne
, final double minCostExport, final double totalCostExport
, final double minCostImport, final double totalCostImport
, final String imgSrc) {
this.cityToId = cityToId;
this.productID = productID;
this.distance = distance;
this.deliverOne = deliverOne;
this.minCostExport = minCostExport;
this.totalCostExport = totalCostExport;
this.minCostImport = minCostImport;
this.totalCostImport = totalCostImport;
this.imgSrc = imgSrc;
}
public String getCityToId() {
return cityToId;
}
public String getProductID() {
return productID;
}
public int getDistance() {
return distance;
}
public double getDeliverOne() {
return deliverOne;
}
public double getMinCostExport() {
return minCostExport;
}
public double getTotalCostExport() {
return totalCostExport;
}
public double getMinCostImport() {
return minCostImport;
}
public double getTotalCostImport() {
return totalCostImport;
}
public String getImgSrc() {
return imgSrc;
}
}<file_sep>/src/main/java/ru/VirtaMarketAnalyzer/parser/ServiceGuideParser.java
package ru.VirtaMarketAnalyzer.parser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.VirtaMarketAnalyzer.data.*;
import ru.VirtaMarketAnalyzer.main.Utils;
import java.util.*;
import java.util.stream.Collectors;
/**
* Created by cobr123 on 17.02.2019.
*/
final public class ServiceGuideParser {
private static final Logger logger = LoggerFactory.getLogger(ServiceGuideParser.class);
/**
* Создает розничный гид по одной категории товаров для всех городов
*/
public static List<ServiceGuide> genServiceGuide(
final String host,
final String realm,
final UnitType serviceType
) throws Exception {
final List<City> cities = CityListParser.getCities(host, realm, false);
final List<Product> products = ProductInitParser.getServiceProducts(host, realm, serviceType);
final Map<String, List<ProductRemain>> productRemains = ProductRemainParser.getRemains(host, realm, products);
return cities.parallelStream()
.map(city -> {
try {
return genServiceGuide(host, realm, city, serviceType, products, productRemains);
} catch (Exception e) {
logger.error(e.getLocalizedMessage(), e);
}
return null;
})
.filter(Objects::nonNull)
.flatMap(Collection::stream)
.collect(Collectors.toList());
}
/**
* Создает розничный гид по одной категории товаров для одного города.
* Только если хотя бы один продукт прибыльный.
*/
public static List<ServiceGuide> genServiceGuide(
final String host,
final String realm,
final City city,
final UnitType serviceType,
final List<Product> products,
final Map<String, List<ProductRemain>> productRemains
) throws Exception {
final List<ServiceGuide> serviceGuides = new ArrayList<>();
final Set<String> tradingProductsId = products.stream().map(Product::getId).collect(Collectors.toSet());
final List<RentAtCity> rents = RentAtCityParser.getUnitTypeRent(host, realm, city.getId());
final ServiceAtCity stat = ServiceAtCityParser.get(host, realm, city, serviceType, null, tradingProductsId, rents);
for (final UnitTypeSpec unitTypeSpec : serviceType.getSpecializations()) {
final List<ServiceGuideProduct> serviceGuideProducts = new ArrayList<>();
for (final RawMaterial rawMaterial : unitTypeSpec.getRawMaterials()) {
serviceGuideProducts.add(genServiceGuideProduct(
host, realm, rawMaterial,
stat, stat.getRetailBySpec().get(unitTypeSpec.getCaption()).get(rawMaterial.getId()),
productRemains.getOrDefault(rawMaterial.getId(), new ArrayList<>())
));
}
final ServiceGuide serviceGuide = new ServiceGuide(host, realm, unitTypeSpec.getId(), city, serviceGuideProducts, Math.round(stat.getVolume() * 0.1));
if (serviceGuide.getIncomeAfterTaxSum() > 0) {
serviceGuides.add(serviceGuide);
}
}
return serviceGuides;
}
/**
* Считает прибыльность товара для одного города.
* Максимальный объем продаж 10% рынка.
*/
public static ServiceGuideProduct genServiceGuideProduct(
final String host,
final String realm,
final RawMaterial rawMaterial,
final ServiceAtCity stat,
final ServiceSpecRetail serviceSpecRetail,
final List<ProductRemain> productRemains
) throws Exception {
final List<String> suppliersUnitIds = new ArrayList<>();
final List<ProductRemain> productRemainsFiltered = productRemains.stream()
.filter(pr -> pr.getRemainByMaxOrderType() > 0 && pr.getQuality() >= serviceSpecRetail.getLocalQuality())
.sorted(Comparator.comparingDouble(o -> o.getPrice() / o.getQuality()))
.collect(Collectors.toList());
final long maxVolume = Math.round(stat.getVolume() * 0.1 * rawMaterial.getQuantity());
double quality = 0;
double buyPrice = 0;
long volume = 0;
for (final ProductRemain pr : productRemainsFiltered) {
suppliersUnitIds.add(pr.getUnitID());
final long maxProductRemainVolume = Math.min(pr.getRemainByMaxOrderType(), maxVolume - volume);
final double priceWithDuty = CountryDutyListParser.addDuty(host, realm, pr.getCountryId(), stat.getCountryId(), pr.getProductID(), pr.getPrice());
final double transportCost = Utils.repeatOnErr(() -> CountryDutyListParser.getTransportCost(host, realm, pr.getTownId(), stat.getTownId(), pr.getProductID()));
quality = merge(quality, volume, pr.getQuality(), maxProductRemainVolume);
buyPrice = merge(buyPrice, volume, priceWithDuty + transportCost, maxProductRemainVolume);
volume += maxProductRemainVolume;
if (volume >= maxVolume) {
break;
}
}
double sellPrice = serviceSpecRetail.getLocalPrice();
if (quality - 30.0 > serviceSpecRetail.getLocalQuality()) {
sellPrice = Utils.round2(serviceSpecRetail.getLocalPrice() * 2.5);
} else if (quality - 20.0 > serviceSpecRetail.getLocalQuality()) {
sellPrice = Utils.round2(serviceSpecRetail.getLocalPrice() * 2.0);
} else if (quality - 10.0 > serviceSpecRetail.getLocalQuality()) {
sellPrice = Utils.round2(serviceSpecRetail.getLocalPrice() * 1.5);
}
return new ServiceGuideProduct(rawMaterial.getId(), rawMaterial.getQuantity(), quality, buyPrice, sellPrice, volume, suppliersUnitIds);
}
private static double merge(double quality1, double volume1, double quality2, double volume2) {
return Utils.round2((quality1 * volume1) / (volume1 + volume2) + (quality2 * volume2) / (volume1 + volume2));
}
}
<file_sep>/src/test/java/ru/VirtaMarketAnalyzer/parser/TradeGuideParserTest.java
package ru.VirtaMarketAnalyzer.parser;
import org.junit.jupiter.api.Test;
import ru.VirtaMarketAnalyzer.data.*;
import ru.VirtaMarketAnalyzer.main.Wizard;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Created by cobr123 on 08.02.2019.
*/
public class TradeGuideParserTest {
@Test
void genTradeGuideTest() throws Exception {
final String realm = "olga";
final List<ProductCategory> productCategories = ProductInitParser.getTradeProductCategories(Wizard.host, realm);
final List<TradeGuide> tradeGuides = TradeGuideParser.genTradeGuide(Wizard.host, realm, productCategories.get(0));
assertFalse(tradeGuides.isEmpty());
assertTrue(tradeGuides.stream().anyMatch(l -> !l.getTradeGuideProduct().isEmpty()));
}
}
<file_sep>/src/test/java/ru/VirtaMarketAnalyzer/parser/CityInitParserTest.java
package ru.VirtaMarketAnalyzer.parser;
import org.junit.jupiter.api.Test;
import ru.VirtaMarketAnalyzer.data.Country;
import ru.VirtaMarketAnalyzer.data.Region;
import ru.VirtaMarketAnalyzer.main.Wizard;
import java.io.IOException;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
class CityInitParserTest {
@Test
void getRegionsTest() throws IOException {
final List<Region> list = CityInitParser.getRegions(Wizard.host, "olga");
assertFalse(list.isEmpty());
}
@Test
void getCountriesTest() throws IOException {
final List<Country> list = CityInitParser.getCountries(Wizard.host, "olga");
assertFalse(list.isEmpty());
}
}<file_sep>/src/main/java/ru/VirtaMarketAnalyzer/ml/js/ClassifierToJs.java
package ru.VirtaMarketAnalyzer.ml.js;
import com.yahoo.platform.yui.compressor.JavaScriptCompressor;
import org.apache.commons.io.FileUtils;
import org.apache.commons.text.WordUtils;
import org.mozilla.javascript.ErrorReporter;
import org.mozilla.javascript.EvaluatorException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.VirtaMarketAnalyzer.main.Utils;
import ru.VirtaMarketAnalyzer.ml.RetailSalePrediction;
import ru.VirtaMarketAnalyzer.publish.GitHubPublisher;
import weka.classifiers.Classifier;
import weka.classifiers.trees.J48;
import weka.classifiers.trees.j48.C45Split;
import weka.classifiers.trees.j48.ClassifierSplitModel;
import weka.classifiers.trees.j48.ClassifierTree;
import weka.core.Instances;
import java.io.*;
import java.lang.reflect.Field;
import java.nio.file.Files;
import java.nio.file.Paths;
/**
* Created by cobr123 on 19.01.2016.
*/
public final class ClassifierToJs {
private static final Logger logger = LoggerFactory.getLogger(ClassifierToJs.class);
private static long PRINT_ID = 0;
public static void main(String[] args) throws Exception {
final File file = new File(GitHubPublisher.localPath + RetailSalePrediction.predict_retail_sales + File.separator + "prediction_set_script.model");
final J48 tree = (J48) loadModel(file.getAbsolutePath());
final String path = file.getAbsolutePath().replace(".model", ".test.js");
FileUtils.writeStringToFile(new File(path), ClassifierToJs.compress(ClassifierToJs.toSource(tree, "predictCommonBySet")), "UTF-8");
}
public static Classifier loadModel(final String path) throws Exception {
try (final ObjectInputStream ois = new ObjectInputStream(Files.newInputStream(Paths.get(path)))) {
return (Classifier) ois.readObject();
}
}
public static void saveModel(final Classifier c, final String path) throws Exception {
Utils.mkdirs(path);
try (final ObjectOutputStream oos = new ObjectOutputStream(Files.newOutputStream(Paths.get(path)))) {
oos.writeObject(c);
oos.flush();
}
}
public static String compress(final String script) throws Exception {
final Reader in = new StringReader(script);
final JavaScriptCompressor compressor = new JavaScriptCompressor(in, new ErrorReporter() {
public void warning(String message, String sourceName,
int line, String lineSource, int lineOffset) {
logger.warn("\n[WARNING]");
if (line < 0) {
logger.warn(" " + message);
} else {
logger.warn(" " + line + ':' + lineOffset + ':' + message);
}
}
public void error(String message, String sourceName,
int line, String lineSource, int lineOffset) {
logger.error("[ERROR]");
if (line < 0) {
logger.error(" " + message);
} else {
logger.error(" " + line + ':' + lineOffset + ':' + message);
}
}
public EvaluatorException runtimeError(String message, String sourceName,
int line, String lineSource, int lineOffset) {
error(message, sourceName, line, lineSource, lineOffset);
return new EvaluatorException(message);
}
});
// Close the input stream first, and then open the output stream,
// in case the output file should override the input file.
in.close();
final StringWriter out = new StringWriter();
final int linebreak = 0;
final boolean munge = true;
final boolean verbose = true;
final boolean disableOptimizations = false;
final boolean preserveAllSemiColons = false;
compressor.compress(out, linebreak, munge, verbose, preserveAllSemiColons, disableOptimizations);
return out.toString();
}
public static String toSource(final J48 tree, final String prefix) throws Exception {
PRINT_ID = 0;
/** The decision tree */
final ClassifierTree m_root = (ClassifierTree) getPrivateFieldValue(tree.getClass(), tree, "m_root");
/** Local model at node. */
// final ClassifierSplitModel m_localModel = (ClassifierSplitModel) getPrivateFieldValue(m_root.getClass(), m_root, "m_localModel");
final StringBuilder[] source = toSourceClassifierTree(m_root, prefix);
final StringBuilder sb = new StringBuilder();
sb.append(" function getParamFor").append(WordUtils.capitalize(prefix)).append("(){\n");
sb.append(" param = [").append(RetailSalePrediction.ATTR.values().length - 1).append("];\n");
for (RetailSalePrediction.ATTR attr : RetailSalePrediction.ATTR.values()) {
//для последнего делаем вычисления, поэтому его в параметрах не должно быть
if (attr.ordinal() != RetailSalePrediction.ATTR.values().length - 1) {
sb.append(" param[");
sb.append(attr.ordinal());
sb.append("] = ");
sb.append(attr.getFunctionName());
sb.append("();\n");
}
}
sb.append(" return param;\n");
sb.append(" }\n");
sb.append(" function getValueFor").append(WordUtils.capitalize(prefix)).append("(idx){\n");
sb.append(" values = [];\n");
sb.append(" values[0] = 'менее 50';\n");
sb.append(" values[1] = 'около 50';\n");
int idx = 2;
for (final String number : RetailSalePrediction.numbers) {
for (final String word : RetailSalePrediction.words) {
sb.append(" values[").append(idx).append("] = '").append(word).append(" ").append(number).append("';\n");
++idx;
}
}
sb.append(" return values[idx];\n");
sb.append(" }\n");
return sb.toString()
+ " function " + prefix + "() {\n"
+ " i = getParamFor" + WordUtils.capitalize(prefix) + "();\n"
+ " p = " + prefix + "Classify(i);\n"
+ " return getValueFor" + WordUtils.capitalize(prefix) + "(p);\n"
+ " }\n"
+ " function " + prefix + "Classify(i) {\n"
+ " p = NaN;\n"
+ source[0] // Assignment code
+ " return p;\n"
+ " }\n"
+ source[1] // Support code
;
}
/**
* Returns source code for the tree as an if-then statement. The
* class is assigned to variable "p", and assumes the tested
* instance is named "i". The results are returned as two stringbuffers:
* a section of code for assignment of the class, and a section of
* code containing support code (eg: other support methods).
*
* @return an array containing two stringbuffers, the first string containing
* assignment code, and the second containing source for support code.
* @throws Exception if something goes wrong
*/
public static StringBuilder[] toSourceClassifierTree(final ClassifierTree m_root, final String prefix) throws Exception {
final StringBuilder[] result = new StringBuilder[2];
/** True if node is leaf. */
final boolean m_isLeaf = isLeaf(m_root);
/** Local model at node. */
final ClassifierSplitModel m_localModel = (ClassifierSplitModel) getPrivateFieldValue(m_root.getClass(), m_root, "m_localModel");
// logger.info(m_localModel.getClass().getName());
/** References to sons. */
final ClassifierTree[] m_sons = (ClassifierTree[]) getPrivateFieldValue(m_root.getClass(), m_root, "m_sons");
/** The training instances. */
final Instances m_train = (Instances) getPrivateFieldValue(m_root.getClass(), m_root, "m_train");
if (m_isLeaf) {
result[0] = new StringBuilder(" p = "
+ m_localModel.distribution().maxClass(0) + ";\n");
result[1] = new StringBuilder();
} else {
final StringBuilder text = new StringBuilder();
final StringBuilder atEnd = new StringBuilder();
//nextID
PRINT_ID++;
final long printID = PRINT_ID;
text.append(" function ").append(prefix).append("N").append(Integer.toHexString(m_localModel.hashCode())).append(printID)
.append("(i) {\n")
.append(" p = NaN;\n");
text.append(" if (")
.append(sourceExpression(m_localModel, -1, m_train))
.append(") {\n");
text.append(" p = ")
.append(m_localModel.distribution().maxClass(0))
.append(";\n");
text.append(" } ");
for (int i = 0; i < m_sons.length; i++) {
text.append("else if (").append(sourceExpression(m_localModel, i, m_train)).append(") {\n");
if (isLeaf(m_sons[i])) {
text.append(" p = ").append(m_localModel.distribution().maxClass(i)).append(";\n");
} else {
final StringBuilder[] sub = toSourceClassifierTree(m_sons[i], prefix);
text.append(sub[0]);
atEnd.append(sub[1]);
}
text.append(" } ");
if (i == m_sons.length - 1) {
text.append('\n');
}
}
text.append(" return p;\n }\n");
result[0] = new StringBuilder(" p = " + prefix + "N");
result[0].append(Integer.toHexString(m_localModel.hashCode())).append(printID)
.append("(i);\n");
result[1] = text.append(atEnd);
}
return result;
}
public static String sourceExpression(final ClassifierSplitModel m_localModel, final int index, final Instances data) throws Exception {
if (m_localModel instanceof C45Split) {
return sourceExpression((C45Split) m_localModel, index, data);
} else {
logger.error(m_localModel.getClass().getName());
throw new Exception("метод sourceExpression не реализован для класса \"" + m_localModel.getClass().getName() + "\"");
}
}
public static String sourceExpression(final C45Split m_localModel, final int index, final Instances data) throws Exception {
/** Attribute to split on. */
final int m_attIndex = (int) getPrivateFieldValue(m_localModel.getClass(), m_localModel, "m_attIndex");
/** Value of split point. */
final double m_splitPoint = (double) getPrivateFieldValue(m_localModel.getClass(), m_localModel, "m_splitPoint");
if (index < 0) {
return "i[" + m_attIndex + "] == null";
} else if (data.attribute(m_attIndex).isNominal()) {
return "i[" + m_attIndex + "]" + " === \"" + data.attribute(m_attIndex).value(index) + "\"";
} else {
final StringBuilder expr = new StringBuilder("(i[");
expr.append(m_attIndex).append("])");
if (index == 0) {
expr.append(" <= ").append(m_splitPoint);
} else {
expr.append(" > ").append(m_splitPoint);
}
return expr.toString();
}
}
public static boolean isLeaf(final ClassifierTree m_root) throws Exception {
return (boolean) getPrivateFieldValue(m_root.getClass(), m_root, "m_isLeaf");
}
//protected static метод нельзя вызвать
// public static long nextID(final Class clazz, final ClassifierTree ct) throws Exception {
// try {
// final Method retrieveItems = clazz.getDeclaredMethod("nextID");
// return (long) retrieveItems.invoke(clazz);//NoSuchMethodException
// } catch (final NoSuchMethodException e) {
// final Class superClass = clazz.getSuperclass();
// if (superClass == null) {
// throw e;
// } else {
// return nextID(superClass, ct);
// }
// }
// }
public static Object getPrivateFieldValue(final Class clazz, final Object obj, final String fieldName) throws Exception {
try {
final Field f = clazz.getDeclaredField(fieldName); //NoSuchFieldException
f.setAccessible(true);
return f.get(obj); //NoSuchFieldException
} catch (final NoSuchFieldException e) {
final Class superClass = clazz.getSuperclass();
if (superClass == null) {
throw e;
} else {
return getPrivateFieldValue(superClass, obj, fieldName);
}
}
}
}
|
c4db83132e5a5905a16e62d16db15f4d4c7f31fe
|
[
"Markdown",
"Java",
"Shell"
] | 38
|
Java
|
cobr123/VirtaMarketAnalyzer
|
c7094eb445198e738f71f365d90f817d75d00caf
|
98fa6f53e9c4b38a669c3cf757028bdafdf77761
|
refs/heads/master
|
<file_sep>"""Insert header Here"""
from pathlib import Path
from .kivytest import *
_PROJ_DESC = __doc__.split("\n")[0]
_PROJ_PATH = Path(__file__)
_PROJ_NAME = _PROJ_PATH.stem
_PROJ_VERSION = "0.0.1"
<file_sep>#===================================================================
# This file is auto generated by PackageIt
# Be careful to manually add modules as it might be over written.
# Check the [Project Import][ReWrite] settings in:
# packageit\packageit_testPypi.ini and
# D:\Dropbox\Projects\KivyTest\.packageit\packageit.ini
#===================================================================
termcolor
beetools
<file_sep>import setuptools
with open("README.rst", "r") as fh:
long_description = fh.read()
with open("requirements.txt", "r") as fh:
requirements = [line.strip() for line in fh]
setuptools.setup(
name="KivyTest",
version="0.0.1",
author="<NAME>",
author_email="<EMAIL>",
description="Insert project description here",
long_description=long_description,
long_description_content_type="text/x-rst",
classifiers=[
"Development Status :: 1 - Planning",
"Intended Audience :: Developers",
"Topic :: Software Development",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3.0",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
],
package_dir={"": "src"},
packages=setuptools.find_packages(where="src"),
python_requires=">=3.6",
install_requires=requirements,
)
<file_sep>"""Testing kivytest__init__()"""
from pathlib import Path
from beetools.beearchiver import Archiver
import kivytest
_PROJ_DESC = __doc__.split("\n")[0]
_PROJ_PATH = Path(__file__)
_PROJ_NAME = _PROJ_PATH.stem
_PROJ_VERSION = "0.0.1"
b_tls = Archiver(_PROJ_NAME, _PROJ_VERSION, _PROJ_DESC, _PROJ_PATH)
class TestKivyTest:
def test__init__(self, setup_env):
"""Assert class __init__"""
working_dir = setup_env
t_kivytest = kivytest.KivyTest(_PROJ_NAME, working_dir)
assert t_kivytest.success
pass
del b_tls
<file_sep>.. image:: https://img.shields.io/pypi/status/KivyTest
:alt: PyPI - Status
.. image:: https://img.shields.io/pypi/wheel/KivyTest
:alt: PyPI - Wheel
.. image:: https://img.shields.io/pypi/pyversions/KivyTest
:alt: PyPI - Python Version
.. image:: https://img.shields.io/github/v/release/hendrikdutoit/KivyTest
:alt: GitHub release (latest by date)
.. image:: https://img.shields.io/github/license/hendrikdutoit/KivyTest
:alt: License
.. image:: https://img.shields.io/github/issues-raw/hendrikdutoit/KivyTest
:alt: GitHub issues
.. image:: https://img.shields.io/pypi/dm/BEETest21
:alt: PyPI - Downloads
.. image:: https://img.shields.io/github/search/hendrikdutoit/KivyTest/GitHub hit
:alt: GitHub Searches
.. image:: https://img.shields.io/codecov/c/gh/hendrikdutoit/KivyTest
:alt: CodeCov
:target: https://app.codecov.io/gh/hendrikdutoit/KivyTest
.. image:: https://img.shields.io/github/workflow/status/hendrikdutoit/KivyTest/Pre-Commit
:alt: GitHub Actions - Pre-Commit
:target: https://github.com/hendrikdutoit/KivyTest/actions/workflows/pre-commit.yaml
.. image:: https://img.shields.io/github/workflow/status/hendrikdutoit/KivyTest/CI
:alt: GitHub Actions - CI
:target: https://github.com/hendrikdutoit/KivyTest/actions/workflows/ci.yaml
.. image:: https://img.shields.io/testpypi/v/KivyTest
:alt: PyPi
Project Short Description (default ini)
Project long description or extended summary goes in here (default ini)
=======
Testing
=======
This project uses ``pytest`` to run tests and also to test docstring examples.
Install the test dependencies.
.. code-block:: bash
$ pip install - r requirements_test.txt
Run the tests.
.. code-block:: bash
$ pytest tests
=== XXX passed in SSS seconds ===
==========
Developing
==========
This project uses ``black`` to format code and ``flake8`` for linting. We also support ``pre-commit`` to ensure these have been run. To configure your local environment please install these development dependencies and set up the commit hooks.
.. code-block:: bash
$ pip install black flake8 pre-commit
$ pre-commit install
=========
Releasing
=========
Releases are published automatically when a tag is pushed to GitHub.
.. code-block:: bash
# Set next version number
export RELEASE = x.x.x
# Create tags
git commit --allow -empty -m "Release $RELEASE"
git tag -a $RELEASE -m "Version $RELEASE"
# Push
git push upstream --tags
<file_sep>#===================================================================
# This file is auto generated by PackageIt
# Be careful to manually add modules as it might be over written.
# Check the [Project Import][ReWrite] settings in:
# packageit\packageit_testPypi.ini and
# D:\Dropbox\Projects\KivyTest\.packageit\packageit.ini
#===================================================================
pip
wheel
gitpython
pre-commit
pygithub
pytest
pytest-cov
termcolor
gitignore_parser
sphinx-autobuild
sphinx
black
beetools
configparserext
<file_sep>["tool.black"]
skip-string-normalization = true
<file_sep>"""Project Short Description (default ini)
Project long description or extended summary goes in here (default ini)
"""
import logging
from pathlib import Path
from termcolor import colored
from beetools.beearchiver import Archiver
_PROJ_DESC = __doc__.split("\n")[0]
_PROJ_PATH = Path(__file__)
_PROJ_NAME = _PROJ_PATH.stem
_PROJ_VERSION = "0.0.1"
class KivyTest:
"""Class short description one-liner goes here.
Class multi-liner detail description goes here.
"""
def __init__(self, p_project_name, p_dir, p_parent_log_name="", p_verbose=True):
"""Initialize the class
Parameters
----------
p_parent_log_name : str
Name of the parent. In combination witt he class name it will
form the logger name.
p_logger : bool, default = False
Activate the logger
p_verbose: bool, default = True
Write messages to the console.
Returns
-------
See Also
--------
Notes
-----
Examples
--------
"""
self.success = True
if p_parent_log_name:
self.log_name = "{}.{}".format(p_parent_log_name, _PROJ_NAME)
self.logger = logging.getLogger(self._log_name)
self.project_name = p_project_name
self.dir = p_dir
self.verbose = p_verbose
def method_1(self, p_msg):
"""Method short description one-liner goes here.
Class multi-liner detail description goes here.
Parameters
----------
Returns
-------
See Also
--------
Notes
-----
Examples
--------
"""
print(colored("Testing {}...".format(self.project_name), "yellow"))
print(colored("Message: {}".format(p_msg), "yellow"))
return True
def do_examples(p_cls=True):
"""A collection of implementation examples for KivyTest.
A collection of implementation examples for KivyTest. The examples
illustrate in a practical manner how to use the methods. Each example
show a different concept or implementation.
Parameters
----------
p_cls : bool, default = True
Clear the screen or not at startup of Archiver
Returns
-------
success : boolean
Execution status of the examples.
See Also
--------
Notes
-----
Examples
--------
"""
success = do_example1(p_cls)
success = do_example2(False) and success
return success
def do_example1(p_cls=True):
"""A working example of the implementation of KivyTest.
Example1 illustrate the following concepts:
1. Bla, bla, bla
2. Bla, bla, bla
Parameters
----------
p_cls : bool, default = True
Clear the screen or not at startup of Archiver
Returns
-------
success : boolean
Execution status of the example
See Also
--------
Notes
-----
Examples
--------
"""
success = True
archiver = Archiver(_PROJ_NAME, _PROJ_VERSION, _PROJ_DESC, _PROJ_PATH)
archiver.print_header(p_cls=p_cls)
t_kivytest = KivyTest(_PROJ_NAME)
t_kivytest.method_1("This is do_example1")
archiver.print_footer()
return success
def do_example2(p_cls=True):
"""Another working example of the implementation of KivyTest.
Example2 illustrate the following concepts:
1. Bla, bla, bla
2. Bla, bla, bla
Parameters
----------
p_cls : bool, default = True
Clear the screen or not at startup of Archiver
Returns
-------
success : boolean
Execution status of the method
See Also
--------
Notes
-----
Examples
--------
"""
success = True
archiver = Archiver(_PROJ_NAME, _PROJ_VERSION, _PROJ_DESC, _PROJ_PATH)
archiver.print_header(p_cls=p_cls)
t_kivytest = KivyTest(_PROJ_NAME)
t_kivytest.method_1("This is do_example2")
archiver.print_footer()
return success
if __name__ == "__main__":
do_examples()
<file_sep>"""Create a conftest.py
Define the fixture functions in this file to make them accessible across multiple test files.
"""
from pathlib import Path
import pytest
from beetools.beearchiver import Archiver
from beetools.beeutils import rm_tree
_PROJ_DESC = __doc__.split("\n")[0]
_PROJ_PATH = Path(__file__)
_PROJ_NAME = _PROJ_PATH.stem
_PROJ_VERSION = "0.0.1"
b_tls = Archiver(_PROJ_NAME, _PROJ_VERSION, _PROJ_DESC, _PROJ_PATH)
@pytest.fixture
def setup_env(tmp_path):
"""Setup the environment base structure"""
working_dir = tmp_path
yield working_dir
rm_tree(working_dir)
del b_tls
|
b3b3b7f97beb1b3dde860d836c8a5b7bd3b5e10a
|
[
"TOML",
"Python",
"Text",
"reStructuredText"
] | 9
|
Python
|
hendrikdutoit/KivyTest
|
3328e371a77215fd2fb7fa3f1e720baf0b39efe9
|
97586b9208ce44bee1a5838035219bd6f3e8bbda
|
refs/heads/master
|
<repo_name>alicjaotto/sitONchair_website<file_sep>/js/js.js
document.addEventListener("DOMContentLoaded", function(){
//znikanie podpisu przy najechaniu na obrazek
var image1 = document.querySelector(".first_img");
var image2 = document.querySelector(".second_img");
var title1 = image1.querySelector(".description");
var title2 = image2.querySelector(".description");
// console.log(image1);
// console.log(image2);
// console.log(title1);
// console.log(title2);
image1.addEventListener("mouseover", function(event){
title1.style.display="none";
});
image1.addEventListener("mouseout", function(event) {
title1.style.display="block";
});
image2.addEventListener("mouseover", function(event){
title2.style.display="none";
});
image2.addEventListener("mouseout", function(event) {
title2.style.display="block";
});
//slider
var slides = document.querySelectorAll(".slider_ul .slide");
var currentSlide = 0;
// var slideInterval = setInterval(nextSlide, 3000);
var arrows = document.querySelectorAll(".arrows .highlighted"); //tablica
// console.log(arrows);
var arrowForward = arrows[1];
// console.log(arrowForward);
var arrowBackward = arrows[0];
// console.log(arrowBackward);
timeInterval = setInterval(nextSlide, 3000);
function nextSlide() {
slides[currentSlide].className = 'slide';
currentSlide = (currentSlide+1)%slides.length;
slides[currentSlide].className = 'slide showing';
}
nextSlide();
arrowBackward.addEventListener("click", function(event){
slides[currentSlide].className = 'slide';
currentSlide = (currentSlide-1)%slides.length;
if (currentSlide < 0) {
currentSlide=0;
}
slides[currentSlide].className = 'slide showing';
});
arrowForward.addEventListener("click", function(event){
slides[currentSlide].className = 'slide';
currentSlide = (currentSlide+1)%slides.length;
slides[currentSlide].className = 'slide showing';
});
//form validator
var form = document.querySelector("form");
// console.log(form);
var errorDiv = document.querySelector(".error-message");
var successDiv = document.querySelector(".success-message");
var name = document.getElementById("name");
var email = document.getElementById("email");
var textarea = document.getElementById("message");
var checkbox = document.getElementById("checkbox");
// console.log(name);
// console.log(email);
// console.log(textarea);
// console.log(checkbox);
form.addEventListener("submit", function(event) {
event.preventDefault();
var formValidation = true;
var allErrors = [];
errorDiv.innerText = "";
if (email.value. indexOf("@") < 0 ) {
allErrors.push("There should be '@' in your email address!");
formValidation = false;
}
if (name.value.length < 1) {
allErrors.push("You have to write your name!");
formValidation = false;
}
if (textarea.value.length < 10) {
allErrors.push("We do not accept empty messages!");
formValidation = false;
}
if(checkbox.checked === false) {
allErrors.push("You have to agree for terms and conditions!");
formValidation = false;
}
if (formValidation === true) {
successDiv.innerText = "Your message was succesfully sent!";
setTimeout(function() {
form.submit();
}, 2000);
} else {
for (var i=0; i<allErrors.length; i++) {
var p = document.createElement("p");
p.innerText = allErrors[i];
errorDiv.appendChild(p);
}
}
});
//application
//variables in dropdown lists
var models = document.querySelectorAll(".models li"); //array
console.log(models);
var colors = document.querySelectorAll(".colors li"); //array
var fabrics = document.querySelectorAll(".fabrics li"); //array
console.log(fabrics);
var listArrows = document.querySelectorAll(".list_arrow"); //array
console.log(listArrows);
var listPanels = document.querySelectorAll(".list_panel"); //array
console.log(listPanels[0]);
var listLabels = document.querySelectorAll(".list_label");
//variables in the summary
var modelsPrice = 0;
var fabricsPrice = 0;
var colorsPrice = 0;
var sum = 0;
var total = document.querySelector(".sum strong");
total.innerText = sum +"$";
var showModel = document.querySelector(".panel_left > h4");
var showColor = document.querySelector(".color");
var showFabric = document.querySelector(".pattern");
var showModelPrice = document.querySelector(".panel_right > h4");
var showColorPrice = document.querySelector(".color_value");
var showFabricPrice = document.querySelector(".pattern_value");
//events in models list
listArrows[0].addEventListener("click", function(event) {
listPanels[0].classList.toggle("show");
});
for (var i=0; i<models.length; i++) {
models[i].addEventListener("click", function(event) {
listLabels[0].innerText=this.innerText;
showModel.innerText=this.innerText;
showModelPrice.innerText = this.dataset.price;
modelsPrice = Number(this.dataset.price);
sum += modelsPrice;
total.innerText = sum+"$";
});
}
//events in colors list
listArrows[1].addEventListener("click", function(event) {
listPanels[1].classList.toggle("show");
});
for (var i=0; i<colors.length; i++) {
colors[i].addEventListener("click", function(event) {
listLabels[1].innerText=this.innerText;
showColor.innerText=this.innerText;
showColorPrice.innerText = this.dataset.price;
colorsPrice = Number(this.dataset.price);
sum += colorsPrice;
total.innerText = sum+"$";
});
}
//events in fabrics list
listArrows[2].addEventListener("click", function(event) {
listPanels[2].classList.toggle("show");
});
for (var i=0; i<fabrics.length; i++) {
fabrics[i].addEventListener("click", function(event) {
listLabels[2].innerText=this.innerText;
showFabric.innerText=this.innerText;
showFabricPrice.innerText = this.dataset.price;
fabricsPrice = Number(this.dataset.price);
sum += fabricsPrice;
total.innerText = sum+"$";
});
}
//events in transport checkbox
var checkbox = document.getElementById("transport");
// console.log(checkbox);
var showTransport = document.querySelector(".transport");
// console.log(showTransport);
var showTransportPrice = document.querySelector(".transport_value");
// console.log(showTransportPrice);
var transportPrice = 0;
checkbox.addEventListener("change", function(event) {
transportPrice = Number(checkbox.dataset.transportprice);
if (checkbox.checked) {
showTransport.innerText = "Shipping";
showTransportPrice.innerText = checkbox.dataset.transportprice;
sum += transportPrice ;
} else {
showTransport.innerText = "";
showTransportPrice.innerText = "";
sum -= transportPrice ;
}
total.innerText = sum +"$";
});
});
<file_sep>/README.md
My first serious training project based on given jpg layout.
technologies: HTML5 + CSS3 + JavaScript
existing JavaScript features:
* photo carousel
* chair creator
* price calculator
link: https://alicjaotto.github.io/sitONchair_website/
|
2568e043b7253a17ab366c165394e104fec73fab
|
[
"JavaScript",
"Markdown"
] | 2
|
JavaScript
|
alicjaotto/sitONchair_website
|
0d2e8cc31a5ddb561737f04a10facf5e0169128d
|
7d2e7b0cbb949f12f624cc0428aeeee5e2d7f9bd
|
refs/heads/master
|
<file_sep>using NUnit.Framework;
using System;
using WorkQuest_One;
namespace UnitTest
{
public class Tests
{
GeometyCalcAPI api;
[SetUp]
public void Setup()
{
api = new GeometyCalcAPI();
}
/// <summary>
/// Тестирование расчета площади круга
/// </summary>
[Test]
public void circleSquareTestRad1_true()
{
if (api.getSquareOfCircle(1) == Math.PI)
{
Assert.Pass();
}
else
{
Assert.Fail();
}
}
/// <summary>
/// Тестирование расчета площади круга
/// </summary>
[Test]
public void circleSquareTestRad2_false()
{
if (api.getSquareOfCircle(2) != Math.PI)
{
Assert.Pass();
}
else
{
Assert.Fail();
}
}
/// <summary>
/// Тестирование расчета площади круга
/// </summary>
[Test]
public void circleSquareTestRad5_true()
{
if (api.getSquareOfCircle(5) == 25*Math.PI)
{
Assert.Pass();
}
else
{
Assert.Fail();
}
}
/// <summary>
/// Тестирование расчета площади круга
/// </summary>
[Test]
public void circleSquareTestRad_minus_1_error()
{
if (api.getSquareOfCircle(-1) != Math.PI)
{
Assert.Pass();
}
else
{
Assert.Fail();
}
}
/// <summary>
/// Тестирование расчета площади треугольника
/// </summary>
[Test]
public void triangleSquareTest_1_1_1_true()
{
if (Math.Round(api.getSquareOfTriangle(1,1,1),3)==0.433)
{
Assert.Pass();
}
else
{
Assert.Fail();
}
}
/// <summary>
/// Тестирование расчета площади треугольника
/// </summary>
[Test]
public void triangleSquareTest_2_2_1_false()
{
if (Math.Round(api.getSquareOfTriangle(2, 2, 1), 3) != 2)
{
Assert.Pass();
}
else
{
Assert.Fail();
}
}
/// <summary>
/// Тестирование расчета площади треугольника
/// </summary>
[Test]
public void triangleSquareTest_minus_1_all_true()
{
if (Math.Round(api.getSquareOfTriangle(-1, -1, -1), 3) == -1)
{
Assert.Pass();
}
else
{
Assert.Fail();
}
}
}
}<file_sep>using System;
namespace WorkQuest_One
{
public class GeometyCalcAPI
{
/// <summary>
/// Вычислить площадь круга по радиусу
/// </summary>
/// <param name="radius">Радиус круга</param>
/// <returns></returns>
public double getSquareOfCircle(double radius)
{
if (radius >= 0)
return Math.PI * (radius * radius);
else return -1;
}
/// <summary>
/// Вычислить площадь треугольника по 3 сторонам
/// </summary>
/// <param name="a">1 сторона</param>
/// <param name="b">2 сторона</param>
/// <param name="c">3 сторона</param>
/// <returns></returns>
public double getSquareOfTriangle(double a, double b, double c)
{
if (a >= 0 && b >= 0 && c >= 0)
{
double p = getTrianglePerimetr(a, b, c);
return Math.Sqrt(p * ((p - a) * (p - b) * (p - c)));
}else
{
return -1;
}
}
/// <summary>
/// Является ли треуогольник прямоугольным
/// </summary>
/// <param name="a">1 сторона</param>
/// <param name="b">2 сторона</param>
/// <param name="c">3 сторона</param>
/// <returns></returns>
public bool isTriangleIsIsosceles(double a, double b, double c)
{
if (a >= 0 && b >= 0 && c >= 0)
{
if ((a * a + b * b) == c * c)
{
return true;
}
else return false;
}return false;
}
private double getTrianglePerimetr(double a, double b, double c)
{
return (a + b + c) / 2;
}
}
}
|
5c3aceaf901a63300ea98431acc92cdeae14b370
|
[
"C#"
] | 2
|
C#
|
FaceEs/WorkQuest_One
|
fa3fdf730a3be8b061f272764c08a9c27c12d83c
|
0de382385d6550fd10cf35cad3ce3903ed8da2e9
|
refs/heads/master
|
<file_sep>#lib/introduction.RUBY_VERSION
def "introduction"(name)
puts "Hi, my name is {name}."end
|
48cfd1d24d0038438309348acb61ba15aa867904
|
[
"Ruby"
] | 1
|
Ruby
|
jordangekko/method-arguments-lab-online-web-prework
|
ddd7c4623491d909df7f7e107352dbd2f3a18bb0
|
3157136fee6df0eeba9cceafaf4b458c56b48656
|
refs/heads/main
|
<file_sep># Makeless - Storage Amazon S3
Makeless - SaaS Framework - Golang Storage Amazon S3 Implementation
[](https://cloud.drone.io/makeless/makeless-go-storage-amazon-s3)
<file_sep>module github.com/makeless/makeless-go-storage-amazon-s3
go 1.15
require (
github.com/aws/aws-sdk-go v1.38.2
github.com/h2non/filetype v1.1.1 // indirect
)
<file_sep>package makeless_go_storage_amazon_s3
import (
"bytes"
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/aws/aws-sdk-go/service/s3/s3manager"
"github.com/h2non/filetype"
"github.com/h2non/filetype/types"
"sync"
)
type Storage struct {
Bucket string
Config aws.Config
session *session.Session
*sync.RWMutex
}
func (storage *Storage) GetBucket() string {
storage.RLock()
defer storage.RUnlock()
return storage.Bucket
}
func (storage *Storage) GetConfig() aws.Config {
storage.RLock()
defer storage.RUnlock()
return storage.Config
}
func (storage *Storage) GetSession() *session.Session {
storage.RLock()
defer storage.RUnlock()
return storage.session
}
func (storage *Storage) setSession(session *session.Session) {
storage.Lock()
defer storage.Unlock()
storage.session = session
}
func (storage *Storage) Init() error {
sess := session.Must(session.NewSessionWithOptions(session.Options{
Config: storage.GetConfig(),
}))
storage.setSession(sess)
return nil
}
func (storage *Storage) Write(filepath string, data []byte) error {
var err error
var fileType types.Type
var uploader = s3manager.NewUploader(storage.GetSession())
if fileType, err = filetype.Match(data); err != nil {
return err
}
if fileType == filetype.Unknown {
return fmt.Errorf("unknown file type")
}
if _, err := uploader.Upload(&s3manager.UploadInput{
Bucket: aws.String(storage.GetBucket()),
Key: aws.String(filepath),
Body: bytes.NewReader(data),
ContentType: aws.String(fileType.MIME.Value),
}); err != nil {
return err
}
return nil
}
func (storage *Storage) Read(filepath string) ([]byte, error) {
var downloader = s3manager.NewDownloader(storage.GetSession())
var buf = new(aws.WriteAtBuffer)
if _, err := downloader.Download(
buf,
&s3.GetObjectInput{
Bucket: aws.String(storage.GetBucket()),
Key: aws.String(filepath),
},
); err != nil {
return nil, err
}
return nil, nil
}
func (storage *Storage) Exists(filepath string) (bool, error) {
_, err := s3.New(storage.GetSession()).HeadObject(&s3.HeadObjectInput{
Bucket: aws.String(storage.GetBucket()),
Key: aws.String(filepath),
})
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case "NotFound":
return false, nil
default:
return false, err
}
}
return false, err
}
return true, nil
}
func (storage *Storage) Remove(filepath string) error {
return fmt.Errorf("remove not supported yet")
}
|
1fdfb67da85e292d2a97b1bf35cfbf17022f44ab
|
[
"Markdown",
"Go Module",
"Go"
] | 3
|
Markdown
|
makeless/makeless-go-storage-amazon-s3
|
ef0361cfe47be215747b20640ac21c77d2a5a108
|
8389cce54fb26b20de04a1836dab2152c0ebd89c
|
refs/heads/master
|
<file_sep># Timeline
* [Timeline horizontal demo](./timeline-proto/timeline-horizontal.html)
* [Timeline vertical demo](./timeline-proto/timeline-vertical.html)
<file_sep># Timeline prototype
This folder holds a prototype of the timeline for testing purposes.
<file_sep>/**
* Loads the data from airtable into an <ol id="timeline"> element.
*/
function fetchParams () {
const reduceParams = (memo, param) => {
const [key, val] = param.split('=');
memo[key] = val;
return memo;
}
const params = window.location.search && window.location.search.substring(1).split('&').reduce(reduceParams, {});
const url = `https://api.airtable.com/v0/${params.table}`;
const opts = { headers: { authorization: `Bearer ${params.token}` } };
return [url, opts];
}
function sortByOrder (a, b) {
return a.fields.Order - b.fields.Order;
}
function formatItem (record) {
const {
Title: title,
Description: description,
Location: location,
Date: date,
Link: link
} = record.fields;
return `
<li>
<div>
<time>${date}</time>
<h4>${title}</h4>
<p>${description}</p>
<a href="${link}" target="_blank">Learn more</a>
</div>
</li>
`;
}
function appendTimeline ({ records }) {
const timelineElement = document.getElementById("timeline-ordered-list");
let markup = `<li><h4>Timeline data is missing.</h4></li>`;
if (records.length) {
markup = records.sort(sortByOrder).map(formatItem).join('');
}
timelineElement.innerHTML = markup;
applyScrolling();
}
(function () {
const args = fetchParams();
return fetch(...args).then(res => res.json()).then(appendTimeline);
}());
<file_sep># P4TP-Timeline
Timeline project for People for the People project.
View the prototype at https://bgmapp.github.io/P4TP-Timeline/
|
329509699882bbb689d9ff1960bbec0bba4405cb
|
[
"Markdown",
"JavaScript"
] | 4
|
Markdown
|
davidasbury/P4TP-Timeline
|
07395b41aad7d2d4de369beea00e37d013f92c6a
|
6c2525e0167e98d013ca24b75f69773595c0afa8
|
refs/heads/master
|
<file_sep>#!/usr/bin/env ruby
require 'clamp'
require_relative '../lib/project_mod'
require_relative '../lib/command/fix_quick_command'
require_relative '../lib/command/swift_version_command'
require_relative '../lib/command/inhibit_all_warnings_command'
require_relative '../lib/command/clean_project_command'
require_relative '../lib/version'
class MainCommand < Clamp::Command
subcommand 'fix_quick', 'Fix Quick\'s problem with SPM until it\'s resolved. See: https://github.com/Quick/Quick/issues/751', FixQuickCommand
subcommand 'swift', 'Change Swift version of a target/targets', SwiftVersionCommand
subcommand 'inhibit_all_warnings', 'Inhibit all warninigs in a target/targets', InhibitAllWarningsCommand
subcommand 'clean_project', 'Remove .build dir, Package.resolved & packages cache', CleanProjectCommand
option "--version", :flag, "Show version" do
puts SPMFixers::VERSION
exit(0)
end
end
MainCommand.run
<file_sep>require 'xcodeproj'
class ProjectMod
def self.xcodeproject(path:)
xcodeprojs = Dir.new(path).select { |a| a.include? '.xcodeproj' }
xcodeprojs_count = xcodeprojs.count
abort "No *.xcodeproj files in current directory" if xcodeprojs_count == 0
abort "Found #{xcodeprojs_count} .xcodeproj files in the directory (1 required)." if xcodeprojs_count > 1
Xcodeproj::Project.open(xcodeprojs[0])
end
def self.get_targets(project:,target_names:)
targets = project.targets.clone
if !target_names.empty?
not_found_targets = target_names.select { |t| !targets.map { |tt| tt.name }.include? t }
abort not_found_targets.join(", ") + " targets were not found in the Xcodeproj." if !not_found_targets.empty?
targets.select! { |t| target_names.include? t.name }
end
abort "No targets selected" if targets.empty?
return targets
end
def self.apply_build_setting(name:, value:, target_names: [])
project = xcodeproject(path: Dir.pwd)
targets = get_targets(project: project, target_names: target_names)
targets.each do |target|
target.build_configurations.each do |config|
config.build_settings[name] = value
end
end
project.save
end
def self.append_or_apply_build_setting(name:, value:, target_names: [])
project = xcodeproject(path: Dir.pwd)
targets = get_targets(project: project, target_names: target_names)
targets.each do |target|
target.build_configurations.each do |config|
if config.build_settings[name].nil?
config.build_settings[name] = value
else
config.build_settings[name] += " #{value}"
end
end
end
project.save
end
end
<file_sep>class FixQuickCommand < Clamp::Command
def execute
ProjectMod.apply_build_setting(name: 'CLANG_ENABLE_MODULES', value: 'YES', target_names: ['QuickSpecBase'])
puts "Quick fixed!"
end
end
<file_sep># SPM utils
Hey there! This is a repo with a bunch of utility scripts for SPM compiled to a ruby gem. I really like working with SPM nowadays, but I needed to automate some things that I could reuse both on my local computer and also on the CI - maybe you want to use them too!
If you have an idea for a cool fixer/utility - don't hesitate to file and issue or make a PR!
## Current functionalities:
1. [Clean your project (remove cache, builds, xcodeproj etc)](#cleaning-your-project)
1. [Fix Quick on SPM](#quick-fixer)
1. [Update Swift version in given target or all targets](#swift-version---update-your-targets-to-swift-3-or-4)
1. [Inhibit all warnings in given target or all targets](#inhibit-warnings)
## Before you use the script:
1. Go to your SPM project.
1. Backup/commit your files.
1. Clean your project if needed.
1. Run `swift package generate-xcodeproj` (make sure it passes)
1. Install this gem using `gem install spm_utils`
## Cleaning your project
Whenever something goes wrong with building/caching/resolving, try cleaning your project:
```bash
spm_utils clean_project
```
## Quick fixer
See issue [Quick#751](https://github.com/Quick/Quick/issues/751) and PR [swift-package-manager#955](https://github.com/apple/swift-package-manager/pull/955). TL;DR because of SPM, Quick can't set `CLANG_ENABLE_MODULES` by itself.
This script automates it for you:
```bash
spm_utils fix_quick
```
## Swift version - update your targets to Swift 3 or 4
By running `swift package generate-xcodeproj` you don't necessarily get all your targets built with Swift 4 (see [SR-5940](https://bugs.swift.org/browse/SR-5940)). You might also want to change one of the targets to use Swift 3 or 4. This script fixes that for you!
### To update all targets to use Swift 3:
```bash
spm_utils swift 3.0
```
### To update all targets to use Swift 4:
```bash
spm_utils swift 4.0
```
### To update all targets to use Swift 4.2:
```bash
spm_utils swift 4.2
```
### To update few targets to use Swift 4.2:
```bash
spm_utils swift --target Quick --target Nimble 4.2
```
## Inhibit warnings
In [CocoaPods](https://cocoapods.org) there is an option to hide your dependencies warnings. This basically does the same thing.
### To inhibit warnings for all targets
```bash
spm_utils inhibit_all_warnings
```
### To inhibit warnings for only one target
```bash
spm_utils inhibit_all_warnings --target Nimble
```
### To inhibit warnings for multiple targets
```bash
spm_utils inhibit_all_warnings --target Nimble --target Moya
```
## License
[MIT](https://github.com/sunshinejr/spm_fixers/blob/master/LICENSE).
<file_sep>class CleanProjectCommand < Clamp::Command
def execute
system "swift package clean && rm -rf .build && rm Package.resolved &> /dev/null"
puts "All things cleaned! Now to the good stuff..."
end
end<file_sep>class InhibitAllWarningsCommand < Clamp::Command
option ['--target'], 'TARGET', 'Target name', :multivalued => true
def execute
ProjectMod.append_or_apply_build_setting(name: 'OTHER_SWIFT_FLAGS', value: "-suppress-warnings", target_names: target_list)
targets_string = target_list.empty? ? 'All targets' : (target_list.join(", ") + " targets")
puts "#{targets_string} have inhibited warnings now!"
end
end<file_sep>class SwiftVersionCommand < Clamp::Command
parameter "VERSION", "version", :attribute_name => :swift_version
option ['--target'], 'TARGET', 'Target name', :multivalued => true
# option ['--swift-version'], 'SWIFT_VERSION', 'What Swift version to change into', :required => true
def execute
supported_swift_versions = ['3.0', '4.0', '4.2']
if !supported_swift_versions.include? swift_version
signal_usage_error "'#{swift_version}' swift version is not supported. Supported values: " + supported_swift_versions.map { |v| "'#{v}'" }.join(", ")
end
ProjectMod.apply_build_setting(name: 'SWIFT_VERSION', value: "#{swift_version}.0", target_names: target_list)
targets_string = target_list.empty? ? 'All targets' : (target_list.join(", ") + " targets")
puts "#{targets_string} were updated to use Swift #{swift_version}!"
end
end
|
7f6b7f9a3ecbd69812ba58bfa4157d8a570f3430
|
[
"Markdown",
"Ruby"
] | 7
|
Ruby
|
sunshinejr/spm_utils
|
5e36718f4f40751ec1f8585d93a2f740689c7bf2
|
4e1b44aab1878b7ed8e4f47e4d292fa6ec636394
|
refs/heads/master
|
<repo_name>junzulkarnain/news<file_sep>/logout.php
<?php
session_start();
if(session_destroy()){
?>
<script>
alert('Logout Success');
window.location.href="login.php";
</script>
<?php
}
?><file_sep>/page/grafik/grafik.php
<div class="container-fluid">
<!-- Breadcrumbs-->
<ol class="breadcrumb">
<li class="breadcrumb-item">
<a href="?page=dashboard">Dashboard</a>
</li>
<li class="breadcrumb-item active">Grafik</li>
</ol>
<!-- Page Content -->
<div id="container" style="min-width: 310px; height: 400px; max-width: 600px; margin: 0 auto"></div>
<?php
$query = mysqli_query($db,"SELECT tbl_master_kategori.nama_kategori, COUNT(tbl_artikel.id_artikel) AS jumlah FROM tbl_artikel LEFT JOIN tbl_master_kategori ON tbl_master_kategori.id_kategori=tbl_artikel.kategori GROUP BY tbl_artikel.kategori ");
while ($row = mysqli_fetch_assoc($query)){
$arrayData[] = "["."'".$row['nama_kategori']."'".",".$row['jumlah']."]";
}
?>
</div>
</div>
<script src="js/highcharts/highcharts.js"></script>
<script src="js/highcharts/exporting.js"></script>
<script src="js/highcharts/export-data.js"></script>
<script type="text/javascript">
Highcharts.chart('container', {
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
type: 'pie'
},
title: {
text: 'Persentase jumlah Artikel/Kategori'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{point.name}</b>: {point.percentage:.1f} %'
}
}
},
series: [{
name: 'Jumlah',
colorByPoint: true,
data: [<?= join($arrayData,",")?>],
}]
});
</script>
<file_sep>/page/user/form_tambah_user.php
<div class="container-fluid">
<!-- Breadcrumbs-->
<ol class="breadcrumb">
<li class="breadcrumb-item">
<a href="index.html">Artikel</a>
</li>
<li class="breadcrumb-item active">Form Tambah Artikel</li>
</ol>
<!-- Page Content -->
<h1>Tambah Artikel</h1>
<hr>
<form class="form-horizontal" action="" method="POST">
<div class="form-group">
<label class="control-label col-sm-2">ID Artikel:</label>
<div class="col-sm-12">
<input type="text" class="form-control" name="id_artikel" placeholder="Enter ID Artikel">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Judul:</label>
<div class="col-sm-12">
<input type="text" class="form-control" placeholder="Masukan Judul" name="judul">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Penulis:</label>
<div class="col-sm-12">
<input type="text" class="form-control" placeholder="Masukan Penulis" name="penulis">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Tanggal:</label>
<div class="col-sm-12">
<input type="date" class="form-control" name="tanggal">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Isi:</label>
<div class="col-sm-12">
<textarea name="isi" class="form-control"></textarea>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-primary" name="simpan">Simpan</button>
</div>
</div>
</form>
</div>
<?php
@$id = $_POST['id_artikel'];
@$judul = $_POST['judul'];
@$penulis = $_POST['penulis'];
@$isi = $_POST['isi'];
@$tanggal = $_POST['tanggal'];
@$simpan = $_POST['simpan'];
if (isset($simpan )) {
mysqli_query($db,"INSERT INTO artikel (id_artikel, judul,penulis, tanggal, isi) VALUES ('$id', '$judul', '$penulis', '$tanggal', '$isi')");
}
?><file_sep>/login_aksi.php
<?php
include "koneksi.php";
@$username = $_POST['username'];
@$password = $_POST['<PASSWORD>'];
$sql = mysqli_query($db,"SELECT * FROM tbl_user WHERE username='$username' AND password='$password'");
$cek = mysqli_num_rows($sql);
$data = mysqli_fetch_assoc($sql);
if ($cek > 0) {
session_start();
$_SESSION['status'] = "login";
$_SESSION['username'] = $data['username'];
$_SESSION['level'] = $data['level'];
?>
<script type="text/javascript">
alert('Login Berhasil');
window.location.href="index.php";
</script>
<?php
}else{
?>
<script type="text/javascript">
alert('Login Gagal');
window.location.href="login.php";
</script>
<?php
}
?><file_sep>/page/master/kategori/tabel_kategori.php
<div class="container-fluid">
<!-- Breadcrumbs-->
<ol class="breadcrumb">
<li class="breadcrumb-item">
<a href="?page=kategori">Kategori</a>
</li>
<li class="breadcrumb-item active">Daftar Kategori</li>
</ol>
<!-- Page Content -->
<h1>Daftar Katergori</h1>
<hr>
<a href="#" class="btn btn-flat btn-primary" style="margin-bottom:10px"><span class="fa fa-plus-square"></span> Tambah</a>
<table class="table table-hover" width="100%">
<thead>
<tr>
<th>No</th>
<th>Nama Kategori</th>
<th width="10%"><center>Ubah</center></th>
<th width="10%"><center>Hapus</center></th>
</tr>
</thead>
<tbody>
<?php
$no = 1;
$sql = mysqli_query($db,"SELECT * FROM tbl_master_kategori");
while ($tampil = mysqli_fetch_array($sql)) {
?>
<tr>
<td><?php echo $no++; ?></td>
<td><?php echo $tampil['nama_kategori']; ?>
</td>
<td><center>
<a href="#" class="btn btn-success btn-flat"><i class="fa fa-edit"></i></a></center>
</td>
<td><center>
<a href="#" class="btn btn-danger btn-flat"><i class="fa fa-trash"></i></a></center>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</div><file_sep>/page/user/hapus_user.php
<?php
$id = $_GET['id'];
mysqli_query($db, "DELETE FROM tbl_user WHERE id_user='$id'");
?>
<script type="text/javascript">
alert('Hapus Data Berhasil');
window.location.href="index.php?page=user";
</script><file_sep>/page/report/report.php
<div class="container-fluid">
<!-- Breadcrumbs-->
<ol class="breadcrumb">
<li class="breadcrumb-item">
<a href="?page=dashboard">Dashboard</a>
</li>
<li class="breadcrumb-item active">Report</li>
</ol>
<!-- Page Content -->
<h1>Report</h1>
<hr>
<form method="POST">
<div class="row
">
<div class="col-md-2">
<label>Start Date</label>
<input class="form-control" type="date" name="date1" />
</div>
<div class="col-md-2">
<label>Finish Date</label>
<input class="form-control" type="date" name="date2" />
</div>
<div class="col-md-2">
<input style="margin-top:30px" class="btn btn-info" type="submit" name="cari" value="Cari"/>
</div>
<div class="col-md-6"></div>
</div>
</form>
<?php
@$date1 = $_POST['date1'];
@$date2 = $_POST['date2'];
@$cari = $_POST['cari'];
if (isset($cari)) {
$sql = mysqli_query($db,"SELECT COUNT(tbl_artikel.id_artikel) AS jml, tbl_master_kategori.nama_kategori
FROM tbl_artikel
LEFT JOIN tbl_master_kategori
ON tbl_artikel.kategori=tbl_master_kategori.id_kategori
WHERE tbl_artikel.tanggal
BETWEEN '$date1' AND '$date2'
GROUP BY tbl_artikel.kategori");
}else{
$sql = mysqli_query($db,"SELECT COUNT(tbl_artikel.id_artikel) AS jml, tbl_master_kategori.nama_kategori
FROM tbl_artikel
LEFT JOIN tbl_master_kategori
ON tbl_artikel.kategori=tbl_master_kategori.id_kategori
GROUP BY tbl_artikel.kategori");
}
?>
<h4 style="margin-top:5px">Laporan Jumlah Berita</h4>
<h6>Periode: <?php echo $date1; ?> - <?php echo $date2; ?></h6>
<table class="table table-hover" width="100%" id="" >
<thead>
<tr>
<th>No</th>
<th>Kategori</th>
<th>Jumlah Berita</th>
</tr>
</thead>
<tbody>
<?php
$no = 1;
while ($tampil = mysqli_fetch_assoc($sql)) {
?>
<tr>
<td><?php echo $no++; ?></td>
<td><?php echo $tampil['nama_kategori']; ?></td>
<td><?php echo $tampil['jml']; ?></td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
<file_sep>/page/artikel/hapus_artikel_aksi.php
<?php
$id = $_GET['id'];
$sql_fetch = mysqli_query($db,"SELECT foto FROM tbl_artikel WHERE id_artikel='$id'");
$fetch = mysqli_fetch_assoc($sql_fetch);
$foto = $fetch['foto'];
unlink("img/".$foto);
$sql = mysqli_query($db,"DELETE FROM tbl_artikel WHERE id_artikel = '$id'");
?>
<script type="text/javascript">
alert('Hapus Data Berhasil');
window.location.href="index.php?page=artikel";
</script><file_sep>/README.md
# news
Contoh aplikasi CRUD PHP native
Menggunakan template SB admin
Menggunaan 2 level login, admin dan owner
Menu
1. Master
- Kategori berita
- Penulis
- user
2. Transaksi
- artikel
3. Report
- jumlah berita per kategori pada periode tertentu
- grafik
Semoga bermanfaat :)
<file_sep>/koneksi.php
<?php
$server = 'localhost';
$user = 'root';
$password = '';
$db_nama = 'db_news';
$db = mysqli_connect($server, $user,$password,$db_nama);
?><file_sep>/js/highcharts/index/organitation.php
<script src="../highcharts-new.js"></script>
<script src="../sankey.js"></script>
<script src="../organization.js"></script>
<script src="../exporting.js"></script>
<div id="container"></div>
<script>
Highcharts.chart('container', {
chart: {
height: 600,
inverted: true
},
title: {
text: 'Highcharts Org Chart'
},
series: [{
type: 'organization',
name: 'Highsoft',
keys: ['from', 'to'],
data: [
['Shareholders', 'Board'],
['Board', 'CEO'],
['CEO', 'CTO'],
['CEO', 'CPO'],
['CEO', 'CSO'],
['CEO', 'CMO'],
['CEO', 'HR'],
['CTO', 'Product'],
['CTO', 'Web'],
['CSO', 'Sales'],
['CMO', 'Market']
],
levels: [{
level: 0,
color: 'silver',
dataLabels: {
color: 'black'
},
height: 25
}, {
level: 1,
color: 'silver',
dataLabels: {
color: 'black'
},
height: 25
}, {
level: 2,
color: '#980104'
}, {
level: 4,
color: '#359154'
}],
nodes: [{
id: 'Shareholders'
}, {
id: 'Board'
}, {
id: 'CEO',
title: 'CEO',
name: '<NAME>',
image: 'https://wp-assets.highcharts.com/www-highcharts-com/blog/wp-content/uploads/2018/11/12132317/Grethe.jpg'
}, {
id: 'HR',
title: 'HR/CFO',
name: '<NAME>',
color: '#007ad0',
image: 'https://wp-assets.highcharts.com/www-highcharts-com/blog/wp-content/uploads/2018/11/12132314/AnneJorunn.jpg',
column: 3,
offset: '75%'
}, {
id: 'CTO',
title: 'CTO',
name: '<NAME>',
column: 4,
image: 'https://wp-assets.highcharts.com/www-highcharts-com/blog/wp-content/uploads/2018/11/12140620/Christer.jpg',
layout: 'hanging'
}, {
id: 'CPO',
title: 'CPO',
name: '<NAME>',
column: 4,
image: 'https://wp-assets.highcharts.com/www-highcharts-com/blog/wp-content/uploads/2018/11/12131849/Torstein1.jpg'
}, {
id: 'CSO',
title: 'CSO',
name: '<NAME>',
column: 4,
image: 'https://wp-assets.highcharts.com/www-highcharts-com/blog/wp-content/uploads/2018/11/12132313/Anita.jpg',
layout: 'hanging'
}, {
id: 'CMO',
title: 'CMO',
name: '<NAME>',
column: 4,
image: 'https://wp-assets.highcharts.com/www-highcharts-com/blog/wp-content/uploads/2018/11/13105551/Vidar.jpg',
layout: 'hanging'
}, {
id: 'Product',
name: 'Product developers'
}, {
id: 'Web',
name: 'General tech',
description: 'Web developers, sys admin'
}, {
id: 'Sales',
name: 'Sales team'
}, {
id: 'Market',
name: 'Marketing team'
}],
colorByPoint: false,
color: '#007ad0',
dataLabels: {
color: 'white'
},
borderColor: 'white',
nodeWidth: 65
}],
tooltip: {
outside: true
},
exporting: {
allowHTML: true,
sourceWidth: 800,
sourceHeight: 600
}
});
</script><file_sep>/login.php
<?php
session_start();
session_destroy();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>News - Login</title>
<!-- Custom fonts for this template-->
<link href="vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
<!-- Custom styles for this template-->
<link href="css/sb-admin.css" rel="stylesheet">
</head>
<body class="" style="background-image: url('img/bg-login.jpg'); width:100%">
<div class="container">
<div class="card card-login mx-auto mt-5">
<div align="center" style="margin-top:20px;">
<img src="img/logo2.png" width="250px">
</div>
<div class="card-header">Login</div>
<div class="card-body">
<form method="POST" action="login_aksi.php">
<div class="form-group">
<div class="form-label-group">
<input type="text" id="" class="form-control" required="required" autofocus="autofocus" name="username">
<label for="">Username</label>
</div>
</div>
<div class="form-group">
<div class="form-label-group">
<input type="password" id="" class="form-control" required="required" name="password">
<label for="">Password</label>
</div>
</div>
<input type="submit" class="btn btn-primary btn-block" name="login" value="Login">
</form>
</div>
</div>
</div>
<!-- Bootstrap core JavaScript-->
<script src="vendor/jquery/jquery.min.js"></script>
<script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<!-- Core plugin JavaScript-->
<script src="vendor/jquery-easing/jquery.easing.min.js"></script>
</body>
</html>
<file_sep>/page/user/tabel_user.php
<div class="container-fluid">
<!-- Breadcrumbs-->
<ol class="breadcrumb">
<li class="breadcrumb-item">
<a href="?page=artikel">Artikel</a>
</li>
<li class="breadcrumb-item active">Daftar User</li>
</ol>
<!-- Page Content -->
<h1>Daftar User</h1>
<hr>
<a href="?page=user&aksi=tambah_user" class="btn btn-flat btn-primary" style="margin-bottom:10px">Tambah</a>
<table class="table table-hover" width="100%">
<thead>
<tr>
<th>No</th>
<th>Username</th>
<th>Password</th>
<th>Level</th>
<th width="15%"><center>Aksi</center></th>
</tr>
</thead>
<tbody>
<?php
$no = 1;
$sql = mysqli_query($db,"SELECT * FROM tbl_user");
while ($tampil = mysqli_fetch_array($sql)) {
?>
<tr>
<td><?php echo $no++; ?></td>
<td><?php echo $tampil['username']; ?></td>
<td><?php echo $tampil['password']; ?></td>
<td><?php echo $tampil['level']; ?></td>
<td>
<a href="" class="btn btn-success btn-flat">Ubah</a>
<a href="?page=user&aksi=hapus_user&id=<?=$tampil['id_user']?>" class="btn btn-danger btn-flat">Hapus</a>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</div><file_sep>/index.php
<?php
include "koneksi.php";
session_start();
if ($_SESSION['status'] != "login") {
header("location:login.php");
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>Web News</title>
<!-- Custom fonts for this template-->
<link href="vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
<!-- Page level plugin CSS-->
<link href="vendor/datatables/dataTables.bootstrap4.css" rel="stylesheet">
<!-- Custom styles for this template-->
<link href="css/sb-admin.css" rel="stylesheet">
</head>
<body id="page-top">
<nav class="navbar navbar-expand navbar-dark bg-primary static-top" style="color:white">
<a class="navbar-brand mr-1" href="index.php">Web News <img src="img/logo21.png" width="20px"></a>
<button class="btn btn-link btn-sm text-white order-1 order-sm-0" id="sidebarToggle" href="#">
<i class="fas fa-bars"></i>
</button>
<form class="d-none d-md-inline-block form-inline ml-auto mr-0 mr-md-3 my-2 my-md-0">
</form>
<!-- Navbar -->
<ul class="navbar-nav ml-auto ml-md-0">
<li class="">
<a class="nav-link" href="#">Hai <?php echo $_SESSION['username']; ?>
</a>
</li>
<li class="">
<a class="nav-link" href="logout.php">
<i class="fas fa-power-off fa-fw"></i> Logout
</a>
</li>
</ul>
</nav>
<div id="wrapper">
<?php
$level = $_SESSION['level'];
switch ($level) {
case '1':
?>
<ul class="sidebar navbar-nav">
<li class="nav-item <?php if (@$_GET['page'] == '' || @$_GET['page'] == 'dashboard') {
echo "active";
} ?>" >
<a class="nav-link" href="?page=dashboard">
<i class="fas fa-fw fa-tachometer-alt"></i>
<span>Dashboard</span>
</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" data-toggle="dropdown">
<i class="fas fa-fw fa-book"></i>
<span>Master</span>
</a>
<div class="dropdown-menu dropdown-menu-right">
<a class="dropdown-item" href="?page=kategori"><i class="fa fa-sort"></i> Kategori</a>
<a class="dropdown-item" href="?page=penulis"><i class="fa fa-sort"></i> Penulis</a>
</div>
</li>
<li class="nav-item <?php if (@$_GET['page'] == 'artikel') {
echo "active";
} ?>">
<a class="nav-link" href="?page=artikel">
<i class="fas fa-fw fa-table"></i>
<span>Artikel</span></a>
</li>
<li class="nav-item <?php if (@$_GET['page'] == 'user') {
echo "active";
} ?>">
<a class="nav-link" href="?page=user">
<i class="fas fa-fw fa-users"></i>
<span>Users</span></a>
</li>
<li class="nav-item <?php if (@$_GET['page'] == 'user') {
echo "active";
} ?>">
<a class="nav-link" href="?page=report">
<i class="fas fa-fw fa-print"></i>
<span>Report</span></a>
</li>
<li class="nav-item <?php if (@$_GET['page'] == 'grafik') {
echo "active";
} ?>">
<a class="nav-link" href="?page=grafik">
<i class="fas fa-fw fa-chart-pie"></i>
<span>Grafik</span></a>
</li>
</ul>
<?php
break;
case '2':
?>
<ul class="sidebar navbar-nav">
<li class="nav-item <?php if (@$_GET['page'] == '' || @$_GET['page'] == 'dashboard') {
echo "active";
} ?>" >
<a class="nav-link" href="?page=dashboard">
<i class="fas fa-fw fa-tachometer-alt"></i>
<span>Dashboard</span>
</a>
</li>
<li class="nav-item <?php if (@$_GET['page'] == 'artikel') {
echo "active";
} ?>">
<a class="nav-link" href="?page=artikel">
<i class="fas fa-fw fa-table"></i>
<span>Artikel</span></a>
</li>
</ul>
<?php
break;
}
?>
<!-- Sidebar -->
<!-- Content -->
<div id="content-wrapper">
<?php
//Menu dashboard
if (@$_GET['page'] == '' || @$_GET['page'] == 'dashboard') {
include "page/dashboard/dashboard.php";
}
//Menu Master Kategori
elseif (@$_GET['page'] == 'kategori' AND @$_GET['aksi'] == '' ) {
include "page/master/kategori/tabel_kategori.php";
}
//Menu artikel
elseif (@$_GET['page'] == 'artikel' AND @$_GET['aksi'] == '' ) {
include "page/artikel/tabel_artikel.php";
}
elseif (@$_GET['page'] == 'artikel' AND @$_GET['aksi'] == 'tambah_artikel' ) {
include "page/artikel/form_tambah_artikel.php";
}
elseif (@$_GET['page'] == 'artikel' AND @$_GET['aksi'] == 'tambah_artikel' ) {
include "page/artikel/form_tambah_artikel.php";
}
elseif (@$_GET['page'] == 'artikel' AND @$_GET['aksi'] == 'ubah_artikel' ) {
include "page/artikel/form_ubah_artikel.php";
}
elseif (@$_GET['page'] == 'artikel' AND @$_GET['aksi'] == 'hapus_artikel' ) {
include "page/artikel/hapus_artikel_aksi.php";
}
//Menu user
elseif (@$_GET['page'] == 'user' ) {
if (@$_GET['aksi'] == '') {
include "page/user/tabel_user.php";
}
if (@$_GET['aksi'] == 'tambah_user') {
include "page/user/form_tambah_user.php";
}
if (@$_GET['aksi'] == 'ubah_user') {
include "page/user/form_ubah_user.php";
}
if (@$_GET['aksi'] == 'hapus_user') {
include "page/user/hapus_user.php";
}
}
//Menu Report
elseif (@$_GET['page'] == 'report' AND @$_GET['aksi'] == '' ) {
include "page/report/report.php";
}
//Menu Grafik
elseif (@$_GET['page'] == 'grafik' AND @$_GET['aksi'] == '' ) {
include "page/grafik/grafik.php";
}
?>
<!-- Sticky Footer -->
<footer class="sticky-footer">
<div class="container my-auto">
<div class="copyright text-center my-auto">
<span>Copyright © News Website 2019</span>
</div>
</div>
</footer>
</div>
<!-- /.content-wrapper -->
</div>
<!-- /#wrapper -->
<!-- Scroll to Top Button-->
<a class="scroll-to-top rounded" href="#page-top">
<i class="fas fa-angle-up"></i>
</a>
<!-- Logout Modal-->
<div class="modal fade" id="logoutModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Ready to Leave?</h5>
<button class="close" type="button" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">Select "Logout" below if you are ready to end your current session.</div>
<div class="modal-footer">
<button class="btn btn-secondary" type="button" data-dismiss="modal">Cancel</button>
<a class="btn btn-primary" href="login.html">Logout</a>
</div>
</div>
</div>
</div>
<!-- Bootstrap core JavaScript-->
<script src="js/highcharts/highcharts.js"></script>
<script src="js/highcharts/exporting.js"></script>
<script src="js/highcharts/export-data.js"></script>
<script src="vendor/jquery/jquery.min.js"></script>
<script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<!-- Core plugin JavaScript-->
<script src="vendor/jquery-easing/jquery.easing.min.js"></script>
<!-- Custom scripts for all pages-->
<script src="js/data-table/jquery-3.3.1.js"></script>
<script src="js/data-table/jquery.dataTables.min.js"></script>
<!-- Data Table-->
<script src="js/sb-admin.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#table').DataTable();
} );
</script>
</body>
</html>
<file_sep>/database/db_news.sql
-- phpMyAdmin SQL Dump
-- version 4.5.1
-- http://www.phpmyadmin.net
--
-- Host: 127.0.0.1
-- Generation Time: 12 Agu 2019 pada 14.31
-- Versi Server: 10.1.9-MariaDB
-- PHP Version: 7.0.0
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `db_news`
--
-- --------------------------------------------------------
--
-- Struktur dari tabel `tbl_artikel`
--
CREATE TABLE `tbl_artikel` (
`id_artikel` int(11) NOT NULL,
`judul` varchar(100) NOT NULL,
`penulis` varchar(100) NOT NULL,
`tanggal` date NOT NULL,
`kategori` varchar(50) NOT NULL,
`isi` text NOT NULL,
`status` varchar(15) NOT NULL,
`foto` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data untuk tabel `tbl_artikel`
--
INSERT INTO `tbl_artikel` (`id_artikel`, `judul`, `penulis`, `tanggal`, `kategori`, `isi`, `status`, `foto`) VALUES
(87, 'Belajar PHP', 'Junaedi', '2019-07-28', '4', 'Tes', 'tidak_aktif', 'img5.jpg'),
(88, 'Gempa Pesisir Banten', 'Junaedi', '2019-08-02', '5', 'Gempa Pesisir Banten', 'tidak_aktif', '6.jpg'),
(89, 'Hari Raya Idul Adha 2019', 'Junaedi', '2019-08-05', '4', 'Peringatan Hari Raya Idul Adha 2019', 'aktif', 'img1.jpg');
-- --------------------------------------------------------
--
-- Struktur dari tabel `tbl_master_kategori`
--
CREATE TABLE `tbl_master_kategori` (
`id_kategori` int(10) NOT NULL,
`nama_kategori` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data untuk tabel `tbl_master_kategori`
--
INSERT INTO `tbl_master_kategori` (`id_kategori`, `nama_kategori`) VALUES
(1, 'Olahraga'),
(2, 'Pendidikan'),
(3, 'Politik'),
(4, 'Luar Negri'),
(5, 'Nasional');
-- --------------------------------------------------------
--
-- Struktur dari tabel `tbl_user`
--
CREATE TABLE `tbl_user` (
`id_user` int(11) NOT NULL,
`username` varchar(50) NOT NULL,
`password` varchar(50) NOT NULL,
`level` int(2) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data untuk tabel `tbl_user`
--
INSERT INTO `tbl_user` (`id_user`, `username`, `password`, `level`) VALUES
(1, 'admin', 'admin', 1),
(2, '<PASSWORD>', '<PASSWORD>', 2);
--
-- Indexes for dumped tables
--
--
-- Indexes for table `tbl_artikel`
--
ALTER TABLE `tbl_artikel`
ADD PRIMARY KEY (`id_artikel`);
--
-- Indexes for table `tbl_master_kategori`
--
ALTER TABLE `tbl_master_kategori`
ADD PRIMARY KEY (`id_kategori`);
--
-- Indexes for table `tbl_user`
--
ALTER TABLE `tbl_user`
ADD PRIMARY KEY (`id_user`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `tbl_artikel`
--
ALTER TABLE `tbl_artikel`
MODIFY `id_artikel` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=90;
--
-- AUTO_INCREMENT for table `tbl_master_kategori`
--
ALTER TABLE `tbl_master_kategori`
MODIFY `id_kategori` int(10) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
--
-- AUTO_INCREMENT for table `tbl_user`
--
ALTER TABLE `tbl_user`
MODIFY `id_user` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep>/page/dashboard/dashboard.php
<div class="container-fluid">
<!-- Breadcrumbs-->
<ol class="breadcrumb">
<li class="breadcrumb-item">
<a href="?page=dashboard">Dashboard</a>
</li>
</ol>
<!-- Page Content -->
<div class="row">
<div class="col-xl-3 col-sm-6 mb-3">
<div class="card text-white bg-primary o-hidden h-100">
<div class="card-body">
<div class="card-body-icon">
<i class="fas fa-fw fa-newspaper"></i>
</div>
<div class="mr-5">Jumlah Artikel</div>
<h1>
<?php
$query_jumlah_artikel = mysqli_query($db,"SELECT id_artikel FROM tbl_artikel");
$jumlah_artikel = mysqli_num_rows($query_jumlah_artikel);
echo $jumlah_artikel;
?>
</h1>
</div>
<a class="card-footer text-white clearfix small z-1" href="#">
<span class="float-left"></span>
<span class="float-right">
<i class="fas fa-angle-right"></i>
</span>
</a>
</div>
</div>
<div class="col-xl-3 col-sm-6 mb-3">
<div class="card text-white bg-warning o-hidden h-100">
<div class="card-body">
<div class="card-body-icon">
<i class="fa fa-users"></i>
</div>
<div class="mr-5">Jumlah User</div>
<?php
$query_jml_user = mysqli_query($db,"SELECT COUNT(id_user) AS jml_user FROM tbl_user");
$data_jml_user = mysqli_fetch_assoc($query_jml_user);
?>
<h1><?php echo $data_jml_user['jml_user'];?></h1>
</div>
<a class="card-footer text-white clearfix small z-1" href="#">
<span class="float-left"></span>
<span class="float-right">
<i class="fas fa-angle-right"></i>
</span>
</a>
</div>
</div>
</div>
</div>
</div><file_sep>/page/artikel/form_ubah_artikel.php
<div class="container-fluid">
<!-- Breadcrumbs-->
<ol class="breadcrumb">
<li class="breadcrumb-item">
<a href="index.html">Artikel</a>
</li>
<li class="breadcrumb-item active">Form Ubah Artikel</li>
</ol>
<!-- Page Content -->
<h1>Ubah Artikel</h1>
<hr>
<?php
$id = $_GET['id'];
$sql = mysqli_query($db,"SELECT * FROM tbl_artikel WHERE id_artikel='$id'");
$tampil = mysqli_fetch_assoc($sql);
?>
<form class="form-horizontal" action="" method="POST" enctype="multipart/form-data">
<div class="form-group" hidden>
<label class="control-label col-sm-2">ID Artikel:</label>
<div class="col-sm-12">
<input type="text" class="form-control" name="id_artikel" value="<?php echo $tampil['id_artikel'] ?>">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Judul:</label>
<div class="col-sm-12">
<input type="text" class="form-control" placeholder="Masukan Judul" name="judul" value="<?php echo $tampil['judul'] ?>">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Penulis:</label>
<div class="col-sm-12">
<input type="text" class="form-control" name="penulis" value="<?php echo $tampil['penulis'] ?>">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Tanggal:</label>
<div class="col-sm-12">
<input type="text" class="form-control" name="tanggal" value="<?php echo $tampil['tanggal'];?>">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Kategori:</label>
<div class="col-sm-12">
<select name="kategori" class="form-control">
<?php
$query_kategori = mysqli_query($db," SELECT * FROM tbl_master_kategori");
while($tampil_kategori = mysqli_fetch_array($query_kategori)){
$pilih = ($tampil_kategori['id_kategori'] == $tampil['kategori']? "selected":"");
echo "<option value='$tampil_kategori[id_kategori]' $pilih>$tampil_kategori[nama_kategori]</option>";
}
?>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Isi:</label>
<div class="col-sm-12">
<textarea name="isi" class="form-control"><?php echo $tampil['isi'] ?></textarea>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Status:</label>
<div class="col-sm-12">
<div class="radio">
<label style="margin-right:50px" ><input type="radio" name="status" class="form-control" value="aktif" checked>Aktif</label>
<label><input type="radio" name="status" class="form-control" value="tidak_aktif">Tidak Aktif</label>
</div>
</div>
</div>
<img src="img/artikel/<?php echo $tampil['foto']?>" height="100px" width="100px">
<div class="form-group">
<label class="control-label col-sm-2">Foto:</label>
<div class="col-sm-12">
<input type="file" name="foto">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<input type="submit" class="btn btn-primary" name="simpan" value="Simpan">
</div>
</div>
</form>
</div>
<?php
@$id = $_POST['id_artikel'];
@$judul = $_POST['judul'];
@$penulis = $_POST['penulis'];
@$kategori = $_POST['kategori'];
@$isi = $_POST['isi'];
@$tanggal = $_POST['tanggal'];
@$status = $_POST['status'];
@$foto = $_FILES['foto']['name'];
@$tmp = $_FILES['foto']['tmp_name'];
@$file_ext = strtolower(end(explode('.',$foto)));
@$path = "img/".$foto;
move_uploaded_file($tmp, $path);
@$simpan = $_POST['simpan'];
if(isset($simpan)) {
if($foto != null) {
mysqli_query($db,"UPDATE tbl_artikel SET judul='$judul', penulis='$penulis', tanggal='$tanggal', kategori='$kategori', isi='$isi', status='$status', foto='$foto'WHERE id_artikel='$id'");
?>
<script type="text/javascript">
alert('Ubah Data Berhasil');
window.location.href="index.php?page=artikel";
</script>
<?php
}else{
mysqli_query($db,"UPDATE tbl_artikel SET judul='$judul', penulis='$penulis', tanggal='$tanggal', kategori='$kategori', isi='$isi', status='$status' WHERE id_artikel='$id'");
?>
<script type="text/javascript">
alert('Ubah Data Berhasil');
window.location.href="index.php?page=artikel";
</script>
<?php
}
}
?>
<file_sep>/page/artikel/form_tambah_artikel.php
<div class="container-fluid">
<!-- Breadcrumbs-->
<ol class="breadcrumb">
<li class="breadcrumb-item"><a href="?page=dashboard">Dashboard</a></li>
<li class="breadcrumb-item"><a href="?page=artikel">Artikel</a></li>
<li class="breadcrumb-item active">Form Tambah Artikel</li>
</ol>
<!-- Page Content -->
<h1>Tambah Artikel</h1>
<hr>
<form class="form-horizontal" action="" method="POST" enctype="multipart/form-data">
<div class="form-group" hidden>
<label class="control-label col-sm-2">ID Artikel:</label>
<div class="col-sm-12">
<input type="text" class="form-control" name="id_artikel" placeholder="Enter ID Artikel">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Judul:</label>
<div class="col-sm-12">
<input type="text" class="form-control" placeholder="Masukan Judul" name="judul" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Penulis:</label>
<div class="col-sm-12">
<input type="text" class="form-control" placeholder="Masukan Penulis" name="penulis" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Tanggal:</label>
<div class="col-sm-12">
<?php
$tgl_sekarang = date("Y-m-d");
?>
<input type="date" class="form-control" name="tanggal">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Kategori:</label>
<div class="col-sm-12">
<select name="kategori" class="form-control" required>
<option value="">Pilih Kategori</option>
<?php
$query_kategori = mysqli_query($db," SELECT * FROM tbl_master_kategori");
while ($tampil_kategori = mysqli_fetch_array($query_kategori)) {?>
<option value="<?=$tampil_kategori[0]?>"><?php echo $tampil_kategori[1]?></option>
<?php
}
?>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Isi:</label>
<div class="col-sm-12">
<textarea name="isi" class="form-control" required></textarea>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Status:</label>
<div class="col-sm-12">
<div class="radio">
<label style="margin-right:50px" ><input type="radio" name="status" class="form-control" value="aktif" checked>Aktif</label>
<label><input type="radio" name="status" class="form-control" value="tidak_aktif">Tidak Aktif</label>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Foto:</label>
<div class="col-sm-12">
<input type="file" name="foto" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<input type="submit" class="btn btn-primary" name="simpan" value="Simpan">
</div>
</div>
</form>
</div>
<?php
@$id = $_POST['id_artikel'];
@$judul = $_POST['judul'];
@$penulis = $_POST['penulis'];
@$kategori = $_POST['kategori'];
@$isi = $_POST['isi'];
@$tanggal = $_POST['tanggal'];
@$status = $_POST['status'];
@$foto = $_FILES['foto']['name'];
@$tmp = $_FILES['foto']['tmp_name'];
@$file_ext = strtolower(end(explode('.',$foto)));
@$path = "img/artikel/".$foto;
move_uploaded_file($tmp, $path);
@$simpan = $_POST['simpan'];
if (isset($simpan )) {
mysqli_query($db,"INSERT INTO tbl_artikel VALUES ('$id', '$judul', '$penulis', '$tanggal', '$kategori', '$isi', '$status', '$foto')");
?>
<script type="text/javascript">
alert('Tambah Data Berhasil');
window.location.href="index.php?page=artikel";
</script>
<?php
}
?><file_sep>/js/highcharts/index/stacked.php
<script src="../highcharts.js"></script>
<script src="../exporting.js"></script>
<script src="../export-data.js"></script>
<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
<script>
Highcharts.chart('container', {
chart: {
type: 'column'
},
title: {
text: 'Stacked column chart'
},
xAxis: {
categories: ['Apples', 'Oranges', 'Pears', 'Grapes', 'Bananas']
},
yAxis: {
min: 0,
title: {
text: 'Total fruit consumption'
}
},
tooltip: {
pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b> ({point.percentage:.0f}%)<br/>',
shared: true
},
plotOptions: {
column: {
stacking: 'percent'
}
},
series: [{
name: 'John',
data: [5, 3, 4, 7, 2]
}, {
name: 'Jane',
data: [2, 2, 3, 2, 1]
}, {
name: 'Joe',
data: [3, 4, 4, 2, 5]
}]
});
</script>
|
0e998af5cf549086aab564a0373bcf444affb54b
|
[
"Markdown",
"SQL",
"PHP"
] | 19
|
PHP
|
junzulkarnain/news
|
85c1903e62ee04fc791bc1bfbe0c14ba92131d7a
|
e94370cc206927100a6d53c6d0e667a2fb5b8fe4
|
refs/heads/master
|
<repo_name>JMachinaDev/Portfolio2020<file_sep>/src/app/slider.js
import React from 'react';
// https://reactjsexample.com/3d-cover-flow-in-react/
const slides = [
{
title: "MachinaChat",
url: "http://machinachat-env.eba-mme2rhnw.us-east-2.elasticbeanstalk.com/",
git: "https://github.com/JMachinaDev/MachinaChat",
image:
"https://i.postimg.cc/N0NpTbpL/machinachat.png",
},
{
title: "BookHero",
url: "https://book-hero-project.s3.us-east-2.amazonaws.com/Library+Proj/main.html",
git: "https://github.com/killsocks/Library" ,
image:
"https://i.postimg.cc/xjzVzvVq/bookhero.png",
},
{
title: "Etch-A-Sketch",
url: "https://etch-sketch-project.s3.us-east-2.amazonaws.com/EtchASketch/etchsketch.html",
git: "https://github.com/killsocks/EtchASketch",
image:
"https://i.postimg.cc/fbJrhsw-k/etchsketch.png",
},
{
title: "Lazy Calculator",
url: "https://lazy-calculator-project.s3.us-east-2.amazonaws.com/Calculator/calculator.html",
git: "https://github.com/killsocks/Calculator-Proj",
image:
"https://i.postimg.cc/Yqr8H7Rk/lazycalc.png",
},
];
function useTilt(active) {
const ref = React.useRef(null);
React.useEffect(() => {
if (!ref.current || !active) {
return;
}
const state = {
rect: undefined,
mouseX: undefined,
mouseY: undefined
};
let el = ref.current;
const handleMouseMove = (e) => {
if (!el) {
return;
}
if (!state.rect) {
state.rect = el.getBoundingClientRect();
}
state.mouseX = e.clientX;
state.mouseY = e.clientY;
const px = (state.mouseX - state.rect.left) / state.rect.width;
const py = (state.mouseY - state.rect.top) / state.rect.height;
el.style.setProperty("--px", px);
el.style.setProperty("--py", py);
};
el.addEventListener("mousemove", handleMouseMove);
return () => {
el.removeEventListener("mousemove", handleMouseMove);
};
}, [active]);
return ref;
}
const initialState = {
slideIndex: 0
};
const slidesReducer = (state, event) => {
if (event.type === "NEXT") {
return {
...state,
slideIndex: (state.slideIndex + 1) % slides.length
};
}
if (event.type === "PREV") {
return {
...state,
slideIndex:
state.slideIndex === 0 ? slides.length - 1 : state.slideIndex - 1
};
}
};
function Slide({ slide, offset }) {
const active = offset === 0 ? true : null;
const ref = useTilt(active);
return (
<div
ref={ref}
className="slide"
data-active={active}
style={{
"--offset": offset,
"--dir": offset === 0 ? 0 : offset > 0 ? 1 : -1,
}}
>
<div
className="slideBackground"
style={{
backgroundImage: `url('${slide.image}')`
}}
/>
<div
className="slideContent"
style={{
backgroundImage: `url('${slide.image}')`
}}
>
<div className="slideContentInner">
<h4 className="slideTitle">{slide.title}</h4>
<a href={slide.url} target="_blank" rel="noreferrer" className="slideLink">-Site Link</a>
<br></br>
<a href={slide.git} target="_blank" rel="noreferrer" className="slideLink">-Github Link</a>
</div>
</div>
</div>
);
}
export default function Slider() {
const [state, dispatch] = React.useReducer(slidesReducer, initialState);
return (
<div className="slideContainer" id="projectId">
<div className="slideBoxTitle" id="slideLinkSection">Projects</div>
<div className="slideBox">
<div className="slides" >
<button className="slideButton" id="slidePrev" onClick={() => dispatch({ type: "PREV" })}>‹</button>
{[...slides, ...slides, ...slides].map((slide, i) => {
let offset = slides.length + (state.slideIndex - i);
return <Slide slide={slide} offset={offset} key={i} />;
})}
<button className="slideButton" id="slideNext" onClick={() => dispatch({ type: "NEXT" })}>›</button>
</div>
</div>
</div>
);
}
<file_sep>/src/app/contactForm.js
import React from 'react';
import emailjs from 'emailjs-com';
// https://www.youtube.com/watch?v=NgWGllOjkbs
// https://www.docdroid.net/mydocuments
export default function ContactUs() {
function sendEmail(e) {
e.preventDefault();
emailjs.sendForm('service_oge86qg', 'template_8ux5ykj', e.target, 'user_zwK8twhy4NRmlB4iTodFU')
.then((result) => {
console.log(result.text);
}, (error) => {
console.log(error.text);
});
e.target.reset();
}
return (
<div className="contactMeBox" id="contactMeId">
<div className="contactMeForm">
<div className="contactMeSection" >
<div className="contactMeTitle" >Get <strong>In Touch</strong></div>
<form className="contact-form" onSubmit={sendEmail}>
<div className="contactName" >
<label>
<input type="text" name="name" placeholder="Your Name" required/>
</label>
</div>
<div className="contactNumber" >
<label>
<input type="tel" name="number" placeholder="Your Phone Number" />
</label>
</div>
<div className="contactEmail" >
<label>
<input type="email" name="email" placeholder="Your Email" required/>
</label>
</div>
<div className="contactMessage" >
<label>
<textarea name="message" cols="32" rows="10" style={{height: '200px', resize: "vertical"}} placeholder="Your Message" required/>
</label>
</div>
<div className="send" >
<input type="submit" value="Send" style={{width: '75px'}} />
</div>
</form>
</div>
<div className="myInfoBox" >
<div className="myInfoTitle" >My <strong>Info</strong></div>
<div className="myInfo" ><strong>EMAIL</strong></div>
<span style={{color: 'var(--text-color)'}}><EMAIL></span>
<div className="myInfo" ><strong>PHONE</strong></div>
<span style={{color: 'var(--text-color)'}}>+1-574-350-6350</span>
<div className="myInfo" ><strong>LOCATION</strong></div>
<span style={{color: 'var(--text-color)'}}>Elkhart, Indiana</span>
<div style={{marginTop: '20px'}}>
<button className="resumeLink">
<a href="https://docs.google.com/document/d/1R20ZhgHepB6lejP6gVxxNemJTZAUgUd8YWI_nAezAPo/edit?usp=sharing"
alt=""
target="_blank"
rel="noreferrer"
style={{color: 'var(--bg)', backgroundColor: '#fbfafa', fontWeight: 'light', textShadow: 'none'}}
>Resume</a></button>
</div>
</div>
</div>
</div>
);
}
<file_sep>/README.md
# JMachinaDev Portfolio 2020v.3
-Created using REACT Library
## Libraries used
-Bootstrap
-Sass
-EmailJs
-JQuery
|
409b90b3c4e58e07829b2e1731d3537394040c57
|
[
"JavaScript",
"Markdown"
] | 3
|
JavaScript
|
JMachinaDev/Portfolio2020
|
6fc2928b669193a74630fbad47d8314986d8cb61
|
e55c4c6eb7715606605198b1f59e527d3fdadb12
|
refs/heads/main
|
<repo_name>mmatotan/Option-calculator<file_sep>/IV_and_stock_pc.py
from yahoo_fin import options
from yahoo_fin import stock_info as si
import numpy as np
import math as m
from scipy.stats import norm as nd
import datetime
import pandas
import csv
option_selector = 0
#Fetch 10y bond rate
r = si.get_live_price("^TNX")
if m.isnan(r):
r = 0.01356
else:
r = np.round(r / 100, 4)
tickers = []
csvFile = open("tickers.csv", "r")
csvReader = csv.reader(csvFile)
for row in csvReader:
tickers.append(row)
csvFile.close()
class OptionPrice(object):
def __init__(self, stock_price, strike_price, time_to_exp_days, risk_free_rate_pc):
self.S = stock_price
self.K = strike_price
self.t = time_to_exp_days
self.r = risk_free_rate_pc
def calc_d1(self):
return (m.log(self.S / self.K) + (self.r + self.v**2 / 2) * self.t) / (self.v * m.sqrt(self.t))
def calc_d2(self):
d1 = self.calc_d1()
return d1 - self.v * m.sqrt(self.t)
def call_price(self, annual_vol_pc):
self.v = annual_vol_pc
d1 = self.calc_d1()
d2 = self.calc_d2()
callprice = self.S * nd.cdf(d1) - self.K * m.exp(-self.r * self.t) * nd.cdf(d2)
return np.round(callprice, 2)
csvFile = open("variables.csv", "w")
csvWriter = csv.writer(csvFile)
csvWriter.writerow([r])
for ticker in tickers:
option = options.get_calls(ticker[0]).sort_values("Last Trade Date", ascending=False)
dateString = option.iat[option_selector, 0]
dateString = dateString.split(ticker[0])[1][:6]
date = datetime.datetime(2000 + int(dateString[:2]), int(dateString[2:4]), int(dateString[4:6]), 22, 00, 00)
#DTE - Days Till Expiry
DTE = np.round(((date - datetime.datetime.now()).days + 1) / 365, 4)
stockPrice = np.round(si.get_live_price(ticker[0]), 2)
strikePrice = option.iat[option_selector, 2]
price = OptionPrice(stockPrice, strikePrice, DTE, r)
last_price = option.iat[option_selector, 3]
#Metoda bisekcije
low_IV = 0
high_IV = 2000
IV = (low_IV + high_IV) / 2
guess_price = price.call_price(IV / 100)
while guess_price != last_price:
if guess_price < last_price:
low_IV = IV
else:
high_IV = IV
IV = (low_IV + high_IV) / 2
IV = np.round(IV, 2)
guess_price = price.call_price(IV / 100)
csvWriter.writerow([stockPrice] + [IV])
csvFile.close()<file_sep>/launch.sh
#!/bin/bash
gcc -I/usr/include/python3.9 -o option_calculator option_calculator.c -lpython3.9 -lm -pthread -g -fopenmp
<file_sep>/README.md
# Option-calculator
## About
This program is a part of a bachelor's thesis which can be found as a pdf file in this repository.
## Description
This program is used as a demonstration of parallelized option calculation in real time. Variables needed for option calculation are downloaded via an API in a Python subprogram and passed to the C program which then calculates the values of options. It's main purpose is to visualize the speedup in performace in HPC machines, where using multiple cores, in a context of a program, threads, is faster than using the single core or thread. To run the following Python dependencies are required: numpy, scipy, yahoo-fin, pandas. To run the program, run the ./launch.sh command in linux terminal to compile the program and then run the compiled file.
## Abstract of the bachelor's thesis
In this bachelor's thesis high performance computing meets the world of finance on an example of computing the financial derivative options using a program that applies the parallelization of code on a larger number of processors of a supercomputer. The results of program execution are compared with serial code execution on one processor.
<file_sep>/calculations.h
#ifndef CALCULATIONS_H_
# define CALCULATIONS_H_
#include <math.h>
#define e 2.71828
float calculate_call_option(float stock_price, float risk_free_rate, float time, float Nd1, float Nd2, float strike_price){
float Vc;
Vc = stock_price * Nd1 - ((strike_price / pow(e, risk_free_rate * time)) * Nd2);
return Vc;
}
float calculate_put_option(float Vc, float strike_price, float risk_free_rate, float time, float stock_price){
float Vp;
Vp = Vc + (strike_price / pow(e, risk_free_rate * time)) - stock_price;
return Vp;
}
float calculate_d1(float stock_price, float strike_price, float risk_free_rate, float volatility, float time){
float d1;
d1 = (log(stock_price / strike_price) + (risk_free_rate + (0.5 * pow(volatility, 2))) * time) / (volatility * sqrt(time));
return d1;
}
float calculate_d2(float d1, float volatility, float time){
float d2;
d2 = d1 - (volatility * sqrt(time));
return d2;
}
// Calculates the standard normal value, eliminates the use of hard-coded values from the standard normal value table
double normalCDF(double d)
{
return 0.5 * erfc(-d * M_SQRT1_2);
}
#endif<file_sep>/data_visualization.py
import numpy as np
from scipy.stats import iqr
import matplotlib.pyplot as plt
import csv
raw_x = []
raw_y = []
sorted_y = []
x = []
y = []
x_minimum = 0
y_minimum = 10
x_maximum = 0
y_maximum = 0
with open('results.csv', 'r') as csvfile:
plots = csv.reader(csvfile, delimiter=',')
for row in plots:
raw_x.append(int(row[0]))
raw_y.append(float(row[1]))
sorted_y.append(float(row[1]))
sorted_y.sort()
#Q1 = np.quantile(raw_y, 0.25)
#Q3 = np.quantile(raw_y, 0.75)
#IQR = Q3 - Q1
#lower = Q1 - 1.25*IQR
#upper = Q3 + 1.25*IQR
#mean, dev = np.mean(raw_y), np.std(raw_y)
#cut_off = dev * 3
#lower, upper = mean - cut_off, mean + cut_off
for i in raw_x:
x.append(i)
y.append(raw_y[i - 1])
if(raw_y[i - 1] < y_minimum):
y_minimum = float(raw_y[i - 1])
x_minimum = i
if(float(raw_y[i - 1]) > y_maximum):
y_maximum = float(raw_y[i - 1])
x_maximum = i
print(f"Minimum na {x_minimum} dretvi/dretve")
print(f"Maximum: {x_maximum} dretvi/dretve")
plt.plot(x, y, 'kx', label="Zasebno vrijeme izračuna")
plt.plot(x_minimum, y_minimum, 'go', label="Najbrže vrijeme")
plt.plot(x_maximum, y_maximum, 'ro', label="Najduže vrijeme")
stupanj = 3
reg = np.polyfit(x, y, stupanj)
f = np.poly1d(reg)
plt.plot(x, f(x), lw=3, label=f"Regresijska krivulja {stupanj}. stupnja", c='b')
plt.xlabel("Broj dretvi")
plt.ylabel("Vremena izračuna")
plt.legend()
plt.show()
<file_sep>/option_calculator.c
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <python3.9/Python.h>
#include <unistd.h>
#include <omp.h>
#include "calculations.h"
//Global variables which are only changed in functions get_tickers() and get_dates()
//They are used in multiple other functions and threads
int number_of_tickers, number_of_dates;
char **tickers;
float *days;
//Structure for end values of an option
typedef struct{
float call;
float put;
} option;
option calculate_single_option(float stock_price, float volatility, float risk_free_rate, float strike_price, float time){
//The rest follows the formula for calculating options, all functions are located in calculations.h
float d1 = calculate_d1(stock_price, strike_price, risk_free_rate, volatility, time);
float d2 = calculate_d2(d1, volatility, time);
float Nd1 = normalCDF(d1);
float Nd2 = normalCDF(d2);
option option_price;
option_price.call = calculate_call_option(stock_price, risk_free_rate, time, Nd1, Nd2, strike_price);
//To simulate real world, options won't ever be free for purchase, they may expire worthless though
if(option_price.call < 0.01) option_price.call = 0.01;
option_price.put = calculate_put_option(option_price.call, strike_price, risk_free_rate, time, stock_price);
//Same for put
if(option_price.put < 0.01) option_price.put = 0.01;
return option_price;
}
//Embeds provided python file and runs it, needed for APIs used
void run_python(char file_name[]){
FILE* fp = _Py_fopen(file_name, "r");
PyRun_SimpleFile(fp, file_name);
fclose(fp);
return;
}
void get_tickers(){
//Ticker selection and preparation to send to the Python script
printf("How many tickers would you like to follow? ");
scanf("%d", &number_of_tickers);
char ticker[8];
tickers = malloc(number_of_tickers * sizeof(char *));
FILE *fp = fopen("tickers.csv", "w");
for(int i = 0; i < number_of_tickers; i++){
printf("\nEnter the %d. ticker: ", i + 1);
scanf("%s", ticker);
fprintf(fp, "%s", ticker);
if(i != number_of_tickers - 1) fprintf(fp, "\n");
//Store tickers
tickers[i] = malloc(strlen(ticker) * sizeof(char));
strcpy(tickers[i], ticker);
strcat(ticker, ".csv");
FILE *csv = fopen(ticker, "w");
fclose(csv);
}
fclose(fp);
return;
}
void get_dates(){
//Options usually exipre on fridays but it is left to the user's will to put in their own DTE(days till expiry)
printf("\nFor how many dates would you like to calculate options? ");
scanf("%d", &number_of_dates);
days = malloc(number_of_dates * sizeof(float));
for(int i = 0; i < number_of_dates; i++){
printf("\nEnter the %d. DTE: ", i + 1);
scanf("%f", &days[i]);
}
return;
}
int main(int argc, char *argv[]){
int max_threads;
//Arguments setup for number of threads
if(argc == 2){
//If running on >1 threads
if(atoi(argv[1]) != 1){
max_threads = atoi(argv[1]);
omp_set_nested(1);
} else {
max_threads = 1;
omp_set_nested(0);
}
} else {
max_threads = 1;
omp_set_nested(0);
}
//Python embed init, input for tickers and dates
Py_Initialize();
get_tickers();
get_dates();
int number_of_results;
printf("\nEnter the number of result calculations:\n");
scanf("%d", &number_of_results);
//Time to check if NYSE is working currently
time_t raw_time;
time(&raw_time);
struct tm *time_info;
float risk_free_rate, current_prices[number_of_tickers], volatilities[number_of_tickers];
int number_of_strikes[number_of_tickers], lowest_strikes[number_of_tickers], highest_strikes[number_of_tickers];
unsigned long long int number_of_calculations = 0;
option *option_prices[number_of_tickers][number_of_dates];
double times[max_threads], dtime;
memset(times, 0, sizeof times);
do{
run_python("IV_and_stock_pc.py");
time_info = localtime(&raw_time);
FILE *fp = fopen("variables.csv", "r");
fscanf(fp, "%f\n", &risk_free_rate);
//Loop for loading and preparing values
for (int i = 0; i < number_of_tickers; i++)
{
fscanf(fp, "%f,%f\n", ¤t_prices[i], &volatilities[i]);
lowest_strikes[i] = (int) floor(current_prices[i] - ((volatilities[i] / 100) * current_prices[i]));
if(lowest_strikes[i] < 1) lowest_strikes[i] = 1;
highest_strikes[i] = (int) floor(current_prices[i] + ((volatilities[i] / 100) * current_prices[i]));
number_of_strikes[i] = highest_strikes[i] - lowest_strikes[i];
number_of_calculations += (number_of_dates * number_of_strikes[i]);
}
fclose(fp);
fp = fopen("results.csv", "w");
for (int threads = 1; threads <= max_threads; threads++)
{
omp_set_num_threads(threads);
for (int results = 0; results < number_of_results; results++)
{
dtime = omp_get_wtime();
int i, j, k;
//Parralelized loop for calculating and saving options
#pragma omp parallel for private(j, k) schedule(dynamic) collapse(2)
for (i = 0; i < number_of_tickers; i++)
{
for (j = 0; j < number_of_dates; j++)
{
option *chain = malloc(number_of_strikes[i] * sizeof(option));
for (k = 0; k < number_of_strikes[i]; k++)
{
chain[k] = calculate_single_option(current_prices[i], volatilities[i] / 100, risk_free_rate, k + lowest_strikes[i], days[j] / 365);
}
option_prices[i][j] = chain;
}
}
dtime = omp_get_wtime() - dtime;
times[threads - 1] += dtime;
}
}
for (int i = 0; i < max_threads; i++){
times[i] /= number_of_results;
fprintf(fp, "%d,%f,%lld\n", i + 1, times[i], number_of_calculations);
}
fclose(fp);
//Loops for saving prices in .csv files
for(int i = 0; i < number_of_tickers; i++){
char *ticker = malloc(strlen(tickers[i]) * sizeof(char));
strcpy(ticker, tickers[i]);
strcat(ticker, ".csv");
FILE *csv = fopen(ticker, "a");
free(ticker);
for(int j = 0; j < number_of_dates; j++){
fprintf(csv, "\n%d,%d/%d/%d,%d:%d:%d\n", (int)days[j], time_info->tm_mday, time_info->tm_mon + 1, time_info->tm_year + 1900, time_info->tm_hour, time_info->tm_min, time_info->tm_sec);
for(int k = 0; k < number_of_strikes[i]; k++){
fprintf(csv, "%.2f,%d,%.2f\n", option_prices[i][j][k].call, k + lowest_strikes[i], option_prices[i][j][k].put);
}
free(option_prices[i][j]);
}
fclose(csv);
}
//For constant updating delete this break
break;
//NYSE working hours in local time
} while( (time_info->tm_wday != 0 && time_info->tm_wday != 6) && ( ((time_info->tm_hour >= 15 && time_info->tm_min >= 30) || time_info->tm_hour > 15) && time_info->tm_hour <= 22) );
run_python("data_visualization.py");
Py_Finalize();
return 0;
}
|
5f9923b08999e52bbd9f9bfaf59e383a4669f75f
|
[
"Markdown",
"C",
"Python",
"Shell"
] | 6
|
Python
|
mmatotan/Option-calculator
|
95d5858ef2e83d7969ed9aa115fb8ebf2aa30585
|
31d55b1c9aeea3b9033be7edaca848c9b73c1607
|
refs/heads/main
|
<file_sep>const express = require("express");
const router = express.Router();
const Comment = require("../models/comment");
require("date-utils");
// postId 검증은 내일하자...!
router.get("/:postId", async (req, res) => {
const { postId } = req.params;
try {
const comment = await Comment.find({ upperPost: postId }).sort("-_id");
res.status(200).send({ comment: comment });
} catch (err) {
res.status(400).send({ err: "코맨트 에러" });
}
});
router.post("/:postId", async (req, res) => {
const { postId } = req.params;
const { nickname, comment } = req.body;
let newDate = new Date();
let date = newDate.toFormat("YYYY-MM-DD HH24:MI:SS");
try {
await Comment.create({
nickname: nickname,
comment: comment,
upperPost: postId,
commentTime: date,
});
res.status(200).send({ result: "success" });
} catch (err) {
console.log(err);
res.status(400).send({ err: "err" });
}
});
router.patch("/:commentId", async (req, res) => {
const { commentId } = req.params;
const { email, comment } = req.body;
const iscomment = await Comment.findById(commentId);
console.log(iscomment);
if (iscomment) {
if (true) {
await Comment.updateOne(
{ commentId },
{ $set: { email: email, comment, comment } }
);
res.status(200).send({ result: "success" });
} else {
res.status(400).send({ result: "err" });
}
} else {
res.status(400).send({ result: "게시글 존재하지 않음" });
}
});
router.delete("/:commentId", async (req, res) => {
const { commentId } = req.params;
const iscomment = await Comment.findById(commentId);
if (iscomment) {
//nickname == ispost["nickname"]
if (true) {
await Comment.deleteOne({ commentId });
res.status(200).send({ result: "success" });
} else {
res.status(400).send({ result: "사용자 본인이 아님" });
}
} else {
res.status(400).send({ result: "게시글 존재하지 않음" });
}
});
module.exports = router;
<file_sep>const jwt = require('jsonwebtoken');
const User = require('../models/user');
module.exports = async (req, res, next) => {
const token = req.cookies.user;
console.log('미들웨어 사용함');
try {
if (token) {
const decoded = jwt.verify(token, 'IDEA-secret-key');
const user = await User.findOne({ userId: decoded.userId }).exec();
const users ={
userId : user._id,
email: user.email,
nickname: user.nickname,
}
res.locals.user = users;
console.log('로컬 유저는?', res.locals.user);
} else {
res.locals.user = undefined;
console.log('로컬 유저는?', res.locals.user);
}
} catch (err) {
res.status(401).send({ errorMessage: '로그인이 필요합니다' });
return;
}
next();
};
<file_sep>function idCheck(id_give) {
const reg_name = /^[0-9a-zA-Z]([-_.]?[0-9a-zA-Z])*@[0-9a-zA-Z]([-_.]?[0-9a-zA-Z])*.[a-zA-Z]{2,3}$/i;
if (reg_name.test(id_give) && id_give.length >= 3) {
return true;
}
return false;
}
function pwConfirm(pw_give, pw2_give) {
if (pw_give === pw2_give) {
return true;
}
return false;
}
function pwLenCheck(pw_give) {
if (pw_give.length >= 4) {
return true;
}
return false;
}
function pw_idCheck(id_give, pw_give) {
if (!id_give.includes(pw_give)) {
return true;
}
return false;
}
module.exports = { idCheck, pwConfirm, pwLenCheck, pw_idCheck };<file_sep>const express = require('express');
const User = require('../models/user');
const jwt = require('jsonwebtoken');
const router = express.Router();
const uf = require('./userfunction.js');
// 회원가입
router.post('/signup', async (req, res) => {
const { email, pw, pwCheck, nickname } = req.body;
const existId = await User.findOne({ email: email });
const existName = await User.findOne({ nickname: nickname });
if (existId) {
res.status(401).send({result: "아이디가 중복입니다."});
} else if (existName) {
res.status(401).send({result: "닉네임이 중복입니다."});
} else if (!uf.idCheck(email)) {
res.status(401).send({});
} else if (!uf.pwConfirm(pw, pwCheck)) {
res.status(401).send({});
} else if (!uf.pwLenCheck(pw)) {
res.status(401).send({});
} else if (!uf.pw_idCheck(email, pw)) {
res.status(401).send({});
} else {
await User.create({
email: email,
pw: pw,
nickname: nickname
});
res.send({ result: 'success' });
}
});
// 로그인
router.post('/login', async (req, res) => {
const { email, pw } = req.body;
const users = await User.findOne({ email: email });
if (users) {
if (users.pw === pw) {
//{expiresIn: '5m'}
const token = jwt.sign({ email: users.email ,nickname: users.nickname, userId: users._id}, 'IDEA-secret-key');
res.cookie('user', token);
res.json({ token });
} else {
res.status(400).send({});
}
} else {
res.status(400).send({});
}
});
module.exports = router;<file_sep>const express = require('express'); // 익스프레스 참조
const cookieParser = require('cookie-parser');
const app = express(); // 익스프레스 쓸때는 app이라고 명시
app.use(cookieParser()); // 쿠키값을 꺼낼 수 있음
const port = 3000;
const authMiddleware = require('./middlewares/auth-middleware');
const cors = require('cors');
const connect = require('./models'); // models 폴더 참조
connect(); // 모델이랑 연결하기
// const options = {
// origin: 'http://example.com', // 접근 권한을 부여하는 도메인
// credentials: true, // 응답 헤더에 Access-Control-Allow-Credentials 추가
// optionsSuccessStatus: 200 // 응답 상태 200으로 설정
// };
// app.use(cors(options));
app.use(cors({origin: true, credentials: true}));
app.use(express.urlencoded({ extended: true }));
app.use(express.json()); // POST로 메소드 받을 때 req.body로 사용가능하게 함
const postRouter = require('./routers/post');
const userRouter = require('./routers/user');
const wishRouter = require('./routers/wish');
const commRouter = require('./routers/comment');
app.use('/post', [ postRouter ]); // postRouter를 api 하위부분에서 쓰겠다 !
app.use('/', [ userRouter ]);
app.use('/comment', [ commRouter ]);
app.use('/wish', [ wishRouter ]);
app.listen(port, () => {
console.log(`listening at http://localhost:${ port }`);
});
|
d0c3ccdaa57b978228c4e0bb4a4445afca6690ae
|
[
"JavaScript"
] | 5
|
JavaScript
|
devLily/idea_backend
|
79f6407237fb14c858a3f7c3d045c89d9b5cfb00
|
0cd8e3532fd5b75e34614347cb88e9abec694865
|
refs/heads/master
|
<file_sep>import React from 'react';
import logo from './logo.svg';
import './App.scss';
import { RootViewContainer } from './containers/RootViewContainer';
import { configureStore } from './configureStore';
import { Provider } from 'react-redux';
const store = configureStore();
function App() {
return (
<Provider store={store}>
<RootViewContainer />
</Provider>
);
}
export default App;
<file_sep>import {
setPawn,
setRook,
setKnight,
setBishop,
setQueen,
setKing,
} from './placePieces';
describe('setPawn', () => {
it('should set pawn', () => {
const mockBoard = {};
const pawnSet = setPawn('white', mockBoard);
expect(mockBoard).toEqual(pawnSet);
for (let i = 0; i < 8; i++) {
expect(mockBoard[i + 48].name).toEqual('Pawn');
}
});
it('should set pawn', () => {
const mockBoard = {};
const pawnSet = setPawn('black', mockBoard);
expect(mockBoard).toEqual(pawnSet);
for (let i = 0; i < 8; i++) {
expect(mockBoard[i + 8].name).toEqual('Pawn');
}
});
});
describe('setRook', () => {
it('should set rook', () => {
let mockBoard = {};
const black = setRook(mockBoard, 'black');
expect(black[0].name).toEqual('Rook');
expect(black[7].name).toEqual('Rook');
});
it('should set rook', () => {
let mockBoard = {};
const white = setRook(mockBoard, 'white');
expect(white[56].name).toEqual('Rook');
expect(white[63].name).toEqual('Rook');
});
});
describe('setKnight', () => {
it('should set knight', () => {
let mockBoard = {};
const black = setKnight(mockBoard, 'black');
expect(black[1].name).toEqual('Knight');
expect(black[6].name).toEqual('Knight');
});
it('should set knight', () => {
let mockBoard = {};
const white = setKnight(mockBoard, 'white');
expect(white[57].name).toEqual('Knight');
expect(white[62].name).toEqual('Knight');
});
});
describe('setBishop', () => {
it('should set bishop', () => {
let mockBoard = {};
const black = setBishop(mockBoard, 'black');
expect(black[2].name).toEqual('Bishop');
expect(black[5].name).toEqual('Bishop');
});
it('should set bishop', () => {
let mockBoard = {};
const white = setBishop(mockBoard, 'white');
expect(white[58].name).toEqual('Bishop');
expect(white[61].name).toEqual('Bishop');
});
});
describe('setQueen', () => {
it('should set queen', () => {
let mockBoard = {};
const black = setQueen(mockBoard, 'black');
expect(black[4].name).toEqual('Queen');
});
it('should set bishop', () => {
let mockBoard = {};
const white = setBishop(mockBoard, 'white');
expect(white[59].name).toEqual('Queen');
});
});
describe('setKing', () => {
it('should set king', () => {
let mockBoard = {};
const black = setKing(mockBoard, 'black');
expect(black[3].name).toEqual('King');
});
it('should set bishop', () => {
let mockBoard = {};
const white = setKing(mockBoard, 'white');
expect(white[60].name).toEqual('King');
});
});
<file_sep>import { combineReducers } from 'redux';
import { boardReducer } from './boardReducer';
import { turnReducer } from './turnReducer';
export const rootReducer = combineReducers({
board: boardReducer,
turn: turnReducer,
});
<file_sep>import { shallow } from 'enzyme';
import React from 'react';
import {
setupPlayingBoard,
startingPieceLocations,
} from '../helperFunctons/setupStart';
import GameBoard from './GameBoardView';
describe('GameBoard', () => {
describe('white turn', () => {
const mockBoard = setupPlayingBoard();
const mockTurn = 'white';
const mockOpponentPiece = startingPieceLocations('black');
const movePiece = jest.fn();
const mockEnpassant = null;
const mockCheck = null;
const wrapper = shallow(
<GameBoard
board={mockBoard}
turn={mockTurn}
opponentPiece={mockOpponentPiece}
enpassant={mockEnpassant}
check={mockCheck}
/>,
);
const grids = wrapper.find('Grid');
it('should be 8 x 8', () => {
const listElement = wrapper.find('li');
expect(listElement).toHaveLength(8);
expect(listElement.at(0).find('Grid')).toHaveLength(8);
expect(grids).toHaveLength(64);
for (let i = 0; i < grids.length; i++) {
if (i % 2 === 0) {
expect(grids.at(i).props().color).toEqual('white');
} else {
expect(grids.at(i).props().color).toEqual('blue');
}
}
});
it('should run function', () => {
//test for state changes by clicking on grids and checking for green background
//color, then check the click for background color by checking the mockMovePiece
const pawn = grids.at(8);
pawn.simulate('click');
const newGrids = wrapper.find('Grid');
const highlightOne = newGrids.at(16);
expect(highlightOne.props().color).toEqual('green');
const highlightTwo = newGrids.at(24);
expect(highlightTwo.props().color).toEqual('green');
highlightTwo.simulate('click');
expect(movePiece).toHaveBeenCalled();
const newerGrids = wrapper.find('Grid');
const moved = newerGrids.at(24);
expect(moved.props().image).not.toEqual(null); //there's a piece there
const oldSpot = newerGrids.at(8);
expect(oldSpot.props().image).toEqual(null); //there's not a piece there
for (let i = 0; i < 64; i++) {
expect(newerGrids.at(i).props().color).not.toEqual('green');
}
});
it('should not run function', () => {
const oppPawn = grids.at(48);
oppPawn.simulate('click');
const newGrids = wrapper.find('Grid');
for (let i = 0; i < 64; i++) {
expect(newGrids.at(i).props().color).not.toEqual('green');
}
});
});
describe('black turn', () => {
const mockBoard = setupPlayingBoard();
const mockTurn = 'black';
const mockOpponentPiece = startingPieceLocations('white');
const movePiece = jest.fn();
const mockEnpassant = null;
const mockCheck = null;
const wrapper = shallow(
<GameBoard
board={mockBoard}
turn={mockTurn}
opponentPiece={mockOpponentPiece}
enpassant={mockEnpassant}
check={mockCheck}
/>,
);
const grids = wrapper.find('Grid');
it('should run function', () => {
//test for state changes by clicking on grids and checking for green background
//color, then check the click for background color by checking the mockMovePiece
const pawn = grids.at(48);
pawn.simulate('click');
const newGrids = wrapper.find('Grid');
const highlightOne = newGrids.at(40);
expect(highlightOne.props().color).toEqual('green');
const highlightTwo = newGrids.at(32);
expect(highlightTwo.props().color).toEqual('green');
highlightTwo.simulate('click');
expect(movePiece).toHaveBeenCalled();
const newerGrids = wrapper.find('Grid');
const moved = newerGrids.at(32);
expect(moved.props().image).not.toEqual(null); //there's a piece there
const oldSpot = newerGrids.at(48);
expect(oldSpot.props().image).toEqual(null); //there's not a piece there
for (let i = 0; i < 64; i++) {
expect(newerGrids.at(i).props().color).not.toEqual('green');
}
});
it('should not run function', () => {
const oppPawn = grids.at(8);
oppPawn.simulate('click');
const newGrids = wrapper.find('Grid');
for (let i = 0; i < 64; i++) {
expect(newGrids.at(i).props().color).not.toEqual('green');
}
});
});
});
<file_sep>import { MOVE } from '../actions/actionTypes';
import {
startingPieceLocations,
setupPlayingBoard,
} from '../helperFunctons/setupStart';
import { runMove } from '../helperFunctons/reducerFunctions';
const initialState = {
board: setupPlayingBoard(),
enpassant: null,
check: false,
blackPieces: startingPieceLocations('black'),
whitePieces: startingPieceLocations('white'),
checkMate: false,
};
export function boardReducer(state = initialState, action) {
let stateUpdates;
switch (action.type) {
case MOVE:
stateUpdates = runMove(state, action);
return Object.assign({}, state, stateUpdates);
default:
return state;
}
}
<file_sep>import { shallow } from 'enzyme';
import React from 'react';
import { RootView } from './RootView';
describe('RootView', () => {
describe('not check/checkMate, white turn', () => {
it('should return component', () => {
const mockTurn = 'white';
const mockCheckMate = false;
const mockCheck = false;
const wrapper = shallow(
<RootView
turn={mockTurn}
checkMate={mockCheckMate}
check={mockCheck}
/>,
);
const header = wrapper.find('h1');
expect(header).toEqual('CHESS GAME!');
const turn = wrapper.find('.turn');
expect(turn).toEqual('WHITE TURN');
const check = wrapper.find('.check');
expect(check).toEqual(null);
const board = wrapper.find('GameBoardContainer');
expect(board).toHaveLength(1);
});
});
describe('not check/checkMate, black turn', () => {
it('should return component', () => {
const mockTurn = 'black';
const mockCheckMate = false;
const mockCheck = false;
const wrapper = shallow(
<RootView
turn={mockTurn}
checkMate={mockCheckMate}
check={mockCheck}
/>,
);
const header = wrapper.find('h1');
expect(header).toEqual('CHESS GAME!');
const turn = wrapper.find('.turn');
expect(turn).toEqual('BLACK TURN');
const check = wrapper.find('.check');
expect(check).toEqual(null);
const board = wrapper.find('GameBoardContainer');
expect(board).toHaveLength(1);
});
});
describe('check, not checkMate, white turn', () => {
it('should return component', () => {
const mockTurn = 'white';
const mockCheckMate = false;
const mockCheck = true;
const wrapper = shallow(
<RootView
turn={mockTurn}
checkMate={mockCheckMate}
check={mockCheck}
/>,
);
const header = wrapper.find('h1');
expect(header).toEqual('CHESS GAME!');
const turn = wrapper.find('.turn');
expect(turn).toEqual('WHITE TURN');
const check = wrapper.find('.check');
expect(check).toEqual('CHECK');
const board = wrapper.find('GameBoardContainer');
expect(board).toHaveLength(1);
});
});
describe('check, checkMate, white turn', () => {
it('should return component', () => {
const mockTurn = 'white';
const mockCheckMate = true;
const mockCheck = true;
const wrapper = shallow(
<RootView
turn={mockTurn}
checkMate={mockCheckMate}
check={mockCheck}
/>,
);
const header = wrapper.find('h1');
expect(header).toEqual('CHESS GAME!');
const turn = wrapper.find('.turn');
expect(turn).toEqual('GAME OVER WHITE WINS!');
const check = wrapper.find('.check');
expect(check).toEqual('CHECK');
const board = wrapper.find('GameBoardContainer');
expect(board).toHaveLength(1);
});
});
});
<file_sep>export function copyBoard(board) {
return Object.assign({}, board)
}
<file_sep>import { Pawn, King, Queen, Rook, Bishop, Knight } from './pieceCreaters';
describe('Pawn', () => {
it('should work', () => {
const pawn = Pawn('white');
expect(pawn.name).toEqual('Pawn');
expect(pawn.color).toEqual('white');
expect(pawn.image).toEqual('whitepawn');
});
});
describe('King', () => {
it('should work', () => {
const king = King('white');
expect(king.name).toEqual('King');
expect(king.color).toEqual('white');
expect(king.image).toEqual('whitekin');
expect(king.castle).toEqual('true');
});
});
describe('Queen', () => {
it('should work', () => {
const queen = Queen('black');
expect(queen.name).toEqual('Queen');
expect(queen.color).toEqual('black');
expect(queen.image).toEqual('whiteque');
});
});
describe('Rook', () => {
it('should work', () => {
const rook = Rook('black');
expect(rook.name).toEqual('Rook');
expect(rook.color).toEqual('black');
expect(rook.image).toEqual('blackroo');
expect(rook.castle).toEqual(true);
});
});
describe('Bishop', () => {
it('should work', () => {
const bishop = Bishop('white');
expect(bishop.name).toEqual('Bishop');
expect(bishop.color).toEqual('white');
expect(bishop.image).toEqual('whitebis');
});
});
describe('Knight', () => {
it('should work', () => {
const knight = Knight('black');
expect(knight.name).toEqual('Knight');
expect(knight.color).toEqual('black');
expect(knight.image).toEqual('blackknight');
});
});
<file_sep>import {
setupPlayingBoard,
startingPieceLocations,
makeBoard,
} from './setupStart';
import { isCheck, isCheckMate, willMoveCauseCheck } from './checkFunctions';
import { Rook, King, Pawn, Queen, Bishop } from './pieceCreaters';
describe('isCheck', () => {
describe('initial', () => {
it('should return false', () => {
const mockWhitePieces = startingPieceLocations('white');
const mockBlackPieces = startingPieceLocations('black');
const mockGameBoard = setupPlayingBoard();
const whiteCheck = isCheck(mockBlackPieces, mockGameBoard);
const blackCheck = isCheck(mockWhitePieces, mockGameBoard);
expect(whiteCheck).toEqual(false);
expect(blackCheck).toEqual(false);
});
});
describe('no king danger', () => {
it('should return false', () => {
const mockWhitePieces = [3, 11, 15, 19, 20, 38];
const mockBlackPieces = [30, 45, 69, 39];
const mockGameBoard = makeBoard();
mockGameBoard[3] = Rook('white');
mockGameBoard[11] = King('white');
mockGameBoard[15] = Pawn('white');
mockGameBoard[19] = Pawn('white');
mockGameBoard[20] = Pawn('white');
mockGameBoard[38] = Pawn('white');
mockGameBoard[39] = King('black');
mockGameBoard[45] = Pawn('black');
mockGameBoard[69] = Pawn('black');
mockGameBoard[30] = Pawn('black');
const whiteCheck = isCheck(mockBlackPieces, mockGameBoard);
const blackCheck = isCheck(mockWhitePieces, mockGameBoard);
const whiteCheckMate = isCheckMate(
mockWhitePieces,
mockGameBoard,
mockBlackPieces,
);
const blackCheckMate = isCheckMate(
mockBlackPieces,
mockGameBoard,
mockWhitePieces,
);
expect(whiteCheckMate).toEqual(false);
expect(blackCheckMate).toEqual(false);
expect(whiteCheck).toEqual(false);
expect(blackCheck).toEqual(false);
});
});
describe('black king danger, no block', () => {
it('should return true', () => {
const mockWhitePieces = [7, 11, 15, 19, 20, 38];
const mockBlackPieces = [30, 45, 69, 39];
const mockGameBoard = makeBoard();
mockGameBoard[7] = Rook('white');
mockGameBoard[11] = King('white');
mockGameBoard[15] = Pawn('white');
mockGameBoard[19] = Pawn('white');
mockGameBoard[20] = Pawn('white');
mockGameBoard[38] = Pawn('white');
mockGameBoard[39] = King('black');
mockGameBoard[45] = Pawn('black');
mockGameBoard[69] = Pawn('black');
mockGameBoard[30] = Pawn('black');
const whiteCheck = isCheck(mockBlackPieces, mockGameBoard);
const blackCheck = isCheck(mockWhitePieces, mockGameBoard);
const whiteCheckMate = isCheckMate(
mockWhitePieces,
mockGameBoard,
mockBlackPieces,
);
const blackCheckMate = isCheckMate(
mockBlackPieces,
mockGameBoard,
mockWhitePieces,
);
expect(whiteCheckMate).toEqual(false);
expect(blackCheckMate).toEqual(false);
expect(whiteCheck).toEqual(false);
expect(blackCheck).toEqual(true);
});
});
describe('black king danger, blocked', () => {
it('should return false', () => {
const mockWhitePieces = [7, 11, 15, 19, 20, 38];
const mockBlackPieces = [30, 31, 69, 39];
const mockGameBoard = makeBoard();
mockGameBoard[7] = Rook('white');
mockGameBoard[11] = King('white');
mockGameBoard[15] = Pawn('white');
mockGameBoard[19] = Pawn('white');
mockGameBoard[20] = Pawn('white');
mockGameBoard[38] = Pawn('white');
mockGameBoard[39] = King('black');
mockGameBoard[31] = Pawn('black');
mockGameBoard[69] = Pawn('black');
mockGameBoard[30] = Pawn('black');
const whiteCheck = isCheck(mockBlackPieces, mockGameBoard);
const blackCheck = isCheck(mockWhitePieces, mockGameBoard);
const whiteCheckMate = isCheckMate(
mockWhitePieces,
mockGameBoard,
mockBlackPieces,
);
const blackCheckMate = isCheckMate(
mockBlackPieces,
mockGameBoard,
mockWhitePieces,
);
expect(whiteCheckMate).toEqual(false);
expect(blackCheckMate).toEqual(false);
expect(whiteCheck).toEqual(false);
expect(blackCheck).toEqual(false);
});
});
describe('white king danger, no block', () => {
it('should return true', () => {
const mockWhitePieces = [7, 11, 15, 18, 20, 38];
const mockBlackPieces = [30, 43, 69, 39];
const mockGameBoard = makeBoard();
mockGameBoard[7] = Rook('white');
mockGameBoard[11] = King('white');
mockGameBoard[15] = Pawn('white');
mockGameBoard[18] = Pawn('white');
mockGameBoard[20] = Pawn('white');
mockGameBoard[38] = Pawn('white');
mockGameBoard[39] = King('black');
mockGameBoard[43] = Queen('black');
mockGameBoard[69] = Pawn('black');
mockGameBoard[30] = Pawn('black');
const whiteCheck = isCheck(mockBlackPieces, mockGameBoard);
const blackCheck = isCheck(mockWhitePieces, mockGameBoard);
const whiteCheckMate = isCheckMate(
mockWhitePieces,
mockGameBoard,
mockBlackPieces,
);
const blackCheckMate = isCheckMate(
mockBlackPieces,
mockGameBoard,
mockWhitePieces,
);
expect(whiteCheckMate).toEqual(false);
expect(blackCheckMate).toEqual(false);
expect(whiteCheck).toEqual(true);
expect(blackCheck).toEqual(false);
});
});
describe('white king danger, no block', () => {
it('should return true', () => {
const mockWhitePieces = [17, 11, 15, 19, 20, 38];
const mockBlackPieces = [30, 43, 69, 39];
const mockGameBoard = makeBoard();
mockGameBoard[17] = Pawn('white');
mockGameBoard[11] = King('white');
mockGameBoard[15] = Pawn('white');
mockGameBoard[19] = Pawn('white');
mockGameBoard[20] = Pawn('white');
mockGameBoard[38] = Pawn('white');
mockGameBoard[39] = King('black');
mockGameBoard[43] = Queen('black');
mockGameBoard[69] = Pawn('black');
mockGameBoard[30] = Pawn('black');
const whiteCheck = isCheck(mockBlackPieces, mockGameBoard);
const blackCheck = isCheck(mockWhitePieces, mockGameBoard);
const whiteCheckMate = isCheckMate(
mockWhitePieces,
mockGameBoard,
mockBlackPieces,
);
const blackCheckMate = isCheckMate(
mockBlackPieces,
mockGameBoard,
mockWhitePieces,
);
expect(whiteCheckMate).toEqual(false);
expect(blackCheckMate).toEqual(false);
expect(whiteCheck).toEqual(false);
expect(blackCheck).toEqual(false);
});
});
});
describe('isCheckMate', () => {
describe('initial', () => {
it('should return false', () => {
const mockWhitePieces = startingPieceLocations('white');
const mockBlackPieces = startingPieceLocations('black');
const mockGameBoard = makeBoard();
const whiteCheckMate = isCheckMate(
mockWhitePieces,
mockGameBoard,
mockBlackPieces,
);
const blackCheckMate = isCheckMate(
mockBlackPieces,
mockGameBoard,
mockWhitePieces,
);
expect(whiteCheckMate).toEqual(false);
expect(blackCheckMate).toEqual(false);
});
});
describe('black checkmate', () => {
it('should return true', () => {
const mockWhitePieces = [47, 11, 15, 51, 20, 63];
const mockBlackPieces = [61];
const mockGameBoard = makeBoard();
mockGameBoard[47] = Bishop('white');
mockGameBoard[11] = King('white');
mockGameBoard[15] = Queen('white');
mockGameBoard[51] = Rook('white');
mockGameBoard[20] = Bishop('white');
mockGameBoard[63] = Rook('white');
mockGameBoard[61] = King('black');
const blackCheck = isCheck(mockWhitePieces, mockGameBoard);
const blackCheckMate = isCheckMate(
mockBlackPieces,
mockGameBoard,
mockWhitePieces,
);
expect(blackCheck).toEqual(true);
expect(blackCheckMate).toEqual(true);
});
});
describe('white checkmate', () => {
it('should return true', () => {
const mockWhitePieces = [5];
const mockBlackPieces = [14, 53, 11, 0];
const mockGameBoard = makeBoard();
mockGameBoard[11] = Bishop('black');
mockGameBoard[53] = King('black');
mockGameBoard[0] = Queen('black');
mockGameBoard[14] = Rook('black');
mockGameBoard[5] = King('white');
const whiteCheck = isCheck(mockBlackPieces, mockGameBoard);
const whiteCheckMate = isCheckMate(
mockWhitePieces,
mockGameBoard,
mockBlackPieces,
);
expect(whiteCheck).toEqual(true);
expect(whiteCheckMate).toEqual(true);
});
});
});
describe('willMoveCauseCheck', () => {
describe('first move black', () => {
it('should return false', () => {
const mockGameBoard = makeBoard();
const mockBlackPieces = startingPieceLocations('black');
const move = willMoveCauseCheck(mockGameBoard, 50, 32, mockBlackPieces);
expect(move).toEqual(false);
});
});
describe('first move white', () => {
it('should return false', () => {
const mockGameBoard = makeBoard();
const mockWhitePieces = startingPieceLocations('white');
const move = willMoveCauseCheck(mockGameBoard, 13, 29, mockWhitePieces);
expect(move).toEqual(false);
});
});
describe('bad move', () => {
it('should return true', () => {
const mockBlackPieces = [14, 53, 11, 0];
const mockGameBoard = makeBoard();
mockGameBoard[11] = Pawn('black');
mockGameBoard[53] = King('black');
mockGameBoard[0] = Queen('black');
mockGameBoard[14] = Rook('black');
mockGameBoard[5] = King('white');
const move = willMoveCauseCheck(mockGameBoard, 5, 6, mockBlackPieces);
expect(move).toBe(true);
});
});
describe('bad move', () => {
it('should return true', () => {
const mockWhitePieces = [3, 12, 15, 13, 20, 38];
const mockGameBoard = makeBoard();
mockGameBoard[3] = Rook('white');
mockGameBoard[12] = King('white');
mockGameBoard[15] = Pawn('white');
mockGameBoard[13] = Pawn('white');
mockGameBoard[20] = Pawn('white');
mockGameBoard[38] = Pawn('white');
mockGameBoard[34] = King('black');
mockGameBoard[45] = Pawn('black');
mockGameBoard[69] = Pawn('black');
mockGameBoard[30] = Pawn('black');
const move = willMoveCauseCheck(mockGameBoard, 34, 35, mockWhitePieces);
expect(move).toBe(true);
});
});
});
<file_sep>import { boardReducer } from './boardReducer';
import {
setupPlayingBoard,
startingPieceLocations,
} from '../helperFunctons/setupStart';
import { BLACK_MOVE, WHITE_MOVE } from '../actions/actionTypes';
describe('boardReducer', () => {
it('should return object', () => {
const wrapper = boardReducer();
const {
board,
enpassant,
check,
blackPieces,
whitePieces,
checkMate,
} = wrapper;
expect(enpassant).toEqual(null);
expect(check).toEqual(false);
expect(checkMate).toEqual(false);
expect(blackPieces).toHaveLength(16);
expect(blackPieces).toEqual([
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
0,
]);
expect(whitePieces).toHaveLength(16);
expect(whitePieces).toEqual([
63,
62,
61,
60,
59,
58,
57,
56,
55,
54,
53,
52,
51,
50,
49,
48,
47,
]);
expect(board).toHaveLength(64);
board.forEach(grid => {
expect(grid).toEqual(null);
});
});
describe('WHITE_MOVE', () => {
let initialBoard = setupPlayingBoard();
initialBoard[40] = initialBoard[48];
initialBoard[48] = null;
let initialWhitePieces = startingPieceLocations('white');
let initialBlackPieces = startingPieceLocations('black');
initialBlackPieces.splice(initialBlackPieces.indexOf(48), 1, 40);
const previousState = {
check: false,
checkMate: false,
enpassant: 6,
whitePieces: initialWhitePieces,
blackPieces: initialBlackPieces,
board: initialBoard,
};
let action = { type: WHITE_MOVE, previous: 1, target: 8 };
const wrapper = boardReducer(previousState, action);
const {
check,
checkMate,
enpassant,
whitePieces,
blackPieces,
board,
} = wrapper;
expect(check).toEqual(false);
expect(checkMate).toEqual(false);
expect(enpassant).toEqual(null);
expect(blackPieces).toEqual(blackPieces);
expect(whitePieces).toEqual(
initialWhitePieces.splice(initialWhitePieces.indexOf(1), 1, 8),
);
expect(board[8].name).toEqual(initialBoard[1].name);
expect(board[1]).toEqual(null);
});
describe('BLACK_MOVE', () => {
let initialBoard = setupPlayingBoard();
initialBoard[23] = initialBoard[2];
initialBoard[2] = null;
let initialWhitePieces = startingPieceLocations('white');
let initialBlackPieces = startingPieceLocations('black');
initialWhitePieces.splice(initialWhitePieces.indexOf(2), 1, 23);
const previousState = {
check: false,
checkMate: false,
enpassant: 6,
whitePieces: initialWhitePieces,
blackPieces: initialBlackPieces,
board: initialBoard,
};
let action = { type: BLACK_MOVE, previous: 52, target: 44 };
const wrapper = boardReducer(previousState, action);
const {
check,
checkMate,
enpassant,
whitePieces,
blackPieces,
board,
} = wrapper;
expect(check).toEqual(false);
expect(checkMate).toEqual(false);
expect(enpassant).toEqual(null);
expect(whitePieces).toEqual(initialWhitePieces);
expect(blackPieces).toEqual(
initialBlackPieces.splice(initialBlackPieces.indexOf(52), 1, 44),
);
expect(board[44].name).toEqual(initialBoard[52].name);
expect(board[52]).toEqual(null);
});
});
<file_sep>import { setupPlayingBoard } from './setupStart';
import { copyBoard } from './copiesBoard';
describe('copyBoard', () => {
it('should have new board', () => {
const mockBoard = setupPlayingBoard();
mockBoard[4] = 'JUST TO CHANGE THINGS UP';
const copiedBoard = copyBoard(mockBoard);
expect(copiedBoard).not.toEqual(mockBoard);
const mockKeys = Object.keys(mockBoard);
const mockValues = Object.values(mockBoard);
const copiedKeys = Object.keys(copiedBoard);
const copiedValues = Object.values(copiedBoard);
mockKeys.forEach((key, index) => {
expect(key).toEqual(copiedKeys[index]);
});
mockValues.forEach((value, index) => {
expect(value).toEqual(copiedValues[index]);
});
});
});
<file_sep>import { connect } from "react-redux";
import { RootView } from "../views/RootView";
function mapStateToProps(state) {
return {
turn: state.turn,
checkMate: state.board.checkMate,
check: state.board.check
};
}
export const RootViewContainer = connect(
mapStateToProps,
null
)(RootView);
<file_sep>import { movePieceOnBoard } from './moveFunctions';
import { getMoves } from './pieceMoves';
import { copyBoard } from './copiesBoard';
export function isCheck(allColorPieces, gameboard) {
//this needs to know board AND pieces to check if there is check.
let board = copyBoard(gameboard);
for (let i = 0; i < allColorPieces.length; i++) {
let piece = allColorPieces[i];
let allMoves = getMoves(piece, board);
for (let j = 0; j < allMoves.length; j++) {
let move = allMoves[j];
if (board[move]) {
const notMyPiece = !allColorPieces.includes(move);
if (board[move].name === 'King' && notMyPiece) {
return true;
}
}
}
}
return false;
}
export function isCheckMate(attackingPieces, board, defendingPieces) {
//checkmate goes through every piece of the player being checked, gets every move for each piece and
//checks each move and sees if it still results in a check with that move. remember check function is the aggressors pieces.
let piecesLocations = defendingPieces.slice();
for (let i = 0; i < piecesLocations.length; i++) {
let indexOfPiece = piecesLocations[i];
let rival = attackingPieces.slice();
let moves = getMoves(indexOfPiece, board);
for (let j = 0; j < moves.length; j++) {
let move = moves[j];
let causesCheck = willMoveCauseCheck(board, indexOfPiece, move, rival);
if (!causesCheck) {
return false;
}
}
}
return true;
}
export function willMoveCauseCheck(board, previous, target, rival) {
//this function checks if your move causes the mover to be checked, aka your bishop is blocking your king from being checked and you want to move that bishop.
let copyboard = copyBoard(board);
let opponentPieces = rival.slice();
let moveOnBoard = movePieceOnBoard(copyboard, previous, target);
let opponentAtTarget = opponentPieces.indexOf(target);
if (opponentAtTarget !== -1) {
opponentPieces.splice(opponentAtTarget, 1);
}
//we just need the board to check
return isCheck(opponentPieces, moveOnBoard);
}
<file_sep>import { Rook, Pawn } from './pieceCreaters';
import { rankUpPawn, pawnLevelUp, choosePiece } from './pawnRankUp';
describe('rankUpPawn', () => {
describe('not pawn', () => {
const rook = Rook('white');
const notPawn = rankUpPawn(rook, 40);
expect(notPawn).toEqual(notPawn);
});
describe('pawn, not end', () => {
const pawn = Pawn('white');
const stillPawn = rankUpPawn(pawn, 33);
expect(pawn).toEqual(stillPawn);
});
describe('pawn, at end', () => {
window.prompt = () => {
return 'rook';
};
const pawn = Pawn('white');
const noLongerPawn = rankUpPawn(pawn, 4);
expect(pawnLevelUp).toHaveBeenCalled();
expect(noLongerPawn.name).toEqual('Rook');
});
describe('pawn, at end', () => {
window.prompt = () => {
return 'queen';
};
const pawn = Pawn('black');
const noLongerPawn = rankUpPawn(pawn, 62);
expect(pawnLevelUp).toHaveBeenCalled();
expect(noLongerPawn.name).toEqual('Queen');
});
});
describe('choosePiece', () => {
let counter = 0;
window.prompt = () => {
if (counter === 4) {
return 'rook';
}
counter++;
};
describe('should return after 4 times', () => {
const piece = choosePiece();
expect(piece).toEqual('rook');
expect(counter).toEqual(4);
describe('PawnLevelUp', () => {
const newPiece = pawnLevelUp('white')
expect(newPiece.name).toEqual('Rook')
expect(newPiece.color).toEqual('white')
});
});
});
<file_sep>import {
setKing,
setQueen,
setBishop,
setRook,
setPawn,
setKnight,
} from './placePieces';
export function makeBoard() {
//we could just make this an object that has keys 0 - 63 and our 'moves' can just be Board[spot] = piece and Board[oldSpot] = null
const board = {};
for (var i = 0; i < 64; i++) {
board[i] = null;
}
return board;
}
export function setupPlayingBoard() {
const board = makeBoard();
let placeWhite = placePieces('white', board);
let placeBlack = placePieces('black', placeWhite);
return placeBlack;
}
export function startingPieceLocations(color) {
let locations = [];
for (let i = 0; i < 16; i++) {
if (color === 'black') {
locations.push(i);
} else {
locations.push(i + 48);
}
}
return locations;
}
export function placePieces(color, board) {
let placePawns = setPawn(color, board);
let placeRooks = setRook(color, placePawns);
let placeBishops = setBishop(color, placeRooks);
let placeKnights = setKnight(color, placeBishops);
let placeQueen = setQueen(color, placeKnights);
let placeKing = setKing(color, placeQueen);
return placeKing;
}
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
export function Grid(props) {
const { click, piece, color, id } = props;
return (
<section className={`grid ${id} ${color}`} key={id} onClick={click}>
{piece}
</section>
);
}
Grid.propTypes = {
click: PropTypes.func,
piece: PropTypes.object,
color: PropTypes.string,
id: PropTypes.number,
};
<file_sep>import React from 'react';
function ImageCreator(name, url) {
return <img className={`${name}`} src={`${url}`} alt={`${name}`} />;
}
export function Pawn(color) {
return {
name: 'Pawn',
color: color,
image:
color === 'white'
? ImageCreator(
'white__pawn',
'https://images.cdn2.stockunlimited.net/clipart/chess-piece_1489848.jpg',
)
: ImageCreator(
'blackpawn',
'https://cdn3.iconfinder.com/data/icons/chess-7/100/black_pawn-512.png',
),
};
}
export function King(color) {
return {
name: 'King',
color: color,
image:
color === 'white'
? ImageCreator(
'white king',
'https://cdn2.iconfinder.com/data/icons/chess-set-pieces/100/Chess_Set_01-White-Classic-King-512.png',
)
: ImageCreator(
'blackking',
'https://c7.uihere.com/files/941/949/299/battle-chess-chess-piece-bishop-king-chess-pieces.jpg',
),
castle: true,
};
}
export function Queen(color) {
return {
name: 'Queen',
color: color,
image:
color === 'white'
? ImageCreator(
'whitequeen',
'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSQStyqGa8IPghZxLXe7CzwwSkI3xolt4ZwWtoDgg0I9fGef3aPlw&s',
)
: ImageCreator(
'blackqueen',
'https://p7.hiclipart.com/preview/532/888/1/battle-chess-queen-chess-piece-king-chess-game.jpg',
),
};
}
export function Rook(color) {
return {
name: 'Rook',
color: color,
image:
color === 'white'
? ImageCreator(
'whiterook',
'https://www.netclipart.com/pp/m/66-669058_chess-castle-tower-figure-piece-white-game-play.png',
)
: ImageCreator(
'blackrook',
'https://cdn.clipart.email/f7622d8973944f3c9bde0f6ed6b4b1cb_chess-piece-rook-icon-iconexperience-professional-icons-o-_512-512.png',
),
castle: true,
};
}
export function Bishop(color) {
return {
name: 'Bishop',
color: color,
image:
color === 'white'
? ImageCreator(
'whitebis',
'https://cdn.clipart.email/a350502c54942d259683b1eedd076a1e_chess-battle-figure-game-checkmate-bishop-icon_512-512.png',
)
: ImageCreator(
'blackbis',
'https://cdn.iconscout.com/icon/premium/png-512-thumb/bishop-black-games-battle-checkmate-chess-camel-figure-58246.png',
),
};
}
export function Knight(color) {
return {
name: 'Knight',
color: color,
image:
color === 'white'
? ImageCreator(
'whiteknight',
'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSGuH1y85WNKVYXMcxF25Izj-lS6xf-dNTfkfVW8HeRepfx2Bn71g&s',
)
: ImageCreator(
'blackknight',
'https://png.pngtree.com/png-vector/20190505/ourlarge/pngtree-chess-knight--horse--logo-illustration-png-image_1021838.jpg',
),
};
}
<file_sep>import { turnReducer } from './turnReducer';
import { WHITE_MOVE, BLACK_MOVE } from '../actions/actionTypes';
describe('turnReducer', () => {
it('should return white', () => {
const initialReducer = turnReducer();
expect(initialReducer).toEqual('white');
});
it('should return white', () => {
let action = { type: WHITE_MOVE };
const whiteAction = turnReducer('black', action);
expect(whiteAction).toEqual('white');
});
it('should return black', () => {
let action = { type: BLACK_MOVE };
const blackAction = turnReducer('white', action);
expect(blackAction).toEqual('black');
});
});
<file_sep>import { copyBoard } from "./copiesBoard";
//these are dispatches.
export function movePieceOnBoard(currentBoard, previous, target) {
let board = copyBoard(currentBoard);
let piece = board[previous];
board[previous] = null;
board[target] = piece;
return board;
}
export function updatePieceIndex(allColorPieces, previous, target) {
let allPieces = allColorPieces.slice();
let index = allPieces.indexOf(previous);
allPieces.splice(index, 1, target);
return allPieces;
}
<file_sep>import { setupPlayingBoard } from './setupStart';
import { movePieceOnBoard, updatePieceIndex } from './moveFunctions';
describe('movePieceOnBoard', () => {
const mockBoard = setupPlayingBoard();
describe('move 4, 30', () => {
it('should work', () => {
const movedBoard = movePieceOnBoard(mockBoard, 4, 30);
expect(movedBoard).not.toEqual(mockBoard);
expect(movedBoard[4]).toEqual(null);
expect(Object.values(movedBoard[30])).toEqual(Object.value(mockBoard[4]));
});
});
describe('move 50, 41', () => {
it('should work', () => {
const movedBoard = movePieceOnBoard(mockBoard, 50, 41);
expect(movedBoard).not.toEqual(mockBoard);
expect(movedBoard[50]).toEqual(null);
expect(Object.values(movedBoard[41])).toEqual(
Object.value(mockBoard[50]),
);
});
});
});
describe('updatePieceIndex', () => {
const pieces = [4, 6, 5, 7, 8, 9, 0];
it('should return new array', () => {
const updated = updatePieceIndex(pieces, 4, 11);
const expected = pieces.splice(0, 1, 11);
expect(updated).not.toEqual(pieces);
updated.forEach((point, index) => {
expect(point).toEqual(expected[index]);
});
});
});
<file_sep>import { connect } from 'react-redux';
import { movePiece, moveWhite, moveBlack } from '../actions/actions';
import GameBoard from '../views/GameBoardView';
function mapStateToProps(state) {
return {
board: state.board.board,
turn: state.turn,
opponentPiece:
state.turn === 'white'
? state.board.blackPieces
: state.board.whitePieces,
enpassant: state.board.enpassant,
check: state.board.check,
};
}
function mapDispatchToProps(dispatch) {
return {
movePiece: (previous, target, color) => {
dispatch(movePiece(previous, target, color));
dispatch(color === 'white' ? moveWhite() : moveBlack());
},
};
}
export const GameBoardContainer = connect(
mapStateToProps,
mapDispatchToProps,
)(GameBoard);
<file_sep>import {
isCastleMove,
castleMove,
updatePieces,
movePieceOnBoard,
removeOpponentPiece,
possibleEnpassant,
wasEnpassantMove,
} from './reducerFunctions';
import { setupPlayingBoard, startingPieceLocations } from './setupStart';
import { King, Pawn } from './pieceCreaters';
describe('isCastleMove', () => {
describe('return true', () => {
const mockBoard = setupPlayingBoard();
const previous = 3;
const target = 0;
const color = 'white';
const isCastle = isCastleMove(mockBoard, previous, target, color);
expect(isCastle).toBe(true);
});
describe('return true', () => {
const mockBoard = setupPlayingBoard();
const previous = 3;
const target = 7;
const color = 'white';
const isCastle = isCastleMove(mockBoard, previous, target, color);
expect(isCastle).toBe(true);
});
describe('return true', () => {
const mockBoard = setupPlayingBoard();
const previous = 59;
const target = 63;
const color = 'white';
const isCastle = isCastleMove(mockBoard, previous, target, color);
expect(isCastle).toBe(true);
});
describe('return true', () => {
const mockBoard = setupPlayingBoard();
const previous = 59;
const target = 56;
const color = 'white';
const isCastle = isCastleMove(mockBoard, previous, target, color);
expect(isCastle).toBe(true);
});
describe('return false', () => {
const mockBoard = setupPlayingBoard();
const previous = 59;
const target = 54;
const color = 'white';
const isCastle = isCastleMove(mockBoard, previous, target, color);
expect(isCastle).toBe(false);
});
describe('return false', () => {
const mockBoard = setupPlayingBoard();
const previous = 8;
const target = 0;
const color = 'white';
const isCastle = isCastleMove(mockBoard, previous, target, color);
expect(isCastle).toBe(false);
});
});
describe('castleMove', () => {
describe('it should return object', () => {
const mockBoard = setupPlayingBoard();
const mockPieces = startingPieceLocations('black');
const previous = 3;
const target = 7;
mockBoard[4] = null;
mockBoard[5] = null;
mockBoard[6] = null;
mockPieces.splice(4, 3);
const castled = castleMove(mockBoard, mockPieces, previous, target);
expect(castled.board[3]).toEqual(null);
expect(castled.board[7]).toEqual(null);
expect(castled.board[5]).toEqual(mockBoard[7]);
expect(castled.board[6]).toEqual(mockBoard[3]);
expect(mockPieces).toEqual([0, 1, 2, 4, 5]);
let ignore = { 3: true, 5: true, 6: true, 7: true };
for (let i = 0; i < 63; i++) {
if (!ignore[i]) {
expect(castled.board[i]).toEqual(mockBoard[i]);
}
}
});
describe('it should return object', () => {
const mockBoard = setupPlayingBoard();
const mockPieces = startingPieceLocations('black');
const previous = 3;
const target = 0;
mockBoard[1] = null;
mockBoard[2] = null;
mockPieces.splice(1, 2);
const castled = castleMove(mockBoard, mockPieces, previous, target);
expect(castled.board[3]).toEqual(null);
expect(castled.board[0]).toEqual(null);
expect(castled.board[1]).toEqual(mockBoard[3]);
expect(castled.board[2]).toEqual(mockBoard[0]);
expect(mockPieces).toEqual([1, 2, 5, 6, 7]);
let ignore = { 0: true, 1: true, 2: true, 3: true };
for (let i = 0; i < 63; i++) {
if (!ignore[i]) {
expect(castled.board[i]).toEqual(mockBoard[i]);
}
}
});
describe('it should return object', () => {
const mockBoard = setupPlayingBoard();
const mockPieces = startingPieceLocations('white');
const previous = 60;
const target = 56;
mockBoard[57] = null;
mockBoard[58] = null;
mockBoard[59] = null;
mockPieces.splice(57, 3);
const castled = castleMove(mockBoard, mockPieces, previous, target);
expect(castled.board[60]).toEqual(null);
expect(castled.board[56]).toEqual(null);
expect(castled.board[57]).toEqual(mockBoard[60]);
expect(castled.board[58]).toEqual(mockBoard[56]);
expect(mockPieces).toEqual([57, 58, 61, 62, 63]);
let ignore = { 56: true, 57: true, 58: true, 60: true };
for (let i = 0; i < 63; i++) {
if (!ignore[i]) {
expect(castled.board[i]).toEqual(mockBoard[i]);
}
}
});
describe('it should return object', () => {
const mockBoard = setupPlayingBoard();
const mockPieces = startingPieceLocations('white');
const previous = 60;
const target = 63;
mockBoard[61] = null;
mockBoard[62] = null;
mockPieces.splice(61, 2);
const castled = castleMove(mockBoard, mockPieces, previous, target);
expect(castled.board[60]).toEqual(null);
expect(castled.board[63]).toEqual(null);
expect(castled.board[62]).toEqual(mockBoard[60]);
expect(castled.board[61]).toEqual(mockBoard[56]);
expect(mockPieces).toEqual([56, 57, 58, 59, 61, 62]);
let ignore = { 60: true, 61: true, 62: true, 63: true };
for (let i = 0; i < 63; i++) {
if (!ignore[i]) {
expect(castled.board[i]).toEqual(mockBoard[i]);
}
}
});
});
describe('updatePieces', () => {
describe('it should return array', () => {
const mockPieces = [1, 2, 3, 4, 5];
const mockPrevious = 4;
const mockTarget = 44;
const updated = updatePieces(mockPieces, mockPrevious, mockTarget);
expect(updated).toEqual([1, 2, 3, 44, 5]);
});
});
describe('movePieceOnBoard', () => {
describe('it should return object', () => {
const mockBoard = setupPlayingBoard();
const mockPrevious = 14;
const mockTarget = 22;
const moved = movePieceOnBoard(mockBoard, mockPrevious, mockTarget);
let ignore = { 22: true, 14: true };
expect(moved[22]).toEqual(mockBoard[14]);
expect(mockBoard[14]).toEqual(null);
for (let i = 0; i < 63; i++) {
if (!ignore[i]) {
expect(moved[i]).toEqual(mockBoard[i]);
}
}
});
describe('it should return object', () => {
const mockBoard = setupPlayingBoard();
const mockPrevious = 54;
const mockTarget = 22;
const moved = movePieceOnBoard(mockBoard, mockPrevious, mockTarget);
let ignore = { 22: true, 54: true };
expect(moved[22]).toEqual(mockBoard[54]);
expect(mockBoard[54]).toEqual(null);
for (let i = 0; i < 63; i++) {
if (!ignore[i]) {
expect(moved[i]).toEqual(mockBoard[i]);
}
}
});
});
describe('removeOpponentPiece', () => {
describe('it should return array', () => {
const mockPieces = [2, 4, 6, 8];
const removed = removeOpponentPiece(mockPieces, 4);
expect(removed).toEqual([2, 6, 8]);
});
describe('it should return array', () => {
const mockPieces = [2, 4, 6, 8];
const removed = removeOpponentPiece(mockPieces, 7);
expect(removed).toEqual([2, 4, 6, 8]);
});
});
describe('possibleEnpassant', () => {
it('should return null', () => {
const mockPiece = new King('white');
const mockPrevious = 14;
const mockTarget = 15;
const enpassant = possibleEnpassant(mockPiece, mockPrevious, mockTarget);
expect(enpassant).toEqual(null);
});
it('should return null', () => {
const mockPiece = new Pawn('white');
const mockPrevious = 44;
const mockTarget = 36;
const enpassant = possibleEnpassant(mockPiece, mockPrevious, mockTarget);
expect(enpassant).toEqual(null);
});
it('should return null', () => {
const mockPiece = new Pawn('black');
const mockPrevious = 44;
const mockTarget = 35;
const enpassant = possibleEnpassant(mockPiece, mockPrevious, mockTarget);
expect(enpassant).toEqual(null);
});
it('should return number', () => {
const mockPiece = new Pawn('white');
const mockPrevious = 14;
const mockTarget = 30;
const enpassant = possibleEnpassant(mockPiece, mockPrevious, mockTarget);
expect(enpassant).toEqual(30);
});
});
describe('wasEnpassantMove', () => {
it('should return obj', () => {
const mockBoard = setupPlayingBoard();
mockBoard[24] = mockBoard[8];
mockBoard[23] = mockBoard[48];
mockBoard[48] = null;
mockBoard[8] = null;
const mockEnpassant = 24;
const mockTarget = 16;
const mockPiece = mockBoard[23];
const mockDefending = startingPieceLocations('black');
mockDefending[8] = 24;
const enpassantMove = wasEnpassantMove(
mockPiece,
mockBoard,
mockTarget,
mockEnpassant,
mockDefending,
);
expect(enpassantMove.defending).toEqual([
0,
1,
2,
3,
4,
5,
6,
8,
7,
8,
9,
10,
11,
12,
13,
14,
15,
]);
const expectedBoard = Object.assign({}, mockBoard);
expectedBoard[24] = null;
expect(enpassantMove.board).toEqual(expectedBoard);
});
it('should return obj', () => {
const mockBoard = setupPlayingBoard();
const mockEnpassant = null;
const mockTarget = 16;
const mockPiece = mockBoard[23];
const mockDefending = startingPieceLocations('black');
const enpassantMove = wasEnpassantMove(
mockPiece,
mockBoard,
mockTarget,
mockEnpassant,
mockDefending,
);
expect(enpassantMove.defending).toEqual(mockDefending);
expect(enpassantMove.board).toEqual(mockBoard);
});
it('should return obj', () => {
const mockBoard = setupPlayingBoard();
const mockEnpassant = 44;
const mockTarget = 16;
const mockPiece = mockBoard[23];
const mockDefending = startingPieceLocations('black');
const enpassantMove = wasEnpassantMove(
mockPiece,
mockBoard,
mockTarget,
mockEnpassant,
mockDefending,
);
expect(enpassantMove.defending).toEqual(mockDefending);
expect(enpassantMove.board).toEqual(mockBoard);
});
});
<file_sep>import { King, Queen, Rook, Knight, Bishop, Pawn } from './pieceCreaters';
function setPawn(color, board) {
let row = color === 'white' ? 48 : 8;
for (let i = 0; i < 8; i++) {
let location = i + row;
let piece = new Pawn(color);
board[location] = piece;
}
return board;
}
function setRook(color, board) {
return setHigherLevel(color, Rook, [0, 7], board);
}
function setKnight(color, board) {
return setHigherLevel(color, Knight, [1, 6], board);
}
function setBishop(color, board) {
return setHigherLevel(color, Bishop, [2, 5], board);
}
function setQueen(color, board) {
var spot = color === 'white' ? [3] : [4];
return setHigherLevel(color, Queen, spot, board);
}
function setKing(color, board) {
var spot = color === 'white' ? [4] : [3];
return setHigherLevel(color, King, spot, board);
}
function setHigherLevel(color, type, spot, board) {
const LAST_ROW = 56;
const TOP_ROW = 0;
var row = color === 'white' ? LAST_ROW : TOP_ROW;
var spots = spot.map(rowIndex => rowIndex + row);
spots.forEach(spot => {
let piece = new type(color);
board[spot] = piece;
});
return board;
}
export { setKing, setQueen, setBishop, setRook, setPawn, setKnight };
<file_sep>export const MOVE = 'MOVE';
export const WHITE_MOVE = 'WHITE_MOVE'
export const BLACK_MOVE = 'BLACK_MOVE'
|
9f3436f56641de270db74a69e3a87f2e4279f93b
|
[
"JavaScript"
] | 24
|
JavaScript
|
rayzlui/chess
|
4ada565a6b6c808d3b92e443c044a83acee6eccf
|
b1d1818e147480ffd05538363f42a06a68a1274d
|
refs/heads/main
|
<repo_name>maidsafe/terraform-ci-infra<file_sep>/lambda/manage_runners/Dockerfile
FROM public.ecr.aws/lambda/python:3.9
COPY app.py requirements.txt ./
RUN python3.9 -m pip install -r requirements.txt -t .
CMD ["app.manage_runners"]
<file_sep>/lambda/tests/integration/test_manage_runners.py
import datetime
import hmac
import hashlib
import os
import pytest
from dateutil.tz import tzutc
from manage_runners import app
from manage_runners.app import ConfigurationError
TEST_SECRET = "<KEY>"
@pytest.fixture()
def workflow_job_webhook_payload():
"""
Example defined here:
https://docs.github.com/en/developers/webhooks-and-events/webhooks/webhook-events-and-payloads#workflow_job
The `action` has been changed from `in_progress` to `queued` because we'll be interested in
queued actions; we'll only launch an EC2 instance for a `queued` action.
This workflow_job payload will be the body of the HTTP request received by the Lambda.
"""
return """{
"action": "queued",
"workflow_job": {
"id": 2832853555,
"run_id": 940463255,
"run_url": "https://api.github.com/repos/octo-org/example-workflow/actions/runs/940463255",
"node_id": "MDg6Q2hlY2tSdW4yODMyODUzNT55",
"head_sha": "e3103f8eb03e1ad7f2331c5446b23c070fc54055",
"url": "https://api.github.com/repos/octo-org/example-workflow/actions/jobs/2832853555",
"html_url": "https://github.com/octo-org/example-workflow/runs/2832853555",
"status": "in_progress",
"conclusion": null,
"started_at": "2021-06-15T19:22:27Z",
"completed_at": null,
"name": "Test workflow",
"steps": [
{
"name": "Set up job",
"status": "in_progress",
"conclusion": null,
"number": 1,
"started_at": "2021-06-15T19:22:27.000Z",
"completed_at": null
}
],
"check_run_url": "https://api.github.com/repos/octo-org/example-workflow/check-runs/2832853555",
"labels": ["self-hosted"],
"runner_id": 1,
"runner_name": "my runner",
"runner_group_id": 2,
"runner_group_name": "my runner group"
},
"repository": {
"id": 376034443,
"node_id": "MDEwOlJlcG9zaXRvcnkzNzYwMzQ0ND55",
"name": "example-workflow",
"full_name": "octo-org/example-workflow",
"private": true,
"owner": {
"login": "octo-org",
"id": 33435655,
"node_id": "MDEyOk9yZ2FuaXphdGlvbjMzNDM1Nj55",
"avatar_url": "https://avatars.githubusercontent.com/u/21031067?s=460&u=d851e01410b4f1674f000ba7e0dc94e0b82cd9cc&v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/octo-org",
"html_url": "https://github.com/octo-org",
"followers_url": "https://api.github.com/users/octo-org/followers",
"following_url": "https://api.github.com/users/octo-org/following{/other_user}",
"gists_url": "https://api.github.com/users/octo-org/gists{/gist_id}",
"starred_url": "https://api.github.com/users/octo-org/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/octo-org/subscriptions",
"organizations_url": "https://api.github.com/users/octo-org/orgs",
"repos_url": "https://api.github.com/users/octo-org/repos",
"events_url": "https://api.github.com/users/octo-org/events{/privacy}",
"received_events_url": "https://api.github.com/users/octo-org/received_events",
"type": "Organization",
"site_admin": false
},
"html_url": "https://github.com/octo-org/example-workflow",
"description": "Test workflow",
"fork": false,
"url": "https://api.github.com/repos/octo-org/example-workflow",
"forks_url": "https://api.github.com/repos/octo-org/example-workflow/forks",
"keys_url": "https://api.github.com/repos/octo-org/example-workflow/keys{/key_id}",
"collaborators_url": "https://api.github.com/repos/octo-org/example-workflow/collaborators{/collaborator}",
"teams_url": "https://api.github.com/repos/octo-org/example-workflow/teams",
"hooks_url": "https://api.github.com/repos/octo-org/example-workflow/hooks",
"issue_events_url": "https://api.github.com/repos/octo-org/example-workflow/issues/events{/number}",
"events_url": "https://api.github.com/repos/octo-org/example-workflow/events",
"assignees_url": "https://api.github.com/repos/octo-org/example-workflow/assignees{/user}",
"branches_url": "https://api.github.com/repos/octo-org/example-workflow/branches{/branch}",
"tags_url": "https://api.github.com/repos/octo-org/example-workflow/tags",
"blobs_url": "https://api.github.com/repos/octo-org/example-workflow/git/blobs{/sha}",
"git_tags_url": "https://api.github.com/repos/octo-org/example-workflow/git/tags{/sha}",
"git_refs_url": "https://api.github.com/repos/octo-org/example-workflow/git/refs{/sha}",
"trees_url": "https://api.github.com/repos/octo-org/example-workflow/git/trees{/sha}",
"statuses_url": "https://api.github.com/repos/octo-org/example-workflow/statuses/{sha}",
"languages_url": "https://api.github.com/repos/octo-org/example-workflow/languages",
"stargazers_url": "https://api.github.com/repos/octo-org/example-workflow/stargazers",
"contributors_url": "https://api.github.com/repos/octo-org/example-workflow/contributors",
"subscribers_url": "https://api.github.com/repos/octo-org/example-workflow/subscribers",
"subscription_url": "https://api.github.com/repos/octo-org/example-workflow/subscription",
"commits_url": "https://api.github.com/repos/octo-org/example-workflow/commits{/sha}",
"git_commits_url": "https://api.github.com/repos/octo-org/example-workflow/git/commits{/sha}",
"comments_url": "https://api.github.com/repos/octo-org/example-workflow/comments{/number}",
"issue_comment_url": "https://api.github.com/repos/octo-org/example-workflow/issues/comments{/number}",
"contents_url": "https://api.github.com/repos/octo-org/example-workflow/contents/{+path}",
"compare_url": "https://api.github.com/repos/octo-org/example-workflow/compare/{base}...{head}",
"merges_url": "https://api.github.com/repos/octo-org/example-workflow/merges",
"archive_url": "https://api.github.com/repos/octo-org/example-workflow/{archive_format}{/ref}",
"downloads_url": "https://api.github.com/repos/octo-org/example-workflow/downloads",
"issues_url": "https://api.github.com/repos/octo-org/example-workflow/issues{/number}",
"pulls_url": "https://api.github.com/repos/octo-org/example-workflow/pulls{/number}",
"milestones_url": "https://api.github.com/repos/octo-org/example-workflow/milestones{/number}",
"notifications_url": "https://api.github.com/repos/octo-org/example-workflow/notifications{?since,all,participating}",
"labels_url": "https://api.github.com/repos/octo-org/example-workflow/labels{/name}",
"releases_url": "https://api.github.com/repos/octo-org/example-workflow/releases{/id}",
"deployments_url": "https://api.github.com/repos/octo-org/example-workflow/deployments",
"created_at": "2021-06-11T13:29:13Z",
"updated_at": "2021-06-11T13:33:01Z",
"pushed_at": "2021-06-11T13:32:58Z",
"git_url": "git://github.com/octo-org/example-workflow.git",
"ssh_url": "git@github.com:octo-org/example-workflow.git",
"clone_url": "https://github.com/octo-org/example-workflow.git",
"svn_url": "https://github.com/octo-org/example-workflow",
"homepage": null,
"size": 1,
"stargazers_count": 0,
"watchers_count": 0,
"language": null,
"has_issues": true,
"has_projects": true,
"has_downloads": true,
"has_wiki": true,
"has_pages": false,
"forks_count": 0,
"mirror_url": null,
"archived": false,
"disabled": false,
"open_issues_count": 0,
"license": null,
"forks": 0,
"open_issues": 0,
"watchers": 0,
"default_branch": "main"
},
"organization": {
"login": "octo-org",
"id": 33435655,
"node_id": "MDEyOk9yZ2FuaXphdGlvbjMzNDM1Nj55",
"url": "https://api.github.com/orgs/octo-org",
"repos_url": "https://api.github.com/orgs/octo-org/repos",
"events_url": "https://api.github.com/orgs/octo-org/events",
"hooks_url": "https://api.github.com/orgs/octo-org/hooks",
"issues_url": "https://api.github.com/orgs/octo-org/issues",
"members_url": "https://api.github.com/orgs/octo-org/members{/member}",
"public_members_url": "https://api.github.com/orgs/octo-org/public_members{/member}",
"avatar_url": "https://avatars.githubusercontent.com/u/21031067?s=460&u=d851e01410b4f1674f000ba7e0dc94e0b82cd9cc&v=4",
"description": "octo-org"
},
"sender": {
"login": "octocat",
"id": 319655,
"node_id": "MDQ6VXNlcjMxOTY1NQ55",
"avatar_url": "https://avatars.githubusercontent.com/u/21031067?s=460&u=d851e01410b4f1674f000ba7e0dc94e0b82cd9cc&v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/octocat",
"html_url": "https://github.com/octocat",
"followers_url": "https://api.github.com/users/octocat/followers",
"following_url": "https://api.github.com/users/octocat/following{/other_user}",
"gists_url": "https://api.github.com/users/octocat/gists{/gist_id}",
"starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/octocat/subscriptions",
"organizations_url": "https://api.github.com/users/octocat/orgs",
"repos_url": "https://api.github.com/users/octocat/repos",
"events_url": "https://api.github.com/users/octocat/events{/privacy}",
"received_events_url": "https://api.github.com/users/octocat/received_events",
"type": "User",
"site_admin": true
}
}"""
@pytest.fixture()
def apigw_event():
"""Generates API GW Event"""
return {
"body": "",
"resource": "/{proxy+}",
"requestContext": {
"resourceId": "123456",
"apiId": "1234567890",
"resourcePath": "/{proxy+}",
"httpMethod": "POST",
"requestId": "c6af9ac6-7b61-11e6-9a41-93e8deadbeef",
"accountId": "123456789012",
"identity": {
"apiKey": "",
"userArn": "",
"cognitoAuthenticationType": "",
"caller": "",
"userAgent": "Custom User Agent String",
"user": "",
"cognitoIdentityPoolId": "",
"cognitoIdentityId": "",
"cognitoAuthenticationProvider": "",
"sourceIp": "127.0.0.1",
"accountId": "",
},
"stage": "prod",
},
"queryStringParameters": {"foo": "bar"},
"headers": {
"Via": "1.1 08f323deadbeefa7af34d5feb414ce27.cloudfront.net (CloudFront)",
"Accept-Language": "en-US,en;q=0.8",
"CloudFront-Is-Desktop-Viewer": "true",
"CloudFront-Is-SmartTV-Viewer": "false",
"CloudFront-Is-Mobile-Viewer": "false",
"X-Forwarded-For": "127.0.0.1, 127.0.0.2",
"CloudFront-Viewer-Country": "US",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"Upgrade-Insecure-Requests": "1",
"X-Forwarded-Port": "443",
"Host": "1234567890.execute-api.us-east-1.amazonaws.com",
"X-Forwarded-Proto": "https",
"X-Amz-Cf-Id": "aaaaaaaaaae3VYQb9jd-nvCd-de396Uhbp027Y2JvkCPNLmGJHqlaA==",
"CloudFront-Is-Tablet-Viewer": "false",
"Cache-Control": "max-age=0",
"User-Agent": "Custom User Agent String",
"CloudFront-Forwarded-Proto": "https",
"Accept-Encoding": "gzip, deflate, sdch",
},
"pathParameters": {"proxy": "/examplepath"},
"httpMethod": "POST",
"stageVariables": {"baz": "qux"},
"path": "/examplepath",
}
@pytest.fixture()
def describe_instances_response():
return {
"Reservations": [
{
"Groups": [],
"Instances": [
{
"AmiLaunchIndex": 0,
"ImageId": "ami-05b371382b07cb80a",
"InstanceId": "i-0d63d1911b0c34cf7",
"InstanceType": "t2.medium",
"KeyName": "gha_runner_image_builder",
"LaunchTime": datetime.datetime(
2022, 11, 16, 15, 29, 38, tzinfo=tzutc()
),
"Monitoring": {"State": "disabled"},
"Placement": {
"AvailabilityZone": "eu-west-2a",
"GroupName": "",
"Tenancy": "default",
},
"PrivateDnsName": "ip-10-0-0-128.eu-west-2.compute.internal",
"PrivateIpAddress": "10.0.0.128",
"ProductCodes": [],
"PublicDnsName": "",
"PublicIpAddress": "172.16.31.10",
"State": {"Code": 16, "Name": "running"},
"StateTransitionReason": "",
"SubnetId": "subnet-08486e3b32f903438",
"VpcId": "vpc-0571e788c4263aeb3",
"Architecture": "x86_64",
"BlockDeviceMappings": [
{
"DeviceName": "/dev/sda1",
"Ebs": {
"AttachTime": datetime.datetime(
2022, 11, 16, 15, 29, 38, tzinfo=tzutc()
),
"DeleteOnTermination": True,
"Status": "attached",
"VolumeId": "vol-06318a4cc96429a43",
},
}
],
"ClientToken": "<PASSWORD>8f9f564",
"EbsOptimized": False,
"EnaSupport": True,
"Hypervisor": "xen",
"NetworkInterfaces": [
{
"Association": {
"IpOwnerId": "amazon",
"PublicDnsName": "",
"PublicIp": "172.16.31.10",
},
"Attachment": {
"AttachTime": datetime.datetime(
2022, 11, 16, 15, 29, 38, tzinfo=tzutc()
),
"AttachmentId": "eni-attach-043aa5db24f41c29f",
"DeleteOnTermination": True,
"DeviceIndex": 0,
"Status": "attached",
"NetworkCardIndex": 0,
},
"Description": "",
"Groups": [
{
"GroupName": "gha_runner_image_builder",
"GroupId": "sg-0f802f984aa514480",
}
],
"Ipv6Addresses": [],
"MacAddress": "06:7f:c2:a3:79:9e",
"NetworkInterfaceId": "eni-04a15d49979939d56",
"OwnerId": "389640522532",
"PrivateIpAddress": "10.0.0.128",
"PrivateIpAddresses": [
{
"Association": {
"IpOwnerId": "amazon",
"PublicDnsName": "",
"PublicIp": "172.16.31.10",
},
"Primary": True,
"PrivateIpAddress": "10.0.0.128",
}
],
"SourceDestCheck": True,
"Status": "in-use",
"SubnetId": "subnet-08486e3b32f903438",
"VpcId": "vpc-0571e788c4263aeb3",
"InterfaceType": "interface",
}
],
"RootDeviceName": "/dev/sda1",
"RootDeviceType": "ebs",
"SecurityGroups": [
{
"GroupName": "gha_runner_image_builder",
"GroupId": "sg-0f802f984aa514480",
}
],
"SourceDestCheck": True,
"VirtualizationType": "hvm",
"CpuOptions": {"CoreCount": 2, "ThreadsPerCore": 1},
"CapacityReservationSpecification": {
"CapacityReservationPreference": "open"
},
"HibernationOptions": {"Configured": False},
"MetadataOptions": {
"State": "applied",
"HttpTokens": "optional",
"HttpPutResponseHopLimit": 1,
"HttpEndpoint": "enabled",
"HttpProtocolIpv6": "disabled",
"InstanceMetadataTags": "disabled",
},
"EnclaveOptions": {"Enabled": False},
"PlatformDetails": "Linux/UNIX",
"UsageOperation": "RunInstances",
"UsageOperationUpdateTime": datetime.datetime(
2022, 11, 16, 15, 29, 38, tzinfo=tzutc()
),
"PrivateDnsNameOptions": {
"HostnameType": "ip-name",
"EnableResourceNameDnsARecord": False,
"EnableResourceNameDnsAAAARecord": False,
},
"MaintenanceOptions": {"AutoRecovery": "default"},
}
],
"OwnerId": "389640522532",
"ReservationId": "r-079ac49c9238b5903",
},
{
"Groups": [],
"Instances": [
{
"AmiLaunchIndex": 0,
"ImageId": "ami-05b371382b07cb80a",
"InstanceId": "i-0462bd6a044280798",
"InstanceType": "t2.medium",
"KeyName": "gha_runner_image_builder",
"LaunchTime": datetime.datetime(
2022, 11, 16, 15, 30, 2, tzinfo=tzutc()
),
"Monitoring": {"State": "disabled"},
"Placement": {
"AvailabilityZone": "eu-west-2a",
"GroupName": "",
"Tenancy": "default",
},
"PrivateDnsName": "ip-10-0-0-211.eu-west-2.compute.internal",
"PrivateIpAddress": "10.0.0.211",
"ProductCodes": [],
"PublicDnsName": "",
"PublicIpAddress": "192.168.3.11",
"State": {"Code": 16, "Name": "running"},
"StateTransitionReason": "",
"SubnetId": "subnet-08486e3b32f903438",
"VpcId": "vpc-0571e788c4263aeb3",
"Architecture": "x86_64",
"BlockDeviceMappings": [
{
"DeviceName": "/dev/sda1",
"Ebs": {
"AttachTime": datetime.datetime(
2022, 11, 16, 15, 30, 2, tzinfo=tzutc()
),
"DeleteOnTermination": True,
"Status": "attached",
"VolumeId": "vol-0a570751e897807f7",
},
}
],
"ClientToken": "<PASSWORD>",
"EbsOptimized": False,
"EnaSupport": True,
"Hypervisor": "xen",
"NetworkInterfaces": [
{
"Association": {
"IpOwnerId": "amazon",
"PublicDnsName": "",
"PublicIp": "192.168.3.11",
},
"Attachment": {
"AttachTime": datetime.datetime(
2022, 11, 16, 15, 30, 2, tzinfo=tzutc()
),
"AttachmentId": "eni-attach-059ae5ff374bfab6e",
"DeleteOnTermination": True,
"DeviceIndex": 0,
"Status": "attached",
"NetworkCardIndex": 0,
},
"Description": "",
"Groups": [
{
"GroupName": "gha_runner_image_builder",
"GroupId": "sg-0f802f984aa514480",
}
],
"Ipv6Addresses": [],
"MacAddress": "06:90:a4:9a:68:cc",
"NetworkInterfaceId": "eni-09b544ec73b766acc",
"OwnerId": "389640522532",
"PrivateIpAddress": "10.0.0.211",
"PrivateIpAddresses": [
{
"Association": {
"IpOwnerId": "amazon",
"PublicDnsName": "",
"PublicIp": "192.168.3.11",
},
"Primary": True,
"PrivateIpAddress": "10.0.0.211",
}
],
"SourceDestCheck": True,
"Status": "in-use",
"SubnetId": "subnet-08486e3b32f903438",
"VpcId": "vpc-0571e788c4263aeb3",
"InterfaceType": "interface",
}
],
"RootDeviceName": "/dev/sda1",
"RootDeviceType": "ebs",
"SecurityGroups": [
{
"GroupName": "gha_runner_image_builder",
"GroupId": "sg-0f802f984aa514480",
}
],
"SourceDestCheck": True,
"VirtualizationType": "hvm",
"CpuOptions": {"CoreCount": 2, "ThreadsPerCore": 1},
"CapacityReservationSpecification": {
"CapacityReservationPreference": "open"
},
"HibernationOptions": {"Configured": False},
"MetadataOptions": {
"State": "applied",
"HttpTokens": "optional",
"HttpPutResponseHopLimit": 1,
"HttpEndpoint": "enabled",
"HttpProtocolIpv6": "disabled",
"InstanceMetadataTags": "disabled",
},
"EnclaveOptions": {"Enabled": False},
"PlatformDetails": "Linux/UNIX",
"UsageOperation": "RunInstances",
"UsageOperationUpdateTime": datetime.datetime(
2022, 11, 16, 15, 30, 2, tzinfo=tzutc()
),
"PrivateDnsNameOptions": {
"HostnameType": "ip-name",
"EnableResourceNameDnsARecord": False,
"EnableResourceNameDnsAAAARecord": False,
},
"MaintenanceOptions": {"AutoRecovery": "default"},
}
],
"OwnerId": "389640522532",
"ReservationId": "r-08184d3d1061e282d",
},
],
"ResponseMetadata": {
"RequestId": "0890266c-21c4-4e3f-b91c-dd90ac590cbe",
"HTTPStatusCode": 200,
"HTTPHeaders": {
"x-amzn-requestid": "0890266c-21c4-4e3f-b91c-dd90ac590cbe",
"cache-control": "no-cache, no-store",
"strict-transport-security": "max-age=31536000; includeSubDomains",
"vary": "accept-encoding",
"content-type": "text/xml;charset=UTF-8",
"transfer-encoding": "chunked",
"date": "Wed, 16 Nov 2022 15:57:57 GMT",
"server": "AmazonEC2",
},
"RetryAttempts": 0,
},
}
def generate_signature(secret, payload):
"""
See the Github documentation here:
https://docs.github.com/en/developers/webhooks-and-events/webhooks/securing-your-webhooks#validating-payloads-from-github
Github send the signature in a `X-Hub-Signature-256` header. It's a hash of the workflow_job
payload, using the secret that's defined on the Github app. We use a fake secret here. When the
Lambda is deployed the `GITHUB_APP_SECRET` environment variable will be set to the real secret.
"""
hmac_gen = hmac.new(secret, payload, hashlib.sha256)
digest = "sha256=" + hmac_gen.hexdigest()
return digest
@pytest.mark.skip(reason="full integration test for debugging")
def test_manage_runners_with_queued_job_integration(
apigw_event, workflow_job_webhook_payload
):
"""
An integration test that can be used for debugging.
To run it, remove the skip and set all the environment variables to the values used in
the real environment. You also need to supply the keys of an AWS user who has
permission to run instances. For example:
export AWS_ACCESS_KEY_ID=<access key id>
export AWS_SECRET_ACCESS_KEY=<secret access key>
export AWS_DEFAULT_REGION=eu-west-2
export AMI_ID=ami-05b371382b07cb80a
export EC2_INSTANCE_TYPE=t2.medium
export EC2_KEY_NAME=gha_runner_image_builder
export EC2_SECURITY_GROUP_ID=sg-0f802f984aa514480
export EC2_VPC_SUBNET_ID=subnet-08486e3b32f903438
export GITHUB_APP_ID=<app id>
export GITHUB_APP_PRIVATE_KEY_BASE64=<base64 encoded private key>
export GITHUB_APP_SECRET=<app secret>
pytest tests/integration
"""
github_app_secret = os.getenv("GITHUB_APP_SECRET")
if not github_app_secret:
raise ConfigurationError("The GITHUB_APP_SECRET variable must be set")
apigw_event["body"] = workflow_job_webhook_payload
apigw_event["headers"]["X-Hub-Signature-256"] = generate_signature(
github_app_secret.encode(), workflow_job_webhook_payload.encode()
)
response = app.manage_runners(apigw_event, "")
print(response)
@pytest.mark.skip(reason="full integration test for debugging")
def test_manage_runners_with_completed_job_integration(
apigw_event, workflow_job_webhook_payload
):
"""
An integration test that can be used for debugging.
To run it, set all the environment variables to the values used in the real
environment. You also need to supply the keys of an AWS user who has
permission to run instances. For example:
export AWS_ACCESS_KEY_ID=<access key id>
export AWS_SECRET_ACCESS_KEY=<secret access key>
export AWS_DEFAULT_REGION=eu-west-2
export AMI_ID=ami-05b371382b07cb80a
export EC2_INSTANCE_TYPE=t2.medium
export EC2_KEY_NAME=gha_runner_image_builder
export EC2_SECURITY_GROUP_ID=sg-0f802f984aa514480
export EC2_VPC_SUBNET_ID=subnet-08486e3b32f903438
export GITHUB_APP_ID=<app id>
export GITHUB_APP_PRIVATE_KEY_BASE64=<base64 encoded private key>
export GITHUB_APP_SECRET=<app secret>
pytest tests/integration
"""
github_app_secret = os.getenv("GITHUB_APP_SECRET")
if not github_app_secret:
raise ConfigurationError("The GITHUB_APP_SECRET variable must be set")
payload_with_different_action = workflow_job_webhook_payload.replace(
"queued", "completed"
)
apigw_event["body"] = payload_with_different_action
apigw_event["headers"]["X-Hub-Signature-256"] = generate_signature(
github_app_secret.encode(), payload_with_different_action.encode()
)
response = app.manage_runners(apigw_event, "")
print(response)
<file_sep>/Makefile
SHELL := /bin/bash
REGISTRY_URI := dkr.ecr.eu-west-2.amazonaws.com
REPO_NAME := manage_runners
STACK_NAME := manage-runners
TAG_NAME := python3.9-v1
infrastructure:
terraform init
terraform apply -auto-approve -var-file=secrets.tfvars
.ONESHELL:
build-image:
security_group_id=$$(terraform output -raw gha_runner_security_group_name | xargs)
subnet_id=$$(terraform output subnet_name | xargs | awk '{ print $$2 }' | sed s/,//)
packer init .
packer build -var="security_group_id=$$security_group_id" \
-var="subnet_id=$$subnet_id" gha-runner.pkr.hcl
deploy-create-instance-function:
(
cd lambda/manage_runners
docker build \
--tag $$AWS_ACCOUNT_NUMBER.${REGISTRY_URI}/${REPO_NAME}:${TAG_NAME} \
.
)
docker push $$AWS_ACCOUNT_NUMBER.${REGISTRY_URI}/${REPO_NAME}:${TAG_NAME}
(
security_group_id=$$(terraform output -raw gha_runner_image_security_group_name | xargs)
subnet_id=$$(terraform output subnet_name | xargs | awk '{ print $$2 }' | sed s/,//)
cd lambda
sam deploy \
--stack-name ${STACK_NAME} \
--template template.yaml \
--resolve-image-repos \
--s3-bucket maidsafe-ci-infra \
--s3-prefix manage_runners_lambda \
--parameter-overrides Ec2SecurityGroupId=$$security_group_id Ec2VpcSubnetId=$$subnet_id
)
clean-create-instance-function:
(
cd lambda
sam delete --stack-name ${STACK_NAME} --no-prompts --region eu-west-2
)
<file_sep>/scripts/init-runner.sh
#!/bin/bash
TERRAFORM_VERSION="1.3.5"
TERRAFORM_ARCHIVE_NAME="terraform_${TERRAFORM_VERSION}_linux_amd64.zip"
TERRAFORM_URL="https://releases.hashicorp.com/terraform/${TERRAFORM_VERSION}/${TERRAFORM_ARCHIVE_NAME}"
sudo DEBIAN_FRONTEND=noninteractive apt update
retry_count=1
packages_installed="false"
while [[ $retry_count -le 20 ]]; do
echo "Attempting to install packages..."
# All these packages are necessary for a full build of all safe_network code,
# including test binaries.
sudo DEBIAN_FRONTEND=noninteractive apt install -y \
build-essential docker.io git jq libssl-dev musl-tools pkg-config ripgrep unzip
exit_code=$?
if [[ $exit_code -eq 0 ]]; then
echo "packages installed successfully"
packages_installed="true"
break
fi
echo "Failed to install all packages."
echo "Attempted $retry_count times. Will retry up to 20 times. Sleeping for 10 seconds."
((retry_count++))
sleep 10
# Without running this again there are times when it will just fail on every retry.
sudo DEBIAN_FRONTEND=noninteractive apt update
done
if [[ "$packages_installed" == "false" ]]; then
echo "Failed to install all packages"
exit 1
fi
sudo systemctl enable docker
sudo usermod --groups docker ubuntu
curl -L -O https://static.rust-lang.org/rustup/dist/x86_64-unknown-linux-gnu/rustup-init
chmod +x rustup-init
./rustup-init --default-toolchain stable -y --no-modify-path
# Make Cargo related binaries available in a system-wide location.
# This prevents difficulties with having to source ~/.cargo/env in every shell
# step in an actions workflow.
sudo ln -s ~/.cargo/bin/* /usr/local/bin
rustup target add x86_64-unknown-linux-musl
cd /tmp
curl -O "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip"
unzip awscli-exe-linux-x86_64.zip
sudo ./aws/install
curl -O $TERRAFORM_URL
unzip $TERRAFORM_ARCHIVE_NAME
sudo mv terraform /usr/local/bin
<file_sep>/lambda/manage_runners/requirements.txt
boto3
black
cryptography
pyjwt
requests
<file_sep>/README.md
# Terraform CI Infrastructure
Defines infrastructure for CI-related processes.
We have a requirement for build agents with improved speed and memory capacity than those offered by
the Github Actions infrastructure. This repository automates the creation of a VPC where EC2
instances can be launched and used as a runner for a job in Github Actions. The image for the runner
is also automated. Both configurations can be extended as need be, as and when new requirements
arise.
There are instructions for building the infrastructure, but we may also automate these processes
using Github Actions workflows.
## Building the Infrastructure
Install Terraform on your platform, using at least version 1.3.0.
The Terraform run will create a VPC with a NAT gateway to enable internet access. Internet access is
required for building the AMI, and the connection to the Github Actions infrastructure is also made
via port 443.
There are therefore two different security groups: one for building the AMI and the other for
running the agent during the CI process. The former group will open inbound SSH and outbound port
80/443, and the latter will only open outbound port 443.
To create the infrastructure you should use the `gha_runner_infra` user.
Define the following environment variables:
```
AWS_ACCESS_KEY_ID=<access key ID of gha_runner_infra>
AWS_DEFAULT_REGION=eu-west-2
AWS_SECRET_ACCESS_KEY=<secret access key of gha_runner_infra>
```
Now run `make infrastructure`.
## Building the Runner Image
The AMI is defined using a Packer template. Install Packer on your platform, using at least version
1.8.3.
The private key for the `gha_runner_image_builder` key pair must be obtained and placed somewhere,
with `chmod 0600` permissions. If lost, a new key pair can be generated and redefined in the
`main.tf` Terraform manifest.
You should use the `gha_runner_image_builder` user.
Define the following environment variables:
```
AWS_ACCESS_KEY_ID=<access key ID of gha_runner_image_builder>
AWS_DEFAULT_REGION=eu-west-2
AWS_SECRET_ACCESS_KEY=<secret access key of gha_runner_image_builder>
PACKER_VAR_ssh_private_key_file_path=<path to file>
```
Now run `make build-image`.
## Deploying the Create Instance Lambda Function
This process requires the creation of the Terraform infrastructure above.
The Github app for the self-hosted runner is installed at the organisation level. The app allows you
to provide a webhook where it will post a `workflow_job` event. This webhook hits an AWS Lambda
function, which then launches an EC2 instance.
The Lambda function is deployed using the [AWS SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/install-sam-cli.html), so install this.
You should use the `gha_runner_deploy` user for this process.
The Lambda is packaged in a Docker container, which gets pushed to the private registry on the AWS
account. You need to login to the registry with the `gha_runner_deploy` user:
```
aws ecr get-login-password --region eu-west-2 | docker login --username AWS --password-stdin <AWS_ACCOUNT_NO.dkr.ecr.eu-west-2.amazonaws.com
```
Replace the account number here with our AWS account number.
Define the following environment variables:
```
AWS_ACCOUNT_NUMBER=<account number>
AWS_ACCESS_KEY_ID=<access key ID of gha_runner_image_builder>
AWS_DEFAULT_REGION=eu-west-2
AWS_SECRET_ACCESS_KEY=<secret access key of gha_runner_image_builder>
```
Now run `deploy-create-instance-function`.
## Modifying the Infrastructure
We should strive to keep the infrastructure entirely automated and avoid manual interventions.
Update the Terraform configuration to make your change, then run a `terraform plan`. Open a PR and
submit the output of the plan in the description. After review and merge, we can then run a
`terraform apply` to change the infrastructure. Soon we should be able to automate this with an
Actions workflow.
<file_sep>/lambda/tests/unit/test_manage_runners.py
import datetime
import hmac
import hashlib
import json
import pytest
from dateutil.tz import tzutc
from manage_runners import app
from manage_runners.app import ConfigurationError
from unittest.mock import call
TEST_SECRET = "<KEY>"
@pytest.fixture()
def workflow_job_webhook_payload():
"""
Example defined here:
https://docs.github.com/en/developers/webhooks-and-events/webhooks/webhook-events-and-payloads#workflow_job
The `action` has been changed from `in_progress` to `queued` because we'll be interested in
queued actions; we'll only launch an EC2 instance for a `queued` action.
This workflow_job payload will be the body of the HTTP request received by the Lambda.
"""
return """{
"action": "queued",
"workflow_job": {
"id": 2832853555,
"run_id": 940463255,
"run_url": "https://api.github.com/repos/octo-org/example-workflow/actions/runs/940463255",
"node_id": "MDg6Q2hlY2tSdW4yODMyODUzNT55",
"head_sha": "e3103f8eb03e1ad7f2331c5446b23c070fc54055",
"url": "https://api.github.com/repos/octo-org/example-workflow/actions/jobs/2832853555",
"html_url": "https://github.com/octo-org/example-workflow/runs/2832853555",
"status": "in_progress",
"conclusion": null,
"started_at": "2021-06-15T19:22:27Z",
"completed_at": null,
"name": "Test workflow",
"steps": [
{
"name": "Set up job",
"status": "in_progress",
"conclusion": null,
"number": 1,
"started_at": "2021-06-15T19:22:27.000Z",
"completed_at": null
}
],
"check_run_url": "https://api.github.com/repos/octo-org/example-workflow/check-runs/2832853555",
"labels": ["self-hosted"],
"runner_id": 1,
"runner_name": "my runner",
"runner_group_id": 2,
"runner_group_name": "my runner group"
},
"repository": {
"id": 376034443,
"node_id": "MDEwOlJlcG9zaXRvcnkzNzYwMzQ0ND55",
"name": "example-workflow",
"full_name": "octo-org/example-workflow",
"private": true,
"owner": {
"login": "octo-org",
"id": 33435655,
"node_id": "MDEyOk9yZ2FuaXphdGlvbjMzNDM1Nj55",
"avatar_url": "https://avatars.githubusercontent.com/u/21031067?s=460&u=d851e01410b4f1674f000ba7e0dc94e0b82cd9cc&v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/octo-org",
"html_url": "https://github.com/octo-org",
"followers_url": "https://api.github.com/users/octo-org/followers",
"following_url": "https://api.github.com/users/octo-org/following{/other_user}",
"gists_url": "https://api.github.com/users/octo-org/gists{/gist_id}",
"starred_url": "https://api.github.com/users/octo-org/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/octo-org/subscriptions",
"organizations_url": "https://api.github.com/users/octo-org/orgs",
"repos_url": "https://api.github.com/users/octo-org/repos",
"events_url": "https://api.github.com/users/octo-org/events{/privacy}",
"received_events_url": "https://api.github.com/users/octo-org/received_events",
"type": "Organization",
"site_admin": false
},
"html_url": "https://github.com/octo-org/example-workflow",
"description": "Test workflow",
"fork": false,
"url": "https://api.github.com/repos/octo-org/example-workflow",
"forks_url": "https://api.github.com/repos/octo-org/example-workflow/forks",
"keys_url": "https://api.github.com/repos/octo-org/example-workflow/keys{/key_id}",
"collaborators_url": "https://api.github.com/repos/octo-org/example-workflow/collaborators{/collaborator}",
"teams_url": "https://api.github.com/repos/octo-org/example-workflow/teams",
"hooks_url": "https://api.github.com/repos/octo-org/example-workflow/hooks",
"issue_events_url": "https://api.github.com/repos/octo-org/example-workflow/issues/events{/number}",
"events_url": "https://api.github.com/repos/octo-org/example-workflow/events",
"assignees_url": "https://api.github.com/repos/octo-org/example-workflow/assignees{/user}",
"branches_url": "https://api.github.com/repos/octo-org/example-workflow/branches{/branch}",
"tags_url": "https://api.github.com/repos/octo-org/example-workflow/tags",
"blobs_url": "https://api.github.com/repos/octo-org/example-workflow/git/blobs{/sha}",
"git_tags_url": "https://api.github.com/repos/octo-org/example-workflow/git/tags{/sha}",
"git_refs_url": "https://api.github.com/repos/octo-org/example-workflow/git/refs{/sha}",
"trees_url": "https://api.github.com/repos/octo-org/example-workflow/git/trees{/sha}",
"statuses_url": "https://api.github.com/repos/octo-org/example-workflow/statuses/{sha}",
"languages_url": "https://api.github.com/repos/octo-org/example-workflow/languages",
"stargazers_url": "https://api.github.com/repos/octo-org/example-workflow/stargazers",
"contributors_url": "https://api.github.com/repos/octo-org/example-workflow/contributors",
"subscribers_url": "https://api.github.com/repos/octo-org/example-workflow/subscribers",
"subscription_url": "https://api.github.com/repos/octo-org/example-workflow/subscription",
"commits_url": "https://api.github.com/repos/octo-org/example-workflow/commits{/sha}",
"git_commits_url": "https://api.github.com/repos/octo-org/example-workflow/git/commits{/sha}",
"comments_url": "https://api.github.com/repos/octo-org/example-workflow/comments{/number}",
"issue_comment_url": "https://api.github.com/repos/octo-org/example-workflow/issues/comments{/number}",
"contents_url": "https://api.github.com/repos/octo-org/example-workflow/contents/{+path}",
"compare_url": "https://api.github.com/repos/octo-org/example-workflow/compare/{base}...{head}",
"merges_url": "https://api.github.com/repos/octo-org/example-workflow/merges",
"archive_url": "https://api.github.com/repos/octo-org/example-workflow/{archive_format}{/ref}",
"downloads_url": "https://api.github.com/repos/octo-org/example-workflow/downloads",
"issues_url": "https://api.github.com/repos/octo-org/example-workflow/issues{/number}",
"pulls_url": "https://api.github.com/repos/octo-org/example-workflow/pulls{/number}",
"milestones_url": "https://api.github.com/repos/octo-org/example-workflow/milestones{/number}",
"notifications_url": "https://api.github.com/repos/octo-org/example-workflow/notifications{?since,all,participating}",
"labels_url": "https://api.github.com/repos/octo-org/example-workflow/labels{/name}",
"releases_url": "https://api.github.com/repos/octo-org/example-workflow/releases{/id}",
"deployments_url": "https://api.github.com/repos/octo-org/example-workflow/deployments",
"created_at": "2021-06-11T13:29:13Z",
"updated_at": "2021-06-11T13:33:01Z",
"pushed_at": "2021-06-11T13:32:58Z",
"git_url": "git://github.com/octo-org/example-workflow.git",
"ssh_url": "git@github.com:octo-org/example-workflow.git",
"clone_url": "https://github.com/octo-org/example-workflow.git",
"svn_url": "https://github.com/octo-org/example-workflow",
"homepage": null,
"size": 1,
"stargazers_count": 0,
"watchers_count": 0,
"language": null,
"has_issues": true,
"has_projects": true,
"has_downloads": true,
"has_wiki": true,
"has_pages": false,
"forks_count": 0,
"mirror_url": null,
"archived": false,
"disabled": false,
"open_issues_count": 0,
"license": null,
"forks": 0,
"open_issues": 0,
"watchers": 0,
"default_branch": "main"
},
"organization": {
"login": "octo-org",
"id": 33435655,
"node_id": "MDEyOk9yZ2FuaXphdGlvbjMzNDM1Nj55",
"url": "https://api.github.com/orgs/octo-org",
"repos_url": "https://api.github.com/orgs/octo-org/repos",
"events_url": "https://api.github.com/orgs/octo-org/events",
"hooks_url": "https://api.github.com/orgs/octo-org/hooks",
"issues_url": "https://api.github.com/orgs/octo-org/issues",
"members_url": "https://api.github.com/orgs/octo-org/members{/member}",
"public_members_url": "https://api.github.com/orgs/octo-org/public_members{/member}",
"avatar_url": "https://avatars.githubusercontent.com/u/21031067?s=460&u=d851e01410b4f1674f000ba7e0dc94e0b82cd9cc&v=4",
"description": "octo-org"
},
"sender": {
"login": "octocat",
"id": 319655,
"node_id": "MDQ6VXNlcjMxOTY1NQ55",
"avatar_url": "https://avatars.githubusercontent.com/u/21031067?s=460&u=d851e01410b4f1674f000ba7e0dc94e0b82cd9cc&v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/octocat",
"html_url": "https://github.com/octocat",
"followers_url": "https://api.github.com/users/octocat/followers",
"following_url": "https://api.github.com/users/octocat/following{/other_user}",
"gists_url": "https://api.github.com/users/octocat/gists{/gist_id}",
"starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/octocat/subscriptions",
"organizations_url": "https://api.github.com/users/octocat/orgs",
"repos_url": "https://api.github.com/users/octocat/repos",
"events_url": "https://api.github.com/users/octocat/events{/privacy}",
"received_events_url": "https://api.github.com/users/octocat/received_events",
"type": "User",
"site_admin": true
}
}"""
@pytest.fixture()
def apigw_event():
"""Generates API GW Event"""
return {
"body": "",
"resource": "/{proxy+}",
"requestContext": {
"resourceId": "123456",
"apiId": "1234567890",
"resourcePath": "/{proxy+}",
"httpMethod": "POST",
"requestId": "c6af9ac6-7b61-11e6-9a41-93e8deadbeef",
"accountId": "123456789012",
"identity": {
"apiKey": "",
"userArn": "",
"cognitoAuthenticationType": "",
"caller": "",
"userAgent": "Custom User Agent String",
"user": "",
"cognitoIdentityPoolId": "",
"cognitoIdentityId": "",
"cognitoAuthenticationProvider": "",
"sourceIp": "127.0.0.1",
"accountId": "",
},
"stage": "prod",
},
"queryStringParameters": {"foo": "bar"},
"headers": {
"Via": "1.1 08f323deadbeefa7af34d5feb414ce27.cloudfront.net (CloudFront)",
"Accept-Language": "en-US,en;q=0.8",
"CloudFront-Is-Desktop-Viewer": "true",
"CloudFront-Is-SmartTV-Viewer": "false",
"CloudFront-Is-Mobile-Viewer": "false",
"X-Forwarded-For": "127.0.0.1, 127.0.0.2",
"CloudFront-Viewer-Country": "US",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"Upgrade-Insecure-Requests": "1",
"X-Forwarded-Port": "443",
"Host": "1234567890.execute-api.us-east-1.amazonaws.com",
"X-Forwarded-Proto": "https",
"X-Amz-Cf-Id": "aaaaaaaaaae3VYQb9jd-nvCd-de396Uhbp027Y2JvkCPNLmGJHqlaA==",
"CloudFront-Is-Tablet-Viewer": "false",
"Cache-Control": "max-age=0",
"User-Agent": "Custom User Agent String",
"CloudFront-Forwarded-Proto": "https",
"Accept-Encoding": "gzip, deflate, sdch",
},
"pathParameters": {"proxy": "/examplepath"},
"httpMethod": "POST",
"stageVariables": {"baz": "qux"},
"path": "/examplepath",
}
@pytest.fixture()
def describe_instances_response():
return {
"Reservations": [
{
"Groups": [],
"Instances": [
{
"AmiLaunchIndex": 0,
"ImageId": "ami-05b371382b07cb80a",
"InstanceId": "i-0d63d1911b0c34cf7",
"InstanceType": "t2.medium",
"KeyName": "gha_runner_image_builder",
"LaunchTime": datetime.datetime(
2022, 11, 16, 15, 29, 38, tzinfo=tzutc()
),
"Monitoring": {"State": "disabled"},
"Placement": {
"AvailabilityZone": "eu-west-2a",
"GroupName": "",
"Tenancy": "default",
},
"PrivateDnsName": "ip-10-0-0-128.eu-west-2.compute.internal",
"PrivateIpAddress": "10.0.0.128",
"ProductCodes": [],
"PublicDnsName": "",
"PublicIpAddress": "172.16.31.10",
"State": {"Code": 16, "Name": "running"},
"StateTransitionReason": "",
"SubnetId": "subnet-08486e3b32f903438",
"VpcId": "vpc-0571e788c4263aeb3",
"Architecture": "x86_64",
"BlockDeviceMappings": [
{
"DeviceName": "/dev/sda1",
"Ebs": {
"AttachTime": datetime.datetime(
2022, 11, 16, 15, 29, 38, tzinfo=tzutc()
),
"DeleteOnTermination": True,
"Status": "attached",
"VolumeId": "vol-06318a4cc96429a43",
},
}
],
"ClientToken": "<PASSWORD>df-720468f9f564",
"EbsOptimized": False,
"EnaSupport": True,
"Hypervisor": "xen",
"NetworkInterfaces": [
{
"Association": {
"IpOwnerId": "amazon",
"PublicDnsName": "",
"PublicIp": "172.16.31.10",
},
"Attachment": {
"AttachTime": datetime.datetime(
2022, 11, 16, 15, 29, 38, tzinfo=tzutc()
),
"AttachmentId": "eni-attach-043aa5db24f41c29f",
"DeleteOnTermination": True,
"DeviceIndex": 0,
"Status": "attached",
"NetworkCardIndex": 0,
},
"Description": "",
"Groups": [
{
"GroupName": "gha_runner_image_builder",
"GroupId": "sg-0f802f984aa514480",
}
],
"Ipv6Addresses": [],
"MacAddress": "06:7f:c2:a3:79:9e",
"NetworkInterfaceId": "eni-04a15d49979939d56",
"OwnerId": "389640522532",
"PrivateIpAddress": "10.0.0.128",
"PrivateIpAddresses": [
{
"Association": {
"IpOwnerId": "amazon",
"PublicDnsName": "",
"PublicIp": "172.16.31.10",
},
"Primary": True,
"PrivateIpAddress": "10.0.0.128",
}
],
"SourceDestCheck": True,
"Status": "in-use",
"SubnetId": "subnet-08486e3b32f903438",
"VpcId": "vpc-0571e788c4263aeb3",
"InterfaceType": "interface",
}
],
"RootDeviceName": "/dev/sda1",
"RootDeviceType": "ebs",
"SecurityGroups": [
{
"GroupName": "gha_runner_image_builder",
"GroupId": "sg-0f802f984aa514480",
}
],
"SourceDestCheck": True,
"VirtualizationType": "hvm",
"CpuOptions": {"CoreCount": 2, "ThreadsPerCore": 1},
"CapacityReservationSpecification": {
"CapacityReservationPreference": "open"
},
"HibernationOptions": {"Configured": False},
"MetadataOptions": {
"State": "applied",
"HttpTokens": "optional",
"HttpPutResponseHopLimit": 1,
"HttpEndpoint": "enabled",
"HttpProtocolIpv6": "disabled",
"InstanceMetadataTags": "disabled",
},
"EnclaveOptions": {"Enabled": False},
"PlatformDetails": "Linux/UNIX",
"UsageOperation": "RunInstances",
"UsageOperationUpdateTime": datetime.datetime(
2022, 11, 16, 15, 29, 38, tzinfo=tzutc()
),
"PrivateDnsNameOptions": {
"HostnameType": "ip-name",
"EnableResourceNameDnsARecord": False,
"EnableResourceNameDnsAAAARecord": False,
},
"MaintenanceOptions": {"AutoRecovery": "default"},
}
],
"OwnerId": "389640522532",
"ReservationId": "r-079ac49c9238b5903",
},
{
"Groups": [],
"Instances": [
{
"AmiLaunchIndex": 0,
"ImageId": "ami-05b371382b07cb80a",
"InstanceId": "i-0462bd6a044280798",
"InstanceType": "t2.medium",
"KeyName": "gha_runner_image_builder",
"LaunchTime": datetime.datetime(
2022, 11, 16, 15, 30, 2, tzinfo=tzutc()
),
"Monitoring": {"State": "disabled"},
"Placement": {
"AvailabilityZone": "eu-west-2a",
"GroupName": "",
"Tenancy": "default",
},
"PrivateDnsName": "ip-10-0-0-211.eu-west-2.compute.internal",
"PrivateIpAddress": "10.0.0.211",
"ProductCodes": [],
"PublicDnsName": "",
"PublicIpAddress": "172.16.17.32",
"State": {"Code": 16, "Name": "running"},
"StateTransitionReason": "",
"SubnetId": "subnet-08486e3b32f903438",
"VpcId": "vpc-0571e788c4263aeb3",
"Architecture": "x86_64",
"BlockDeviceMappings": [
{
"DeviceName": "/dev/sda1",
"Ebs": {
"AttachTime": datetime.datetime(
2022, 11, 16, 15, 30, 2, tzinfo=tzutc()
),
"DeleteOnTermination": True,
"Status": "attached",
"VolumeId": "vol-0a570751e897807f7",
},
}
],
"ClientToken": "<PASSWORD>",
"EbsOptimized": False,
"EnaSupport": True,
"Hypervisor": "xen",
"NetworkInterfaces": [
{
"Association": {
"IpOwnerId": "amazon",
"PublicDnsName": "",
"PublicIp": "172.16.17.32",
},
"Attachment": {
"AttachTime": datetime.datetime(
2022, 11, 16, 15, 30, 2, tzinfo=tzutc()
),
"AttachmentId": "eni-attach-059ae5ff374bfab6e",
"DeleteOnTermination": True,
"DeviceIndex": 0,
"Status": "attached",
"NetworkCardIndex": 0,
},
"Description": "",
"Groups": [
{
"GroupName": "gha_runner_image_builder",
"GroupId": "sg-0f802f984aa514480",
}
],
"Ipv6Addresses": [],
"MacAddress": "06:90:a4:9a:68:cc",
"NetworkInterfaceId": "eni-09b544ec73b766acc",
"OwnerId": "389640522532",
"PrivateIpAddress": "10.0.0.211",
"PrivateIpAddresses": [
{
"Association": {
"IpOwnerId": "amazon",
"PublicDnsName": "",
"PublicIp": "172.16.17.32",
},
"Primary": True,
"PrivateIpAddress": "10.0.0.211",
}
],
"SourceDestCheck": True,
"Status": "in-use",
"SubnetId": "subnet-08486e3b32f903438",
"VpcId": "vpc-0571e788c4263aeb3",
"InterfaceType": "interface",
}
],
"RootDeviceName": "/dev/sda1",
"RootDeviceType": "ebs",
"SecurityGroups": [
{
"GroupName": "gha_runner_image_builder",
"GroupId": "sg-0f802f984aa514480",
}
],
"SourceDestCheck": True,
"VirtualizationType": "hvm",
"CpuOptions": {"CoreCount": 2, "ThreadsPerCore": 1},
"CapacityReservationSpecification": {
"CapacityReservationPreference": "open"
},
"HibernationOptions": {"Configured": False},
"MetadataOptions": {
"State": "applied",
"HttpTokens": "optional",
"HttpPutResponseHopLimit": 1,
"HttpEndpoint": "enabled",
"HttpProtocolIpv6": "disabled",
"InstanceMetadataTags": "disabled",
},
"EnclaveOptions": {"Enabled": False},
"PlatformDetails": "Linux/UNIX",
"UsageOperation": "RunInstances",
"UsageOperationUpdateTime": datetime.datetime(
2022, 11, 16, 15, 30, 2, tzinfo=tzutc()
),
"PrivateDnsNameOptions": {
"HostnameType": "ip-name",
"EnableResourceNameDnsARecord": False,
"EnableResourceNameDnsAAAARecord": False,
},
"MaintenanceOptions": {"AutoRecovery": "default"},
}
],
"OwnerId": "389640522532",
"ReservationId": "r-08184d3d1061e282d",
},
],
"ResponseMetadata": {
"RequestId": "0890266c-21c4-4e3f-b91c-dd90ac590cbe",
"HTTPStatusCode": 200,
"HTTPHeaders": {
"x-amzn-requestid": "0890266c-21c4-4e3f-b91c-dd90ac590cbe",
"cache-control": "no-cache, no-store",
"strict-transport-security": "max-age=31536000; includeSubDomains",
"vary": "accept-encoding",
"content-type": "text/xml;charset=UTF-8",
"transfer-encoding": "chunked",
"date": "Wed, 16 Nov 2022 15:57:57 GMT",
"server": "AmazonEC2",
},
"RetryAttempts": 0,
},
}
def generate_signature(secret, payload):
"""
See the Github documentation here:
https://docs.github.com/en/developers/webhooks-and-events/webhooks/securing-your-webhooks#validating-payloads-from-github
Github send the signature in a `X-Hub-Signature-256` header. It's a hash of the workflow_job
payload, using the secret that's defined on the Github app. We use a fake secret here. When the
Lambda is deployed the `GITHUB_APP_SECRET` environment variable will be set to the real secret.
"""
hmac_gen = hmac.new(secret, payload, hashlib.sha256)
digest = "sha256=" + hmac_gen.hexdigest()
return digest
def test_manage_runners_with_queued_job(
apigw_event, workflow_job_webhook_payload, mocker, monkeypatch
):
monkeypatch.setenv("AMI_ID", "ami-092fe15da02f3f1bg")
monkeypatch.setenv(
"EC2_IAM_INSTANCE_PROFILE",
"arn:aws:iam::389640522532:instance-profile/upload_build_artifacts",
)
monkeypatch.setenv("EC2_INSTANCE_TYPE", "t2.medium")
monkeypatch.setenv("EC2_KEY_NAME", "gha_runner_image_builder")
monkeypatch.setenv("EC2_SECURITY_GROUP_ID", "sg-0f802f984aa514480")
monkeypatch.setenv("EC2_VPC_SUBNET_ID", "subnet-08486e3b32f903438")
monkeypatch.setenv("GITHUB_APP_SECRET", TEST_SECRET)
apigw_event["body"] = workflow_job_webhook_payload
apigw_event["headers"]["X-Hub-Signature-256"] = generate_signature(
TEST_SECRET.encode(), workflow_job_webhook_payload.encode()
)
boto_client_mock = mocker.patch("manage_runners.app.boto3.client")
boto_client_mock.return_value.run_instances.return_value = {
"Instances": [{"InstanceId": "i-123456"}]
}
registration_token_mock = mocker.patch("manage_runners.app.get_registration_token")
registration_token_mock.return_value = "<KEY>"
spy = mocker.spy(app, "get_user_data_script")
response = app.manage_runners(apigw_event, "")
data = json.loads(response["body"])
base64_encoded_user_data_script = spy.spy_return
boto_client_mock.return_value.run_instances.assert_called_with(
IamInstanceProfile={
"Arn": "arn:aws:iam::389640522532:instance-profile/upload_build_artifacts"
},
ImageId="ami-092fe15da02f3f1bg",
InstanceType="t2.medium",
KeyName="gha_runner_image_builder",
MaxCount=1,
MinCount=1,
SecurityGroupIds=["sg-0f802f984aa514480"],
SubnetId="subnet-08486e3b32f903438",
UserData=base64_encoded_user_data_script,
)
assert response["statusCode"] == 201
assert "instance_id" in response["body"]
assert data["instance_id"] == "i-123456"
def test_manage_runners_with_completed_workflow_job_action(
apigw_event,
workflow_job_webhook_payload,
describe_instances_response,
mocker,
monkeypatch,
):
monkeypatch.setenv("GITHUB_APP_SECRET", TEST_SECRET)
payload_with_different_action = workflow_job_webhook_payload.replace(
"queued", "completed"
)
apigw_event["body"] = payload_with_different_action
apigw_event["headers"]["X-Hub-Signature-256"] = generate_signature(
TEST_SECRET.encode(), payload_with_different_action.encode()
)
boto_client_mock = mocker.patch("manage_runners.app.boto3.client")
boto_client_mock.return_value.describe_instances.return_value = (
describe_instances_response
)
get_idle_runners_mock = mocker.patch("manage_runners.app.get_idle_runners")
get_idle_runners_mock.return_value = [
(3155, "ip-10-0-0-128"),
(3156, "ip-10-0-0-211"),
]
remove_runner_mock = mocker.patch("manage_runners.app.remove_runner")
response = app.manage_runners(apigw_event, "")
boto_client_mock.return_value.terminate_instances.assert_called_with(
InstanceIds=["i-0d63d1911b0c34cf7", "i-0462bd6a044280798"],
)
remove_runner_mock.assert_has_calls([call(3155), call(3156)])
assert response["statusCode"] == 201
assert "i-0d63d1911b0c34cf7" in response["TerminatedInstanceIds"]
assert "i-0462bd6a044280798" in response["TerminatedInstanceIds"]
def test_manage_runners_with_in_progress_workflow_job_action(
apigw_event, workflow_job_webhook_payload, monkeypatch
):
monkeypatch.setenv("GITHUB_APP_SECRET", TEST_SECRET)
payload_with_different_action = workflow_job_webhook_payload.replace(
"queued", "in_progress"
)
apigw_event["body"] = payload_with_different_action
apigw_event["headers"]["X-Hub-Signature-256"] = generate_signature(
TEST_SECRET.encode(), payload_with_different_action.encode()
)
response = app.manage_runners(apigw_event, "")
assert response["statusCode"] == 200
assert (
response["body"]
== "A workflow_job with an `in_progress` action will not be processed"
)
def test_manage_runners_with_non_self_hosted_label(
apigw_event, workflow_job_webhook_payload, monkeypatch
):
monkeypatch.setenv("GITHUB_APP_SECRET", TEST_SECRET)
payload_with_non_self_hosted = workflow_job_webhook_payload.replace(
"self-hosted", "ubuntu-latest"
)
apigw_event["body"] = payload_with_non_self_hosted
apigw_event["headers"]["X-Hub-Signature-256"] = generate_signature(
TEST_SECRET.encode(), payload_with_non_self_hosted.encode()
)
response = app.manage_runners(apigw_event, "")
assert response["statusCode"] == 200
assert (
response["body"]
== "An EC2 instance will only be launched for a self-hosted job"
)
def test_manage_runners_sha256_sig_not_present(
apigw_event, workflow_job_webhook_payload
):
apigw_event["body"] = workflow_job_webhook_payload
response = app.manage_runners(apigw_event, "")
assert response["statusCode"] == 400
assert response["body"] == "The request did not contain the signature header"
def test_manage_runners_sha256_sig_does_not_match(
apigw_event, workflow_job_webhook_payload, monkeypatch
):
monkeypatch.setenv("GITHUB_APP_SECRET", TEST_SECRET)
apigw_event["body"] = workflow_job_webhook_payload
apigw_event["headers"]["X-Hub-Signature-256"] = generate_signature(
"another secret".encode(), workflow_job_webhook_payload.encode()
)
response = app.manage_runners(apigw_event, "")
assert response["statusCode"] == 401
assert response["body"] == "Signature received is not valid"
def test_manage_runners_github_secret_is_not_set(
apigw_event, workflow_job_webhook_payload
):
apigw_event["body"] = workflow_job_webhook_payload
apigw_event["headers"]["X-Hub-Signature-256"] = generate_signature(
TEST_SECRET.encode(), workflow_job_webhook_payload.encode()
)
with pytest.raises(
ConfigurationError, match="The GITHUB_APP_SECRET variable must be set"
):
app.manage_runners(apigw_event, "")
def test_manage_runners_ami_id_is_not_set(
apigw_event, workflow_job_webhook_payload, monkeypatch
):
monkeypatch.setenv("GITHUB_APP_SECRET", TEST_SECRET)
apigw_event["body"] = workflow_job_webhook_payload
apigw_event["headers"]["X-Hub-Signature-256"] = generate_signature(
TEST_SECRET.encode(), workflow_job_webhook_payload.encode()
)
with pytest.raises(ConfigurationError, match="The AMI_ID variable must be set"):
app.manage_runners(apigw_event, "")
def test_manage_runners_instance_type_is_not_set(
apigw_event, workflow_job_webhook_payload, monkeypatch
):
apigw_event["body"] = workflow_job_webhook_payload
apigw_event["headers"]["X-Hub-Signature-256"] = generate_signature(
TEST_SECRET.encode(), workflow_job_webhook_payload.encode()
)
monkeypatch.setenv("GITHUB_APP_SECRET", TEST_SECRET)
monkeypatch.setenv("AMI_ID", "ami-092fe15da02f3f1bg")
monkeypatch.setenv(
"EC2_IAM_INSTANCE_PROFILE",
"arn:aws:iam::389640522532:instance-profile/upload_build_artifacts",
)
monkeypatch.setenv("EC2_KEY_NAME", "gha_runner_image_builder")
monkeypatch.setenv("EC2_SECURITY_GROUP_ID", "sg-0f802f984aa514480")
monkeypatch.setenv("EC2_VPC_SUBNET_ID", "subnet-08486e3b32f903438")
with pytest.raises(
ConfigurationError, match="The EC2_INSTANCE_TYPE variable must be set"
):
app.manage_runners(apigw_event, "")
def test_manage_runners_key_name_is_not_set(
apigw_event, workflow_job_webhook_payload, monkeypatch
):
apigw_event["body"] = workflow_job_webhook_payload
apigw_event["headers"]["X-Hub-Signature-256"] = generate_signature(
TEST_SECRET.encode(), workflow_job_webhook_payload.encode()
)
monkeypatch.setenv(
"EC2_IAM_INSTANCE_PROFILE",
"arn:aws:iam::389640522532:instance-profile/upload_build_artifacts",
)
monkeypatch.setenv("GITHUB_APP_SECRET", TEST_SECRET)
monkeypatch.setenv("AMI_ID", "ami-092fe15da02f3f1bg")
monkeypatch.setenv("EC2_INSTANCE_TYPE", "t2.medium")
monkeypatch.setenv("EC2_SECURITY_GROUP_ID", "sg-0f802f984aa514480")
monkeypatch.setenv("EC2_VPC_SUBNET_ID", "subnet-08486e3b32f903438")
with pytest.raises(
ConfigurationError, match="The EC2_KEY_NAME variable must be set"
):
app.manage_runners(apigw_event, "")
def test_manage_runners_security_group_id_is_not_set(
apigw_event, workflow_job_webhook_payload, monkeypatch
):
apigw_event["body"] = workflow_job_webhook_payload
apigw_event["headers"]["X-Hub-Signature-256"] = generate_signature(
TEST_SECRET.encode(), workflow_job_webhook_payload.encode()
)
monkeypatch.setenv("GITHUB_APP_SECRET", TEST_SECRET)
monkeypatch.setenv("AMI_ID", "ami-092fe15da02f3f1bg")
monkeypatch.setenv(
"EC2_IAM_INSTANCE_PROFILE",
"arn:aws:iam::389640522532:instance-profile/upload_build_artifacts",
)
monkeypatch.setenv("EC2_INSTANCE_TYPE", "t2.medium")
monkeypatch.setenv("EC2_KEY_NAME", "gha_runner_image_builder")
monkeypatch.setenv("EC2_VPC_SUBNET_ID", "subnet-08486e3b32f903438")
with pytest.raises(
ConfigurationError, match="The EC2_SECURITY_GROUP_ID variable must be set"
):
app.manage_runners(apigw_event, "")
def test_manage_runners_subnet_id_is_not_set(
apigw_event, workflow_job_webhook_payload, monkeypatch
):
apigw_event["body"] = workflow_job_webhook_payload
apigw_event["headers"]["X-Hub-Signature-256"] = generate_signature(
TEST_SECRET.encode(), workflow_job_webhook_payload.encode()
)
monkeypatch.setenv("GITHUB_APP_SECRET", TEST_SECRET)
monkeypatch.setenv("AMI_ID", "ami-092fe15da02f3f1bg")
monkeypatch.setenv(
"EC2_IAM_INSTANCE_PROFILE",
"arn:aws:iam::389640522532:instance-profile/upload_build_artifacts",
)
monkeypatch.setenv("EC2_INSTANCE_TYPE", "t2.medium")
monkeypatch.setenv("EC2_KEY_NAME", "gha_runner_image_builder")
monkeypatch.setenv("EC2_SECURITY_GROUP_ID", "sg-0f802f984aa514480")
with pytest.raises(
ConfigurationError, match="The EC2_VPC_SUBNET_ID variable must be set"
):
app.manage_runners(apigw_event, "")
def test_manage_runners_iam_instance_profile_is_not_set(
apigw_event, workflow_job_webhook_payload, monkeypatch
):
apigw_event["body"] = workflow_job_webhook_payload
apigw_event["headers"]["X-Hub-Signature-256"] = generate_signature(
TEST_SECRET.encode(), workflow_job_webhook_payload.encode()
)
monkeypatch.setenv("GITHUB_APP_SECRET", TEST_SECRET)
monkeypatch.setenv("AMI_ID", "ami-092fe15da02f3f1bg")
monkeypatch.setenv("EC2_INSTANCE_TYPE", "t2.medium")
monkeypatch.setenv("EC2_KEY_NAME", "gha_runner_image_builder")
monkeypatch.setenv("EC2_SECURITY_GROUP_ID", "sg-0f802f984aa514480")
monkeypatch.setenv("EC2_VPC_SUBNET_ID", "subnet-08486e3b32f903438")
with pytest.raises(
ConfigurationError, match="The EC2_IAM_INSTANCE_PROFILE variable must be set"
):
app.manage_runners(apigw_event, "")
<file_sep>/lambda/manage_runners/app.py
import base64
import boto3
import hmac
import hashlib
import json
import jwt
import logging
import os
import requests
import time
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
# The EC2 infrastructure executes the user data script as the root user and you
# don't have any control over that. However, the runner configuration doesn't
# allow execution as root, but you *do* need to install and start the service as
# root. Hence, a bunch of commands execute as the ubuntu user, then we switch
# back to root. The directory switches to the home directory are necessary.
# The registration token will be supplied before the script is passed to the
# RunInstances API.
USER_DATA_SCRIPT = """#!/bin/bash
output=$(file -b -s /dev/nvme1n1)
until [ "$output" == "data" ]
do
echo "$output"
echo "disk still not mounted..."
output=$(file -b -s /dev/nvme1n1)
done
mkfs -t ext4 /dev/nvme1n1
mkdir /mnt/data
mount /dev/nvme1n1 /mnt/data
mkdir /mnt/data/tmp
chmod 0777 /mnt/data/tmp
mkdir /mnt/data/runner
chown ubuntu:ubuntu /mnt/data/runner
mkdir /mnt/data/cargo
chown ubuntu:ubuntu /mnt/data/cargo
echo "CARGO_HOME=/mnt/data/cargo" >> /etc/environment
su ubuntu <<'EOF'
cd /home/ubuntu
REGISTRATION_TOKEN="__REGISTRATION_TOKEN__"
RUNNER_BASE_URL="https://github.com/actions/runner/releases/download"
RUNNER_VERSION="v2.299.1"
RUNNER_ARCHIVE_NAME="actions-runner-linux-x64-2.299.1.tar.gz"
SAFE_NETWORK_REPO_URL="https://github.com/maidsafe/safe_network"
cd /mnt/data/runner
mkdir actions-runner && cd actions-runner
curl -O -L ${RUNNER_BASE_URL}/${RUNNER_VERSION}/${RUNNER_ARCHIVE_NAME}
tar xvf ${RUNNER_ARCHIVE_NAME}
./config.sh --unattended \
--url "${SAFE_NETWORK_REPO_URL}" --token "${REGISTRATION_TOKEN}" --labels self-hosted
EOF
(
cd /mnt/data/runner/actions-runner
./svc.sh install ubuntu
./svc.sh start
)
"""
SIGNATURE_HEADER = "X-Hub-Signature-256"
class ConfigurationError(Exception):
pass
def get_installed_app_token():
"""
Gets a token for the installed Github App, which can then be used for the APIs that require it,
such as requesting a registration token for a runner.
The Github documentation outlines the full process:
https://docs.github.com/en/developers/apps/building-github-apps/authenticating-with-github-apps#authenticating-as-a-github-app
The summary is:
* Use the private key registered with the runner app installed on the organisation to generate
a JWT. Github requires sending an issue time and an expiry time for the token. The minus 60
seconds is for "clock drift."
* Authenticate with that token to get the app installation ID.
* Make another request with the installation ID and the same JWT to get an access token.
The private key is a PEM, but it's assigned to an environment variable as a base64-encoded
string without any newline characters, to avoid any issues with that. We can't read it from a
file because this code is executing in the context of a Lambda function.
"""
app_id = os.getenv("GITHUB_APP_ID")
if not app_id:
raise ConfigurationError("The GITHUB_APP_ID variable must be set")
private_key_base64 = os.getenv("GITHUB_APP_PRIVATE_KEY_BASE64")
if not private_key_base64:
raise ConfigurationError(
"The GITHUB_APP_PRIVATE_KEY_BASE64 variable must be set"
)
private_key = base64.b64decode(private_key_base64).decode("ascii")
iat = int(time.time()) - 60
exp = int(time.time()) + (10 * 60)
payload = {"iat": iat, "exp": exp, "iss": int(app_id)}
encoded_jwt = jwt.encode(payload, private_key, algorithm="RS256")
headers = {
"Authorization": f"Bearer {encoded_jwt}",
"Accept": "application/vnd.github+json",
}
response = requests.get("https://api.github.com/app/installations", headers=headers)
if response.status_code != 200:
logger.debug("Received unexpected response when requesting installation ID")
logger.debug(f"status_code: {response.status_code}")
logger.debug(f"text: {response.text}")
raise ConfigurationError("Unexpected response indicates configuration issue")
json = response.json()
installation_id = json[0]["id"]
response = requests.post(
f"https://api.github.com/app/installations/{installation_id}/access_tokens",
headers=headers,
)
json = response.json()
token = json["token"]
return token
def get_registration_token():
token = get_installed_app_token()
headers = {
"Authorization": f"Bearer {token}",
"Accept": "application/vnd.github+json",
}
response = requests.post(
"https://api.github.com/repos/maidsafe/safe_network/actions/runners/registration-token",
headers=headers,
)
json = response.json()
registration_token = json["token"]
return registration_token
def get_idle_runners():
token = get_installed_app_token()
headers = {
"Authorization": f"Bearer {token}",
"Accept": "application/vnd.github+json",
}
response = requests.get(
"https://api.github.com/repos/maidsafe/safe_network/actions/runners",
headers=headers,
)
json = response.json()
return [(x["id"], x["name"]) for x in json["runners"] if x["busy"] == False]
def remove_runner(id):
# The `workflow_job` event may have been received very quickly.
# Therefore, sleep for a few seconds in case it takes some time to be marked as idle.
time.sleep(3)
token = get_installed_app_token()
headers = {
"Authorization": f"Bearer {token}",
"Accept": "application/vnd.github+json",
}
response = requests.delete(
f"https://api.github.com/repos/maidsafe/safe_network/actions/runners/{id}",
headers=headers,
)
return response.status_code
def get_user_data_script(registration_token):
# This is only really in its own function for testing purposes.
# You can 'spy' on it and check the return value.
user_data_script_with_token = USER_DATA_SCRIPT.replace(
"__REGISTRATION_TOKEN__", registration_token
)
return user_data_script_with_token
def validate_env_vars():
ami_id = os.getenv("AMI_ID")
if not ami_id:
raise ConfigurationError("The AMI_ID variable must be set")
iam_instance_profile = os.getenv("EC2_IAM_INSTANCE_PROFILE")
if not iam_instance_profile:
raise ConfigurationError("The EC2_IAM_INSTANCE_PROFILE variable must be set")
instance_type = os.getenv("EC2_INSTANCE_TYPE")
if not instance_type:
raise ConfigurationError("The EC2_INSTANCE_TYPE variable must be set")
key_name = os.getenv("EC2_KEY_NAME")
if not key_name:
raise ConfigurationError("The EC2_KEY_NAME variable must be set")
security_group_id = os.getenv("EC2_SECURITY_GROUP_ID")
if not security_group_id:
raise ConfigurationError("The EC2_SECURITY_GROUP_ID variable must be set")
subnet_id = os.getenv("EC2_VPC_SUBNET_ID")
if not subnet_id:
raise ConfigurationError("The EC2_VPC_SUBNET_ID variable must be set")
return (
ami_id,
iam_instance_profile,
instance_type,
key_name,
security_group_id,
subnet_id,
)
def is_signature_valid(signature, payload):
secret = os.getenv("GITHUB_APP_SECRET")
if not secret:
raise ConfigurationError("The GITHUB_APP_SECRET variable must be set")
hmac_gen = hmac.new(secret.encode(), payload.encode(), hashlib.sha256)
digest = "sha256=" + hmac_gen.hexdigest()
return hmac.compare_digest(digest, signature)
def manage_runners(event, context):
request_headers = event["headers"]
if SIGNATURE_HEADER not in request_headers:
logger.debug("The request did not contain the signature header")
return {
"statusCode": 400,
"body": "The request did not contain the signature header",
}
signature = event["headers"][SIGNATURE_HEADER]
if not is_signature_valid(signature, event["body"]):
logger.debug("Signature received is not valid")
return {"statusCode": 401, "body": "Signature received is not valid"}
workflow_job = json.loads(event["body"])
action = workflow_job["action"]
logger.debug(f"Received workflow_job with {action} action")
if action == "in_progress":
logger.debug(
"A workflow_job with an `in_progress` action will not be processed"
)
return {
"statusCode": 200,
"body": "A workflow_job with an `in_progress` action will not be processed",
}
if "self-hosted" not in workflow_job["workflow_job"]["labels"]:
logger.debug("An EC2 instance will only be launched for a self-hosted job")
return {
"statusCode": 200,
"body": "An EC2 instance will only be launched for a self-hosted job",
}
response = {}
client = boto3.client("ec2")
if action == "queued":
(
ami_id,
iam_instance_profile,
instance_type,
key_name,
security_group_id,
subnet_id,
) = validate_env_vars()
registration_token = get_registration_token()
user_data_script_with_token = get_user_data_script(registration_token)
response = client.run_instances(
IamInstanceProfile={"Arn": iam_instance_profile},
ImageId=ami_id,
InstanceType=instance_type,
KeyName=key_name,
MaxCount=1,
MinCount=1,
SecurityGroupIds=[security_group_id],
SubnetId=subnet_id,
UserData=user_data_script_with_token,
)
instance_id = response["Instances"][0]["InstanceId"]
logger.debug(f"Launched EC2 instance with ID {instance_id}")
response = {
"statusCode": 201,
"body": json.dumps(
{
"instance_id": instance_id,
}
),
}
elif action == "completed":
idle_runners = get_idle_runners()
ec2_response = client.describe_instances()
instance_ids = []
for (runner_id, private_ip) in idle_runners:
for reservation in ec2_response["Reservations"]:
for instance in reservation["Instances"]:
if instance["PrivateDnsName"].startswith(private_ip):
instance_id = instance["InstanceId"]
instance_ids.append(instance_id)
for (runner_id, private_ip) in idle_runners:
logger.debug(f"Will remove idle runner {private_ip}")
remove_runner(runner_id)
logger.debug(f"Will terminate instances with IDs {instance_ids}")
client.terminate_instances(InstanceIds=instance_ids)
response = {"statusCode": 201, "TerminatedInstanceIds": instance_ids}
return response
|
553d05d29e295cbf62cc155f128dafec73d0e6dd
|
[
"Markdown",
"Makefile",
"Python",
"Text",
"Dockerfile",
"Shell"
] | 8
|
Dockerfile
|
maidsafe/terraform-ci-infra
|
858baf1d5db2da33b48eb39e8c2a293ecd001498
|
275b97a8a3ff1e0af7e945b82ae8b6059f18c0ce
|
refs/heads/master
|
<repo_name>RamashishSingh/image_processing<file_sep>/JPG_to_PngConverter.py
import sys
import os
# from pathlib import Path this is also can be used
from PIL import Image
#my try
# i = sys.argv[1]
# # ent = Path(i)
# # for s in ent.iterdir():
# # if Path(s) == 'pocedek/bulbasaur.jpg':
# # s1 = Image.open(s)
# # # s1.convert("s1.png",'png')
# # s1.save('s1.png','png')
# # print(s.name)
# j = os.listdir(i)
# for s in j:
# s.save('s.new','png')
#solution
opened_folder = sys.argv[1]
final_folder = sys.argv[2]
if not os.path.exists(final_folder):
os.makedirs(final_folder)
for filename in os.listdir(opened_folder):
img = Image.open(f'{opened_folder}{filename}')
clean_name = os.path.splitext(f'{filename}')[0]
img.save(f'{final_folder}{clean_name}.png','png')
print("alll done")
<file_sep>/image_processing.py
from PIL import Image,ImageFilter
img = Image.open('./pocedek/pikachu.jpg') #open image in python
img1 = Image.open('./pocedek/bulbasaur.jpg')
img2 = Image.open('./pocedek/charmander.jpg')
img3 = Image.open('./pocedek/charmander.jpg')
img4 = Image.open('./pocedek/squirtle.jpg')
box =(100,100,400,400)
region = img4.crop(box)
filtered_img = img.filter(ImageFilter.BLUR) #using filter on image for blur the image
filtered_img1 = img1.filter(ImageFilter.SHARPEN) #using filter for sharpen the image
filtered_img2 = img2.convert('L') #to convert image in grey (black and white)
filtered_img2 = img2.convert('1') #to convert image in grey dotted format
filtered_img3 = img3.convert('P') #to convert image in colour dotted format
resize= img3.resize((100,100))
img4.thumbnail((400,100)) # when use thumbnail it didn't give exact ration which you has written it return in an aspct set
# set by itself best aspect for thumbnail
print(img.format) # to check format of image
print(img.size) #to check size of image
print(img.mode) #to check mode of image
filtered_img.save("blur.png",'png') #to save image by its name and format
filtered_img1.save("sharpen.jpg",'jpeg')
filtered_img2.save("grey.jpg",'jpeg')
filtered_img3.save("grey.png",'png')
# filtered_img2.show() # showing converted image in new pop-window
resize.save('resize.png','png')
region.save('crop.png','png')
img4.save('thumbnail.jpg','jpeg')
print(img)
|
bc1856aa3fffb50a56a81abd18e0ee7a72ef7f86
|
[
"Python"
] | 2
|
Python
|
RamashishSingh/image_processing
|
e3b2db6440cf36b7654663c151d2a38ca2f0ad4c
|
b718c2160931fbd82214311b9ba276d8ac4779d9
|
refs/heads/master
|
<file_sep>import { Injectable } from '@angular/core';
import {LogMessage} from './log-message';
@Injectable()
export class AccessControlLogService {
logMessages: Array<LogMessage> = [];
constructor() { }
getAccessLog() {
return this.logMessages;
}
addAccessItem(person: string, message: string) {
let newLogMessage = {
person,
message,
createdAt: new Date()
}
this.logMessages.push(newLogMessage);
console.log(this.logMessages);
}
}
|
3ffbaeeaa5c8c53372c5ae58e5af5fffd66e1213
|
[
"TypeScript"
] | 1
|
TypeScript
|
fcovacarh/lab-angular-access-control
|
81a561667d4031768fb8118aeaeaa4605eeef1e2
|
6f321c86ec7327eba69d83532acf9451d63545e9
|
refs/heads/main
|
<file_sep>
public class Ejercicio5_Parientes
{
public String veriParientes (int a , int b){
String res ="";
if ((a%b==0)||(b%a==0)){
res ="Son parientes ";
}else{
res = "No son parientes ";
}
return res;
}
}
<file_sep>public class Ejercicio12_Divisor
{
public int dividir(int num ,int divisor){
int res =0;
while ( num >= divisor ){
num=num-divisor;
res =res +1;
}
return res;
}
}
<file_sep>
public class Ejer3Circunferencia
{
public double calcularCircunferencia (int radio ){
double pi = 3.14159;
return (radio*2)*pi;
}
}
<file_sep>
public class Ejercicio15_NumerosUnicornios
{
private int sumatoriaDig(int num1){
int res=0;
int numeroDigitos=contarDigitos(numero);
int aux=numeroDado;
int auxiliar=numeroDigitos;
if (numeroDigitos%2==0){
while ( auxiliar<= ((numeroDigitos/2)+1) ) {
}
}
}
private int contarDigitos(int num){
int res=0;
if (num==0){
res=1;
}else{
while (num!=0 ){
num=num /10;
res ++;
}
}
return res;
}
}
<file_sep>
public class Ejercicio1numeroDigitos
{
public int contarDigitos(int num){
int res=0;
if (num==0){
res=1;
}else{
while (num!=0 ){
num=num /10;
res ++;
}
}
return res;
}
}
<file_sep>
public class Ejercicio3_NumeroDariel{
public String verificarDia(int dia){
String res="";
if (dia <10){
res ="Es un dia Normal";
}else {
int dig1 = dia%10;
int dig2 =dia/10;
if((dig1%2==0 && dig2==0)||(dig1%2!=0 && dig2!=0)){
res="Es un dia Normal";
}else {
res="<NAME>";
}
}
return res;
}
}
<file_sep>
public class Ejercicio5_Acarreo
{
public int calcularAcarreo(int num1 ,int num2){
int res=0;
int acarreo=0;
while(num1>0 || num2>0){
int dig1=num1%10;
int dig2=num2%10;
int suma= dig1+dig2+acarreo;
if (suma>9){
res ++;
acarreo=1;
}else{
acarreo=0;
}
num1=num1/10;
num2=num2/10;
}
return res;
}
}
<file_sep>
public class Ejercicio4_Factorial
{
public int encontrarFactorial(int num){
int res=1;
if (num==0){
res=1;
}else{
for (int i=1;i<=num;i++){
res =res*i;
}
}
return res;
}
}
<file_sep>
public class Ejer6Intercambio
{
public String interacambiar(int num1,int num2,int num3){
String respuesta ="";
int aux = num1;
num1 = num2;
num2 = aux;
aux= num1;
num1= num3;
num3= aux;
respuesta = num1+" "+num2+" "+num3;
return respuesta;
}
}
<file_sep>
public class Ejercicio9_DecimalBinario
{
public int transformar(int num){
int res=0;
int mult=1;
while (num>0){
int residuo =num%2;
res = res +(residuo*mult);
num=num/2;
mult= mult*10;
}
return res;
}
}
<file_sep>
public class Ejercicio2_dodecagono
{
public int calcularArea (int radio ){
return 3*radio*radio;
}
}
<file_sep>
public class Ejercicio2_NumeroInvertido
{
public String inversorNumeral(int num1,int num2){
String res="";
int contador=0;
int exp=contarDigitos(num1);
if (num2 ==0){
res = ""+num1;
}else{
while (num2>contador ){
int dig = num1%10;
String aux=""+ dig +(num1/10);
res =res +aux+",";
num1= (num1/10)+ (dig*(int) Math.pow(10,(exp-1)));
contador++;
}
}
return res;
}
private int contarDigitos(int num){
int res=0;
if (num==0){
res=1;
}else{
while (num!=0 ){
num=num /10;
res ++;
}
}
return res;
}
}
<file_sep>
public class Organizador
{
public int cambiarPocision(int num1,int num2,int num3){
int respuesta =0;
num2 = num2*100;
num3= num3*10;
num1= num1*1;
respuesta = num2+num3+num1;
return respuesta;
}
}
<file_sep>
public class Ejercicio3_BinarioDecimal
{
public int conversorBinarioDecimal (int num){
int base=2;
int exponente=0;
int res=0;;
while (num>0){
int dig= num%10;
res = res+(dig*(int) Math.pow(base,exponente));
exponente=exponente+1;
num=num/10;
}
return res;
}
}
|
5b1095c39561d886a748d349741a00493cf4d3eb
|
[
"Java"
] | 14
|
Java
|
MarceloIporreI/Jatun-Respositorio
|
5e09e0aa38bec89bc34420bbb5ed4a95b3db67db
|
0a1d8330bd39e3f89367506ccc6979bc6d5a006e
|
refs/heads/master
|
<repo_name>dhrub-git/spring-annotations-demo1<file_sep>/src/com/hcl/academy/AnnotationsMain.java
package com.hcl.academy;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class AnnotationsMain {
public static void main(String[] args) {
//feed the context on the core container
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//get the bean from the context
Coach theCoach=context.getBean("myCoach",Coach.class);
//use the methods
System.out.println(theCoach.getDailyWorkout());
//close the context
context.close();
}
}
|
73786a0bd635dae0c0235d5c9cdf028fd970dd4a
|
[
"Java"
] | 1
|
Java
|
dhrub-git/spring-annotations-demo1
|
b0561c5b1485142c7910cfb3b93a32ea70faf981
|
6bed5b79fedff63411aa6c4fb67bd608db711b7e
|
refs/heads/master
|
<repo_name>dycor/twitbook<file_sep>/src/components/ImageUpload/index.js
import React from 'react';
import firebase from 'firebase';
import imageCompression from 'browser-image-compression';
const ImageUpload = ({setImageUrl , setBase64Image}) => {
const handleImageUpload = async (file) => {
//const ref = firebase.storage().ref();
//console.log('originalFile instanceof Blob', file instanceof Blob);
//console.log(`originalFile size ${file.size / 1024 / 1024} MB`);
const minifyOptions = {
maxSizeMB: 1,
maxWidthOrHeight: 720,
useWebWorker: true
}
try {
const compressedFile = await imageCompression(file, minifyOptions);
//console.log('compressedFile instanceof Blob', compressedFile instanceof Blob);
//console.log(`compressedFile size ${compressedFile.size / 1024 / 1024} MB`);
return compressedFile;
} catch (error) {
console.log(error);
}
};
const handleChange = async (e) => {
const file = e.target.files[0];
const minifiedFile = await handleImageUpload(file);
const ref = firebase.storage().ref();
const name = (+new Date()) + '-' + minifiedFile.name;
const dirFolder = 'tweets/';
const path = dirFolder + name;
const task = ref.child(path).put(minifiedFile);
task.then((snapshot) => {
snapshot.ref.getDownloadURL().then(function(downloadURL) {
if (document.querySelector('#uploaded-img')) {
document.querySelector('#uploaded-img').src = downloadURL;
document.querySelector('#uploaded-img').alt = name;
document.querySelector('#uploaded-img').title = name;
document.querySelector('#uploaded-img').style.display = "block";
}
let reader = new FileReader();
let base64 = '';
reader.readAsDataURL(minifiedFile);
reader.onload = function () {
base64 = reader.result;
setBase64Image(base64);
};
reader.onerror = function (error) {
console.log('Error: ', error);
};
setImageUrl(downloadURL);
});
})/*.catch((error) => {
switch (error.code) {
case 'storage/unauthorized':
break;
case 'storage/canceled':
break;
case 'storage/unknown':
break;
}
})*/;
}
return <div className="component-upload-image">
<label htmlFor="image-upload-input">Joindre une image</label>
<input id="image-upload-input" name="image-upload-input" type="file" onChange={handleChange}/>
<img id="uploaded-img" width="50%" alt=''/>
</div>
}
export default ImageUpload;
<file_sep>/src/components/NavBar/index.js
import React,{ useState, useContext} from 'react';
import {AppContext} from "../App/AppProvider";
import LoggedNav from "./LoggedNav";
import UnloggedNav from "./UnloggedNav";
const NavBar = () => {
const [active,setActive] = useState('home');
const { user } = useContext(AppContext);
return user ? <LoggedNav user={user} active={active} setActive={setActive}/> : <UnloggedNav active={active} setActive={setActive}/>;
};
export default NavBar;
<file_sep>/src/components/Retweet/index.js
import React,{ useEffect, useState, useContext } from 'react';
import { ReactComponent as RetweetIcon } from '../../static/icons/retweet.svg'
import { ReactComponent as UnRetweetIcon } from '../../static/icons/unretweet.svg'
import {AppContext} from "../App/AppProvider";
const Retweet = ({tweetId, nbRetweet}) => {
const { getStore, user, followers } = useContext(AppContext);
const [retweeted, setRetweeted]= useState(false);
const [countRetweet, setCountRetweet]= useState(nbRetweet);
const store = getStore();
const isRetweeted = async tweetId =>{
try {
if (user) return await store.collection("retweets").doc(user.userId + "_" + tweetId).get();
} catch (err) {
}
};
const unRetweet = tweetId => {
const createdAt = Date.now();
store.collection('retweets').doc(user.userId + "_" + tweetId).delete().then( () =>{
followers.forEach(userId => {
store.collection('feed').doc(userId)
.collection('tweets')
.add({path :`tweets/${tweetId}`,retweet: false,createdAt});
});
store.collection('feed').doc(user.id)
.collection('tweets')
.where('path', '==', 'tweets/'+tweetId)
.get().then(res => {
res.forEach(doc => {
store.collection('feed').doc(user.id).collection('tweets').doc(doc.id).update({retweet: false});
});
const tweetRef = store.collection('tweets').doc(tweetId);
tweetRef.get()
.then(doc => {
tweetRef.update({
NbRetweet: doc.data().NbRetweet - 1
}).then(() => setCountRetweet(countRetweet - 1));
});
})
});
};
const retweet = tweetId => {
const createdAt = Date.now();
store.collection('retweets').doc(user.userId + "_" + tweetId).set({
'userId': user.userId,
'tweetId': tweetId,
}).then( doc =>{
followers.forEach(userId => {
store.collection('feed').doc(userId)
.collection('tweets')
.add({path :`tweets/${tweetId}`,retweet: true,createdAt});
});
store.collection('feed').doc(user.id)
.collection('tweets')
.where('path', '==', 'tweets/'+tweetId).get()
.then(res => {
res.forEach(doc => {
store.collection('feed').doc(user.id)
.collection('tweets')
.doc(doc.id).update({retweet: true});
});
});
const tweetRef = store.collection('tweets').doc(tweetId);
tweetRef.get()
.then(doc => {
tweetRef.update({
NbRetweet: doc.data().NbRetweet + 1
}).then(() => setCountRetweet(countRetweet + 1));
});
});
};
const clickRetweet = () => {
retweeted?unRetweet(tweetId):retweet(tweetId);
setRetweeted(!retweeted);
};
useEffect(() => {
isRetweeted(tweetId).then(doc => setRetweeted(doc.exists));
}, [isRetweeted, tweetId]);
return retweeted ?
<span className="like"><UnRetweetIcon onClick={clickRetweet}></UnRetweetIcon>{countRetweet ?countRetweet :''}</span>
:<span className="like"><RetweetIcon onClick={clickRetweet}></RetweetIcon>{countRetweet ?countRetweet :''}</span>
};
export default Retweet;
<file_sep>/src/components/Profile/index.js
import React, { useContext,useState,useEffect,useRef } from 'react';
import {AppContext} from "../App/AppProvider";
import Spinner from "../Spinner";
import './style.scss';
import Tweets from "../Tweets";
import Tweet from "../Tweet";
const Profile = ({ match }) => {
const { getStore,user } = useContext(AppContext);
const [followed,setFollowed] = useState(false);
const [loading,setLoading] = useState(false);
const [profile,setProfile] = useState('');
const [displayTweets,setDisplayTweets] = useState(true);
const [tweetsLiked,setTweetsLiked] = useState([]);
const store = getStore();
const ref = useRef( { mounted: false });
const style = {color:'white'};
useEffect(() => {
if(!ref.current.mounted){
store.collection('users').where('username', '==', match.params.username).get().then( res => {
if(res.docs.length){
setProfile({id:res.docs[0].id,...res.docs[0].data()});
}
});
if(profile && user ){
store.collection('followers').where('follower', '==', user.id).where('followed', '==', profile.id).get().then( doc => {
if(doc.docs.length) setFollowed(true);
ref.current = { mounted: true };
});
}
}
});
const follow = () => {
if(followed) {
store.collection('followers').where('follower', '==', user.id).where('followed', '==', profile.id).get().then( doc => {
setFollowed(false);
doc.docs[0].ref.delete();
const followerRef = store.collection('users').doc(user.id);
followerRef.get()
.then(doc => {
followerRef.update({
nbFolloweds: doc.data().nbFolloweds -1
});
});
const followedRef = store.collection('users').doc(profile.id);
followedRef.get()
.then(doc => {
followedRef.update({
nbFollowers: doc.data().nbFollowers -1
}).then(() => setProfile({...profile , nbFollowers : profile.nbFollowers - 1}));
});
});
} else {
store.collection('followers').add({follower: user.id , followed: profile.id}).then( doc => {
const followerRef = store.collection('users').doc(user.id);
followerRef.get()
.then(doc => {
followerRef.update({
nbFolloweds: doc.data().nbFolloweds + 1
});
});
const followedRef = store.collection('users').doc(profile.id);
followedRef.get()
.then(doc => {
followedRef.update({
nbFollowers: doc.data().nbFollowers + 1
}).then(() => setProfile({...profile , nbFollowers : profile.nbFollowers + 1}));
});
setFollowed(true);
});
}
};
const fetchTweetLiked = () => {
setDisplayTweets(false);
setLoading(true);
store.collection('likes').where('userId', '==', profile.userId).get().then( doc => {
if(doc.docs.length){
var userTweets = [];
Promise.all(doc.docs.map(docLike => {
const path = 'tweets/'+docLike.data().tweetId;
return store.doc(path).get().then( tweet => userTweets.push({...tweet.data(), id: tweet.id}));
})).then(() => {
setTweetsLiked(userTweets);
setLoading(false);
})
} else {
setLoading(false);
}
});
};
return profile ? <>
<div className="component-profile">
<header>
<div className="profile-header">
{profile.image ? <img src={profile.image}/> : <img />}
<div className="profile-name">
<p className="name">{profile.pseudo}</p>
<p className="twitbook-tag">@{profile.username}</p>
<div className="follow-section">
<span>{profile.nbFolloweds} abonnements</span>
<span>{profile.nbFollowers} abonnés</span>
</div>
{ user.id !== profile.id ?<button onClick={follow} style={style} className="btn-primary twitbook-follow">{followed ? 'Ne plus suivre':'Suivre'}</button> : <></>}
</div>
</div>
</header>
<section className="bar">
<span className={displayTweets ? 'active' : '' } onClick={() => setDisplayTweets(true)}>Tweets</span>
<span className={!displayTweets ? 'active' : '' } onClick={() => fetchTweetLiked()}>J'aime</span>
</section>
{loading ? <Spinner/> :<></>}
{displayTweets ?
<Tweets profile={profile}/>
: <ul className="tweetsList">{tweetsLiked.map(tweet => <Tweet tweet={tweet} key={Math.random()} />) }</ul>
}
</div>
</> : <Spinner/>
};
export default Profile;
<file_sep>/src/components/App/AppProvider.js
import React, { createContext, Component } from "react";
import actions from './actions';
import publicActions from '../../helpers/public-actions';
import firebase from '@firebase/app';
import '@firebase/firestore'
import config from "../../helpers/Config";
export const AppContext = createContext({});
class AppProvider extends Component {
constructor(props) {
super(props);
if (!firebase.apps.length) {
this.firebase = firebase.initializeApp(config);
this.store = firebase.firestore();
this.store.enablePersistence().catch(err => {
if (err.code === "failed-precondition") {
// Multiple tabs open, persistence can only be enabled
// in one tab at a a time.
// ...
console.error(err);
} else if (err.code === "unimplemented") {
// The current browser does not support all of the
// features required to enable persistence
// ...
console.error(err);
}
});
}
const user = localStorage.getItem('user');
const followers = localStorage.getItem('followers');
this.state = {
user: user ? JSON.parse(user) : null,
followers : followers ? JSON.parse(followers) : [],
isOffline: false
};
}
setUser = user => this.setState({ user: user });
setFollowers = followers => this.setState({ followers: followers });
getFirebase = () => this.firebase;
getStore = () => this.store;
componentDidMount() {
this.handleConnectionChange();
window.addEventListener("online", this.handleConnectionChange);
window.addEventListener("offline", this.handleConnectionChange);
}
componentWillUnmount() {
window.removeEventListener("online", this.handleConnectionChange);
window.removeEventListener("offline", this.handleConnectionChange);
}
handleConnectionChange = () => {
const condition = navigator.onLine ? "online" : "offline";
if (condition === "online") {
const webPing = setInterval(() => {
fetch("//google.com", {
mode: "no-cors"
})
.then(() => {
this.setState({ isOffline: false }, () => {
return clearInterval(webPing);
});
})
.catch(() => this.setState({ isOffline: true }));
}, 2000);
return;
}
return this.setState({ isOffline: true });
};
render() {
return (
<AppContext.Provider
value={{ ...this.state, ...publicActions(this, actions) }}
>
<div ref={elem => (this.nv = elem)}>{this.props.children}</div>
</AppContext.Provider>
);
}
}
export default AppProvider;
<file_sep>/src/components/Image/BlurImageLoader.js
import React, { useState, useEffect } from "react";
const styles = (loaded, src) => {
return {
width: "100%",
height: "400px",
maxHeight: "4Ovh",
transition: "filter 1s ease",
filter: `${!loaded ? "blur(3px)" : "unset"}`,
backgroundImage: `url(${src})`,
backgroundPosition: "50% 50%",
backgroundOrigin: "border-box",
backgroundSize: "cover"
}
};
const BlurImageLoader = ({ placeholder, image, visible }) => {
const runOnce = true;
const [loadState, setLoadState] = useState({
src: placeholder,
loaded: false
});
useEffect(() => {
const img = new Image();
img.onload = () => {
setLoadState({
src: img.src,
loaded: true
});
};
if (visible) {
img.src = image;
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [visible, runOnce]);
return (
<header>
<figure>
<div style={styles(visible && loadState.loaded, loadState.src)} />
</figure>
</header>
)
};
export default BlurImageLoader;
<file_sep>/src/components/Tweet/newTweet.js
import React, {useState} from "react";
import ImageUpload from "../ImageUpload";
const NewTweet = ({newTweet , addTweet, setNewTweet, setClosed}) => {
const [imageUrl, setImageUrl] = useState('');
const [base64Image, setBase64Image] = useState('');
return <div className="add-tweet-component">
<div className="form-container">
<div className="options">
<button onClick={() => setClosed(true)} className="btn-primary btn-twitbook-button">Retour</button>
</div>
<div className="form">
<textarea rows={10} cols={35} value={newTweet} onChange={e => setNewTweet(e.target.value)} maxLength={280}/>
<ImageUpload setImageUrl={setImageUrl} setBase64Image={setBase64Image}/>
</div>
<div className="submit">
<button onClick={() => addTweet(imageUrl, base64Image)} className="btn-primary">Tweeter</button>
</div>
</div>
</div>
}
export default NewTweet;<file_sep>/src/components/SignUp/index.js
import React, {useContext,useState} from 'react';
import 'firebase/auth';
import uuid from 'uuid';
import { Link } from "react-router-dom";
import './style.scss';
import { AppContext } from "../App/AppProvider";
const SignUp = props => {
const { getFirebase,getStore } = useContext(AppContext);
const firebase = getFirebase();
const [email,setEmail] = useState('');
const [password,setPassword] = useState('');
const [firstname,setFirstname] = useState('');
const [lastname,setLastname] = useState('');
const [username,setUsername] = useState('');
const [pseudo,setPseudo] = useState('');
const [errors,setErrors] = useState([]);
const handleSubmit = event => {
event.preventDefault();
if (!email || !password) {
setErrors(['Email ou mot de passe invalide']);
}else if (password.length < 6) {
setErrors(['Le mot de passe dois avoir 6 caractères minimums'])
} else {
const db = getStore();
firebase.auth().createUserWithEmailAndPassword(email, password)
.then(response => {
db.collection('users').add({
'lastname': lastname,
'firstname': firstname,
'email': email,
'pseudo': pseudo,
'username': username,
'nbFollowers': 0,
'nbFolloweds': 0,
'userId': uuid()
}).then(user => {
db.collection('feed').doc(user.id).collection('tweets');
});
props.history.push('/login')
}).catch(error => {
errors.push(error.message);
})
}
};
return (
<div className="home-content">
<form onSubmit={handleSubmit} className="flex-content-form">
{errors.map(error => (
<p key={error} className="error-message">{error}</p>
))}
<div className="form-group">
<label>
<span>Nom:</span>
<input type="text" value={lastname} name="firstname" onChange={e => setLastname(e.target.value)}/>
</label>
<label>
<span>Prénom:</span>
<input type="text" value={firstname} name="lastname" onChange={e => setFirstname(e.target.value)}/>
</label>
</div>
<div className="form-group">
<label>
<span>Pseudo:</span>
<input type="text" name="pseudo" onChange={e => setPseudo(e.target.value)} value={pseudo}/>
</label>
</div>
<div className="form-group">
<label>
<span>Username:</span>
<input type="text" name="username" onChange={e => setUsername(e.target.value)} value={username}/>
</label>
</div>
<div className="form-group">
<label>
<span>Email:</span>
<input type="email" value={email} onChange={e => setEmail(e.target.value)} name="email" />
</label>
<label>
<span>Password:</span>
<input type="password" value={password} onChange={e => setPassword(e.target.value)} name="password" />
</label>
</div>
<div className="form-action">
<input type="submit" value="S'inscrire" className="submit" />
</div>
<div className="form-options">
<span>Déjà un compte ? <Link to="login">Cliquez ici</Link></span>
</div>
</form>
</div>
)
};
export default SignUp;
<file_sep>/src/components/Icons/index.js
export { default as OfflineIcon } from './OfflineIcon';
<file_sep>/src/components/Like/index.js
import React,{ useEffect, useState, useContext } from 'react';
import { ReactComponent as LikeIcon } from '../../static/icons/like.svg'
import { ReactComponent as UnlikeIcon } from '../../static/icons/unlike.svg'
import {AppContext} from "../App/AppProvider";
const Like = ({tweetId, nbLike}) => {
const { getStore, user } = useContext(AppContext);
const store = getStore();
const [liked, setLiked]= useState(false);
const [countLike, setCountlike]= useState(nbLike);
useEffect(() => {
isLiked(tweetId).then(doc => setLiked(doc.exists));
}, []);
const addLike = tweetId => {
store.collection('likes').doc(user.userId + "_" + tweetId).set({
'userId': user.userId,
'tweetId': tweetId,
});
let tweetRef = store.collection('tweets').doc(tweetId);
tweetRef.get()
.then(doc => {
tweetRef.update({
NbLike: doc.data().NbLike +1
}).then(() => setCountlike(countLike + 1));
});
};
const removeLike = tweetId => {
store.collection('likes').doc(user.userId + "_" + tweetId).delete().then(e => {
let tweetRef = store.collection('tweets').doc(tweetId);
tweetRef.get()
.then(doc => {
tweetRef.update({
NbLike: doc.data().NbLike -1
}).then(() => setCountlike(countLike - 1));
});
});
};
const isLiked = async tweetId => {
try {
if (user) return await store.collection("likes").doc(user.userId + "_" + tweetId).get();
} catch (err) {
}
};
const clickLike = () => {
liked ? removeLike(tweetId) : addLike(tweetId);
setLiked(!liked);
};
return liked ?
<span className="like"><UnlikeIcon onClick={clickLike}></UnlikeIcon>{countLike ?countLike :''}</span>
:
<span className="like"><LikeIcon onClick={clickLike}></LikeIcon>{countLike ?countLike :''}</span>
};
export default Like;
<file_sep>/src/components/Tweet/index.js
import { Link } from 'react-router-dom';
import React, { useRef } from 'react';
import Like from '../Like';
import Retweet from '../Retweet';
import { ReactComponent as ChatIcon } from '../../static/icons/chat.svg';
import { useIntersection } from '../../hooks';
import { BlurImageLoader } from '../Image';
const Tweet = ({ tweet }) => {
const ref = useRef();
const onScreen = useIntersection(ref);
return (
<div id={tweet.id} className="tweet-card">
<div className="tweet-card--profile">
<div className="tweet-card--profile--avatar">
{tweet.profilImage ? (
<img
src={tweet.profilImage}
className="profilImage"
alt={'Avatar profil of ' + tweet.username}
/>
) : (
''
)}
</div>
<div className="tweet-card--profile--username">
<h3>
<Link className="username" to={`/profile/${tweet.username}`}>
{tweet.username}
</Link>
</h3>
<p>@{tweet.username}</p>
</div>
</div>
<div className="tweet-card--content">
<p>{tweet.text} </p>
</div>
{tweet.imageUrl != null && tweet.imageUrl !== '' ? (
<div ref={ref} className="tweet-card--media">
<BlurImageLoader
placeholder={tweet.base64Image}
image={tweet.imageUrl}
visible={onScreen}
/>
{/* <img src={tweet.imageUrl} alt={`Media from : ` +tweet.username}></img> */}
</div>
) : (
''
)}
<div className="tweet-card--options">
<span className="like">
<ChatIcon />
{tweet.nbComment}
</span>
<Like nbLike={tweet.NbLike} tweetId={tweet.id} />
<Retweet tweetId={tweet.id} nbRetweet={tweet.NbRetweet} />
</div>
</div>
);
};
export default Tweet;
<file_sep>/src/components/Spinner/index.js
import React from 'react';
import './style.scss'
const Spinner = () => <div className="parent"><div className="spinning-loader parent"></div></div>;
export default Spinner;<file_sep>/src/hooks/index.js
export { default as useIntersection } from './useIntersection';
<file_sep>/src/helpers/Config.js
import env from '../env.json';
export default env.firebase;
<file_sep>/src/components/NavBar/UnloggedNav/Logout/index.js
import React, {useContext} from 'react';
import { Redirect } from 'react-router-dom';
import {AppContext} from "../../../App/AppProvider";
import { ReactComponent as LogoutIcone } from '../../../../static/icons/logout.svg'
const Logout = () => {
let { setUser } = useContext(AppContext);
const onClick = () => {
localStorage.removeItem('user');
setUser(null);
return <Redirect to='/'/>
};
return (
<li className='li-navbar'>
<a href="#" onClick={() => onClick()} aria-label="Logout">
<LogoutIcone className='icon'/>
<p>Logout</p>
</a>
</li>
);
};
export default Logout;<file_sep>/src/components/Image/index.js
export { default as BlurImageLoader } from './BlurImageLoader';
|
bf0a6733b0a9e9bdea503058d1ccfe06d225ac24
|
[
"JavaScript"
] | 16
|
JavaScript
|
dycor/twitbook
|
1d362de9b28d25ff3ca5c5c2773e184fcc429fff
|
9806ad5122cb860c871b931e5a9696cdf9b86e8e
|
refs/heads/master
|
<repo_name>bonahona/BonaVirtualGamePad<file_sep>/BonaVirtualGamePad/BonaVirtualGamePad.SharedPortable/NetworkPackage.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
namespace BonaVirtualGamePad.Shared
{
public class NetworkPackage
{
public UdpIpEndPoint SourceEndpoint { get; set; }
public NetworkPackageType PackageType;
public Vector2 LeftStick;
public Vector2 RightStick;
public Vector2 Triggers;
public UInt32 ButtonMask;
public String AdditionalData;
public NetworkPackage(NetworkPackageType packageType = NetworkPackageType.Unknown)
{
PackageType = packageType;
LeftStick = new Vector2();
RightStick = new Vector2();
Triggers = new Vector2();
AdditionalData = "";
}
// Reads a chunk of the data and return the offset of the data after this package has been read
public int Read(byte[] data, int offset)
{
var memoryStream = new MemoryStream(data, offset, data.Length - offset);
var binaryReader = new BinaryReader(memoryStream);
PackageType = (NetworkPackageType)binaryReader.ReadInt32();
LeftStick.ReadFromStream(binaryReader);
RightStick.ReadFromStream(binaryReader);
Triggers.ReadFromStream(binaryReader);
ButtonMask = binaryReader.ReadUInt32();
AdditionalData = binaryReader.ReadString();
var result = (int)memoryStream.Position + offset;
binaryReader.Dispose();
memoryStream.Dispose();
return result;
}
public String CreateAdditionalDataString(Dictionary<String, object> data)
{
var builder = new StringBuilder();
foreach(var key in data.Keys) {
builder.AppendFormat("{0}={1};", key, data[key]);
}
return builder.ToString();
}
public byte[] ToByteArray()
{
var memoryStream = new MemoryStream();
var binaryWriter = new BinaryWriter(memoryStream);
binaryWriter.Write((Int32)PackageType);
LeftStick.WriteToStream(binaryWriter);
RightStick.WriteToStream(binaryWriter);
Triggers.WriteToStream(binaryWriter);
binaryWriter.Write(ButtonMask);
binaryWriter.Write(AdditionalData);
var result = new byte[memoryStream.Length];
memoryStream.Position = 0;
memoryStream.Read(result, 0, (int)memoryStream.Length);
binaryWriter.Dispose();
memoryStream.Dispose();
return result;
}
}
}
<file_sep>/BonaVirtualGamePad/BonaVirtualGamePad.SharedPortable/GamePadNode.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
namespace BonaVirtualGamePad.Shared
{
public delegate void ServerGeneralEvent(GamePadClient client, ClientServerInformation server);
public delegate void ServerDiscoveredEvent(GamePadClient client, ClientServerInformation server, int serverIndex);
public abstract class GamePadNode
{
// These characters are used in to protocol and must therefor not be present in the name of a server. They are allowed in the password as that is sent hashed
public static readonly String[] DISALLOWED_SERVER_NAME_CHARACTERS = { ";", "=" };
public IUdpClient UdpClient { get; set; } // Wrapper for UdpClient connectivity
public IPlatform Plaform { get; set; } // Allows injection of platform specific funtionality like file reading and writing
public abstract void Update(float deltaTime);
public abstract void ApplyDefaults();
public GamePadNode(IUdpClient udpClient, IPlatform platform)
{
UdpClient = udpClient;
Plaform = platform;
ApplyDefaults();
}
public bool ValidateServerName(String serverName)
{
foreach(var disallowedChar in DISALLOWED_SERVER_NAME_CHARACTERS) {
if (serverName.Contains(disallowedChar)) {
return false;
}
}
return true;
}
public virtual bool HandlePackageResponse(NetworkPackage package)
{
return false;
}
public ClientServerInformation ParseServerInformation(NetworkPackage package)
{
var result = new ClientServerInformation();
var keyValuePairs = ParseAdditionalDataString(package.AdditionalData);
result.ServerName = keyValuePairs["name"];
result.ServerEndPoint = new UdpIpEndPoint(keyValuePairs["address"], int.Parse(keyValuePairs["port"]));
result.Capacity = int.Parse(keyValuePairs["capacity"]);
result.PlayerCount = int.Parse(keyValuePairs["players"]);
result.UsePassword = bool.Parse(keyValuePairs["usepassword"]);
return result;
}
public Dictionary<String, String> ParseAdditionalDataString(String additionalData)
{
var result = new Dictionary<String, String>();
var packageDataPairs = additionalData.Split(';');
foreach (var packageDataPair in packageDataPairs) {
// Handle empty string (The last entry in the list will be empty due to a trailing semicolon)
if (packageDataPair != String.Empty) {
var tmpSplit = packageDataPair.Split('=');
result.Add(tmpSplit[0], tmpSplit[1]);
}
}
return result;
}
public List<NetworkPackage> PollNetworkPackages()
{
return UdpClient.PollNetworkPackages();
}
public void SendPackage(NetworkPackage package, UdpIpEndPoint targetEndpoint)
{
var dataToSend = package.ToByteArray();
UdpClient.SendPackage(dataToSend, dataToSend.Length, targetEndpoint);
}
public NetworkPackage CreateNetworkDiscoveryRequest()
{
var result = new NetworkPackage(NetworkPackageType.ClientDiscoveryRequest);
return result;
}
public NetworkPackage CreateNetworkDiscoveryResponse(UdpIpEndPoint listeningEndpoint, GamePadServer gamePadServer)
{
var result = new NetworkPackage(NetworkPackageType.ServerDiscovertResponse);
var localIp = UdpClient.GetLocalIp();
var listeningPort = listeningEndpoint.Port;
var usePassword = (gamePadServer.ServerPassword != String.Empty);
var data = new Dictionary<String, object>();
data.Add("address", localIp);
data.Add("port", listeningEndpoint.Port);
data.Add("name", gamePadServer.ServerName);
data.Add("capacity", gamePadServer.GetPlayerCapacity());
data.Add("players", gamePadServer.GetPlayerCount());
data.Add("usepassword", usePassword);
result.AdditionalData = result.CreateAdditionalDataString(data);
return result;
}
public NetworkPackage CreatePlayerJoinRequest(ClientServerInformation server, PlayerIdentity player, String password = "")
{
var result = new NetworkPackage(NetworkPackageType.ClientPlayerJoinRequest);
var data = new Dictionary<String, object>();
data.Add("playeridentity", player.ToString());
data.Add("playername", player.Name);
// If a password is provided, add it SHA1 hashed to the package
if(password != String.Empty) {
data.Add("password", Plaform.HashString(password));
}
result.AdditionalData = result.CreateAdditionalDataString(data);
return result;
}
}
}
<file_sep>/BonaVirtualGamePad/BonaVirtualGamePad.SharedPortable/PlayerClient.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
namespace BonaVirtualGamePad.Shared
{
public class PlayerClient
{
public PlayerIdentity Identity;
public UdpIpEndPoint EndPoint;
public PLayerClientStatus Status;
public DateTime LastReievedPackage;
public PlayerClient(PlayerIdentity playerIdentity, UdpIpEndPoint endPoint)
{
Identity = playerIdentity;
EndPoint = endPoint;
}
}
}
<file_sep>/BonaVirtualGamePad/BonaVirtualGamePad.ClientDriver/Program.cs
using BonaVirtualGamePad.Shared;
using BonaVirtualGamePad.SharedWindows;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace BonaVirtualGamePad.ClientDriver
{
class Program
{
static void Main(string[] args)
{
new Program();
}
public GamePadClient Client { get; set; }
public Program()
{
Client = new GamePadClient(new WindowsUdpClient(), new WindowsPlatform());
Client.OnServerDiscovered += ServerDiscovered;
while (true) {
var commandLine = Console.ReadLine();
var parts = commandLine.Split(' ');
var command = parts[0];
var commandArgs = new List<String>();
if (parts.Length > 1) {
for (int i = 1; i < parts.Length; i++) {
commandArgs.Add(parts[i]);
}
}
try {
HandleCommand(command, commandArgs);
} catch (Exception e) {
Console.WriteLine("Failed to parse command");
}
}
}
public void HandleCommand(String command, List<String>args)
{
if (command == "discovery") {
Console.WriteLine("Send discovery broadcast");
Client.ClearDiscoveredServers();
Client.SendDiscoveryBroadCast();
Thread.Sleep(50);
var responses = Client.PollNetworkPackages();
foreach (var response in responses) {
try {
Client.HandlePackageResponse(response);
} catch (Exception e) {
Console.WriteLine("Failed to handle package, " + e.Message);
}
}
}else if(command == "connect") {
var serverIndex = int.Parse(args[0]);
var serverConnection = Client.DiscoveredServers[serverIndex];
if(args.Count > 1) {
var password = args[1];
Console.WriteLine(String.Format("Connecting to {0} with password", serverConnection.ServerName));
Client.ConnectToServer(serverConnection, password);
}else {
Console.WriteLine(String.Format("Connecting to {0}", serverConnection.ServerName));
Client.ConnectToServer(serverConnection);
}
}
}
public void ServerDiscovered(GamePadClient client, ClientServerInformation clientServerInformation, int serverIndex)
{
Console.WriteLine(String.Format("{0}\t {1}", serverIndex, clientServerInformation.DebugServerInfo()));
}
}
}
<file_sep>/BonaVirtualGamePad/BonaVirtualGamePad.SharedWindows/WindowsPlatform.cs
using BonaVirtualGamePad.Shared;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
namespace BonaVirtualGamePad.SharedWindows
{
public class WindowsPlatform : IPlatform
{
protected SHA1CryptoServiceProvider Sha1Generator;
public WindowsPlatform()
{
Sha1Generator = new SHA1CryptoServiceProvider();
}
public bool FileExists(string filename)
{
return File.Exists(filename);
}
public byte[] LoadFromFile(string filename)
{
var fileContent = File.ReadAllText(filename);
return Encoding.UTF8.GetBytes(fileContent);
}
public bool SaveDataToFile(byte[] data, string filename)
{
File.WriteAllBytes(filename, data);
return true;
}
public string HashString(String subject)
{
var buffer = Sha1Generator.ComputeHash(Encoding.UTF8.GetBytes(subject));
var result = BitConverter.ToString(buffer);
result.Replace("-", "");
return result;
}
}
}
<file_sep>/BonaVirtualGamePad/BonaVirtualGamePad.SharedWindows/WindowsUdpClient.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using BonaVirtualGamePad.Shared;
namespace BonaVirtualGamePad.SharedWindows
{
public class WindowsUdpClient : IUdpClient
{
protected UdpClient InternalUdpClient;
public UdpIpEndPoint GetBroadCastEndPoint(int port)
{
var broadcastEndpoint = new IPEndPoint(IPAddress.Broadcast, port);
var result = new UdpIpEndPoint(broadcastEndpoint.Address.ToString(), port);
return result;
}
public UdpIpEndPoint GetAnyEndPoint(int port)
{
var anyEndPoint = new IPEndPoint(IPAddress.Any, port);
var result = new UdpIpEndPoint(anyEndPoint.Address.ToString(), port);
return result;
}
public string GetLocalIp()
{
var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in host.AddressList) {
if (ip.AddressFamily == AddressFamily.InterNetwork) {
return ip.ToString();
}
}
throw new BonaVirtualGamePadException("No local IPAddress found");
}
// This only creates an IP address for validation purposes. Its result contains a string representation of the IpAddress
public UdpIpEndPoint ParseIpEndPoint(string address, int port)
{
try {
var ipAddress = IPAddress.Parse(address);
var result = new UdpIpEndPoint(ipAddress.ToString(), port);
return result;
} catch (Exception e) {
throw new BonaVirtualGamePadException("Failed to create IPEndPoint", e);
}
}
public void CreateWithEmptyEndPoint()
{
if(InternalUdpClient != null) {
InternalUdpClient.Close();
}
InternalUdpClient = new UdpClient();
}
public void SetEndPoint(UdpIpEndPoint endPoint)
{
if(InternalUdpClient != null) {
InternalUdpClient.Close();
}
InternalUdpClient = new UdpClient(ConvertUdpEndPointToIpEndPoint(endPoint));
}
public List<NetworkPackage> PollNetworkPackages()
{
var result = new List<NetworkPackage>();
while (InternalUdpClient.Available > 0) {
IPEndPoint source = new IPEndPoint(IPAddress.Any, Defaults.DEFAULT_SERVER_PORT);
byte[] buffer = InternalUdpClient.Receive(ref source);
int lastReadOffset = 0;
while (lastReadOffset < buffer.Length) {
var networkPackage = new NetworkPackage();
lastReadOffset = networkPackage.Read(buffer, lastReadOffset);
networkPackage.SourceEndpoint = ConvertIpEndPointToUdpEndPoint(source);
result.Add(networkPackage);
}
}
return result;
}
public void SendPackage(byte[] data, int packageLength, UdpIpEndPoint reciever)
{
InternalUdpClient.Send(data, packageLength, ConvertUdpEndPointToIpEndPoint(reciever));
}
public IPEndPoint ConvertUdpEndPointToIpEndPoint(UdpIpEndPoint udpIpEndPoint)
{
var result = new IPEndPoint(IPAddress.Parse(udpIpEndPoint.IpAddress), udpIpEndPoint.Port);
return result;
}
public UdpIpEndPoint ConvertIpEndPointToUdpEndPoint(IPEndPoint ipEndPoint)
{
var result = new UdpIpEndPoint(ipEndPoint.Address.ToString(), ipEndPoint.Port);
return result;
}
}
}
<file_sep>/BonaVirtualGamePad/BonaVirtualGamePad.SharedPortable/Vector2.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace BonaVirtualGamePad.Shared
{
public struct Vector2
{
public double X;
public double Y;
public Vector2(double x, double y)
{
X = x;
Y = y;
}
public void ReadFromStream(BinaryReader binaryReader)
{
X = binaryReader.ReadDouble();
Y = binaryReader.ReadDouble();
}
public void WriteToStream(BinaryWriter binaryWriter)
{
binaryWriter.Write(X);
binaryWriter.Write(Y);
}
}
}
<file_sep>/BonaVirtualGamePad/BonaVirtualGamePad.SharedPortable/ClientStatus.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BonaVirtualGamePad.Shared
{
// Status a GameNodeClient can have with regards to it trying to connect to a server
public enum ClientStatus : int
{
Unknown = 0,
Connecting = 1,
Connected = 2,
Disconnected = 3,
Dropped = 4
}
}
<file_sep>/BonaVirtualGamePad/BonaVirtualGamePad.SharedPortable/ClientServerInformation.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
namespace BonaVirtualGamePad.Shared
{
/* Contains the aggregated information of a server, built from a Discovery response, and stored data about a server
* so it can connect at a later moment
*
* Author: <NAME>*/
public class ClientServerInformation
{
public String ServerName { get; set; }
public UdpIpEndPoint ServerEndPoint { get; set; }
public bool UsePassword { get; set; }
public int Capacity { get; set; }
public int PlayerCount { get; set; }
public String DebugServerInfo()
{
return String.Format("Name: {0}, Server: {1}, Port: {2}, Playes; {3}/{4}, Use Password: {5}", ServerName, ServerEndPoint.IpAddress, ServerEndPoint.Port, PlayerCount, Capacity, UsePassword);
}
}
}
<file_sep>/BonaVirtualGamePad/BonaVirtualGamePad.SharedPortable/Defaults.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BonaVirtualGamePad.Shared
{
public static class Defaults
{
#region Server setup data
public const String DEFAULT_SERVER_NAME = "Game Server";
public const String DEFAULT_GAME_NAME = "Default Bona Virtual Gamepad Game";
public const int DEFAULT_SERVER_PORT = 2000;
public const int DEFAULT_SERVER_CAPACITY = 12;
#endregion
#region Client connection data
// Number of times a connection request will be sent in order to get a response before it considered the connection a failure
public const int CLIENT_CONNECTION_ATTEMPTS = 5;
// Time between connection attempts in seconds
public const float CLIENT_CONNECTION_ATTEMPT_TIMER = 1.0f;
#endregion
}
}
<file_sep>/BonaVirtualGamePad/BonaVirtualGamePad.SharedPortable/UdpIpEndPoint.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BonaVirtualGamePad.Shared
{
public delegate void IpAddressChanged(UdpIpEndPoint endPoint);
public class UdpIpEndPoint
{
protected String m_ipAddress;
protected int m_port;
public String IpAddress {
get { return m_ipAddress; }
set {
m_ipAddress = value;
InvokeOnIpAddressChanged();
}
}
public int Port {
get { return m_port; }
set {
m_port = value;
InvokeOnIpAddressChanged();
}
}
public event IpAddressChanged OnIpAddressChanged;
public UdpIpEndPoint()
{
IpAddress = "0.0.0.0";
Port = 0;
}
public UdpIpEndPoint(String ipAddress, int port)
{
IpAddress = ipAddress;
Port = port;
}
public void InvokeOnIpAddressChanged()
{
if(OnIpAddressChanged != null) {
OnIpAddressChanged(this);
}
}
}
}
<file_sep>/BonaVirtualGamePad/BonaVirtualGamePad.SharedPortable/PLayerClientStatus.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BonaVirtualGamePad.Shared
{
// Status a PlayerClient entry on the GameNodeServer can have.
public enum PLayerClientStatus : int
{
Unknown = 0,
Connected = 1,
NotConnected = 2
}
}
<file_sep>/BonaVirtualGamePad/BonaVirtualGamePad.SharedPortable/IUdpClient.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BonaVirtualGamePad.Shared
{
/* The UdpClien class and much of the System.Net namespace is not present in the PCL assembly but we need UDP conectivity
* With the use if this interface, platformspecific implementation can be dependency injected
*
* Auhtor: <NAME>*/
public interface IUdpClient
{
String GetLocalIp();
UdpIpEndPoint GetBroadCastEndPoint(int port);
UdpIpEndPoint GetAnyEndPoint(int port);
UdpIpEndPoint ParseIpEndPoint(String address, int port);
void CreateWithEmptyEndPoint();
void SetEndPoint(UdpIpEndPoint endPoint);
List<NetworkPackage> PollNetworkPackages();
void SendPackage(byte[] data, int packageLength, UdpIpEndPoint reciever);
}
}
<file_sep>/BonaVirtualGamePad/BonaVirtualGamePad.SharedPortable/PlayerIdentity.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BonaVirtualGamePad.Shared
{
public class PlayerIdentity
{
// A 128bit pattern to identify a player (16 x 8 = 128)
public const int PATTERN_LENGTH = 16;
// Characters not allowed in the player name
public static readonly String[] DISALLOWED_PLAYERNAME_CHARACTER= { ";", "=" };
public static bool operator ==(PlayerIdentity a, PlayerIdentity b)
{
return a.Equals(b);
}
public static bool operator !=(PlayerIdentity a, PlayerIdentity b)
{
return !a.Equals(b);
}
public static PlayerIdentity GenerateNew(String name)
{
PlayerIdentity result = new PlayerIdentity(name);
return result;
}
private byte[] m_identity;
// Stored Hexadecimal copy of the identity byte pattern
private String m_identityString;
// Stored hashcode so it does not have to be recalculated every time it's used
private int m_hashCode;
// Returns a copy of the byte pattern
public byte[] Identity
{
get { return Copy(); }
}
public String Name { get; set; }
public PlayerIdentity(String name)
{
if (!ValidatePlayername(name)) {
throw new BonaVirtualGamePadException("Playername contains disallowed character");
}else {
Name = name;
}
m_identity = GenerateRandomCode(PATTERN_LENGTH);
RegenerateIdentityHash();
}
public PlayerIdentity(String name, byte[] data)
{
if (!ValidatePlayername(name)) {
throw new BonaVirtualGamePadException("Playername contains disallowed character");
} else {
Name = name;
}
if (data.Length != PATTERN_LENGTH){
throw new BonaVirtualGamePadException(String.Format("PlayerIdentity intial byte count is not {0}", PATTERN_LENGTH));
}
for(int i = 0; i < PATTERN_LENGTH; i++){
m_identity[i] = data[i];
}
RegenerateIdentityHash();
}
public bool ValidatePlayername(String playerName)
{
foreach(var disallowedChar in DISALLOWED_PLAYERNAME_CHARACTER) {
if (playerName.Contains(disallowedChar)){
return false;
}
}
return true;
}
public byte[] GenerateRandomCode(int length)
{
var random = new System.Random(DateTime.Now.Millisecond);
var result = new byte[length];
for(int i = 0; i < result.Length; i++) {
result[i] = (byte)random.Next(255);
}
return result;
}
public override string ToString()
{
return m_identityString;
}
public override int GetHashCode()
{
return m_hashCode;
}
public override bool Equals(object obj)
{
if(obj is PlayerIdentity){
PlayerIdentity other = (PlayerIdentity)obj;
return other.Equals(m_identity);
}
else{
return false;
}
}
public bool Equals(byte[] other)
{
for(int i = 0; i < other.Length; i++){
if(m_identity[i] != other[i]){
return false;
}
}
return true;
}
private byte[] Copy()
{
byte[] result = new byte[m_identity.Length];
for(int i = 0; i < result.Length; i ++){
result[i] = m_identity[i];
}
return result;
}
private void RegenerateIdentityHash()
{
m_identityString = BitConverter.ToString(m_identity);
m_identityString = m_identityString.Replace("-", "");
m_hashCode = m_identityString.GetHashCode();
;
}
}
}
<file_sep>/BonaVirtualGamePad/BonaVirtualGamePad.SharedPortable/NetworkPackageType.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BonaVirtualGamePad.Shared
{
public enum NetworkPackageType : int
{
Unknown = 0,
ClientDiscoveryRequest = 1,
ServerDiscovertResponse = 2,
ClientPlayerJoinRequest = 3,
ServerPlayerJoinResponse = 4,
}
}
<file_sep>/BonaVirtualGamePad/BonaVirtualGamePad.ServerDriver/Program.cs
using BonaVirtualGamePad.Shared;
using BonaVirtualGamePad.SharedWindows;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace BonaVirtualGamePad.ServerDriver
{
class Program
{
static void Main(string[] args)
{
new Program();
}
public GamePadServer Server { get; set; }
public Program()
{
Server = new GamePadServer(new WindowsUdpClient(), new WindowsPlatform(), Defaults.DEFAULT_SERVER_NAME, "H4mligt");
Console.WriteLine("Start listening...");
while (true) {
Thread.Sleep(2);
var recievedPackages = Server.PollNetworkPackages();
foreach(var package in recievedPackages) {
if(package.PackageType == NetworkPackageType.ClientDiscoveryRequest) {
Server.SendNetworkDiscoveryResponse(Server.ListeningEndPoint, package.SourceEndpoint);
}
Console.WriteLine("Recieved package");
Console.WriteLine(package.AdditionalData);
}
}
}
}
}
<file_sep>/BonaVirtualGamePad/BonaVirtualGamePad.SharedPortable/IPlatform.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BonaVirtualGamePad.Shared
{
public interface IPlatform
{
bool FileExists(String filename);
bool SaveDataToFile(byte[] data, String filename);
byte[] LoadFromFile(String filename);
String HashString(String subject);
}
}
<file_sep>/BonaVirtualGamePad/BonaVirtualGamePad.SharedPortable/GamePadClient.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
namespace BonaVirtualGamePad.Shared
{
public class GamePadClient : GamePadNode
{
public PlayerIdentity PlayerIdentity { get; set; }
public UdpIpEndPoint BroadCastEndPoint { get; set; }
public UdpIpEndPoint HostEndPoint { get; set; }
public UdpIpEndPoint LocalEndPoint { get; set; }
// List of all available servers who have responded to the discovery request
public List<ClientServerInformation> DiscoveredServers { get; set; }
// Server the client has connected to (or is trying). Null means it is not connect not is it trying to connect to anything)
public ClientServerInformation ConnectedServer { get; set; }
public ClientStatus ConnectionStatus { get; set; }
// State data for a connection attempt
public int ConnectionAttemptMax { get; set; }
public int ConnectionAttemptCurrent { get; set; }
public float ConnectionTimerMax { get; set; }
public float ConnectionTimerCurrent { get; set; }
public event ServerDiscoveredEvent OnServerDiscovered;
public event ServerGeneralEvent OnServerJoinAccept;
public event ServerGeneralEvent OnServerJoinDenied;
public event ServerGeneralEvent OnServerDropped;
public GamePadClient(IUdpClient udpClient, IPlatform platform) : base(udpClient, platform)
{
udpClient.CreateWithEmptyEndPoint();
BroadCastEndPoint = udpClient.GetBroadCastEndPoint(Defaults.DEFAULT_SERVER_PORT);
// TODO: Change this to a proper identity
PlayerIdentity = PlayerIdentity.GenerateNew("Test Player");
}
public override void Update(float deltaTime)
{
}
public override void ApplyDefaults()
{
ConnectionAttemptCurrent = 0;
ConnectionAttemptMax = Defaults.CLIENT_CONNECTION_ATTEMPTS;
ConnectionTimerCurrent = 0;
ConnectionTimerMax = Defaults.CLIENT_CONNECTION_ATTEMPT_TIMER;
}
public void InvokeOnServerDiscovered(ClientServerInformation clientServerInformation, int serverIndex)
{
if(OnServerDiscovered != null) {
OnServerDiscovered(this, clientServerInformation, serverIndex);
}
}
public void InvokeOnServerJoinAccept(ClientServerInformation clientServerInformation)
{
if(OnServerJoinAccept != null) {
OnServerJoinAccept(this, clientServerInformation);
}
}
public void InvokeOnServerJoinDenied(ClientServerInformation clientServerInformation)
{
if(OnServerJoinDenied != null) {
OnServerJoinDenied(this, clientServerInformation);
}
}
public void InvokeServerJoin(ClientServerInformation clientServerInformation)
{
if(OnServerDropped != null) {
OnServerDropped(this, clientServerInformation);
}
}
public void ClearDiscoveredServers()
{
if(DiscoveredServers == null) {
DiscoveredServers = new List<ClientServerInformation>();
}
DiscoveredServers.Clear();
}
public override bool HandlePackageResponse(NetworkPackage package)
{
try {
if (base.HandlePackageResponse(package)) {
return true;
}
if (package.PackageType == NetworkPackageType.ServerDiscovertResponse) {
var clientServerInformation = ParseServerInformation(package);
AddDiscoveredServer(clientServerInformation);
}
}catch(Exception e) {
throw new BonaVirtualGamePadException("Failed to handle package, se inner exception", e);
}
return false;
}
public void AddDiscoveredServer(ClientServerInformation clientServerInformation)
{
DiscoveredServers.Add(clientServerInformation);
InvokeOnServerDiscovered(clientServerInformation, DiscoveredServers.Count -1);
}
public void SendDiscoveryBroadCast()
{
var package = CreateNetworkDiscoveryRequest();
SendPackage(package, BroadCastEndPoint);
}
public void ConnectToServer(ClientServerInformation clientServerInformation, String password = "")
{
ConnectedServer = clientServerInformation;
SendJoinRequest(clientServerInformation, PlayerIdentity, password);
ConnectionStatus = ClientStatus.Connecting;
}
public void SendJoinRequest(ClientServerInformation server, PlayerIdentity playerIdentity, String password)
{
var package = CreatePlayerJoinRequest(server, playerIdentity, password);
SendPackage(package, server.ServerEndPoint);
}
}
}
<file_sep>/BonaVirtualGamePad/BonaVirtualGamePad.SharedPortable/GamePadServer.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
namespace BonaVirtualGamePad.Shared
{
public class GamePadServer : GamePadNode
{
public String ServerName;
public String ServerPassword;
public PlayerClient[] Clients; // Array of all currently connected players
public UdpIpEndPoint ListeningEndPoint;
public GamePadServer(IUdpClient udpClient, IPlatform platform, String serverName, String serverPassword = "", int capacity = Defaults.DEFAULT_SERVER_CAPACITY, int listeningPort = Defaults.DEFAULT_SERVER_PORT) : base(udpClient, platform)
{
if (!ValidateServerName(serverName)) {
throw new BonaVirtualGamePadException("Server name contains disallowed characters");
}
ServerName = serverName;
ServerPassword = <PASSWORD>;
ListeningEndPoint = UdpClient.GetAnyEndPoint(listeningPort);
UdpClient.SetEndPoint(ListeningEndPoint);
Clients = new PlayerClient[capacity];
}
public override void ApplyDefaults()
{
// TODO: Implement this
}
public override void Update(float deltaTime)
{
// TODO: Implement this
}
public void SendNetworkDiscoveryResponse(UdpIpEndPoint localEndpoint, UdpIpEndPoint remoteEndpoint)
{
var package = CreateNetworkDiscoveryResponse(localEndpoint, this);
SendPackage(package, remoteEndpoint);
}
public int GetPlayerCount()
{
var result = 0;
for (int i = 0; i < Clients.Length; i++) {
if (Clients[i] != null) {
result++;
}
}
return result;
}
public int GetPlayerCapacity()
{
return Clients.Length;
}
}
}
|
ed6ab9753055c2805a10e91f820878ee74db90eb
|
[
"C#"
] | 19
|
C#
|
bonahona/BonaVirtualGamePad
|
72a7c4d169b2e77a28f108cdf3b4534823e0f437
|
2e128f1efc87d35947a433d45e92e356d97077a4
|
refs/heads/main
|
<file_sep># tecweb-demo-express<file_sep>const db = require("../config/mysql");
exports.insert = async (req, res, next) => {
if (!req.body.username) { // || !req.body.email) {
return res.status(400).json({
message: "Campos obrigatórios não preenchidos.",
fields: ["username", "email"],
});
}
req.body.email = req.body.email ? req.body.email : null;
try {
db.query(
"INSERT INTO `usuario`(`username`,`email`) VALUES(?, ?)",
[req.body.username, req.body.email],
(error, results, fields) => {
if(error) throw error;
res.status(201).json({
message: "Usuário inserido com sucesso.",
data: results,
});
});
} catch (err) {
next(err);
}
};
exports.selectAllUsers = async (req, res, next) => {
try {
db.query("SELECT * FROM `usuario`", (error, results, fields) => {
if(error) throw error;
res.status(200).json(results);
});
} catch (err) {
next(err);
}
};
<file_sep>const restful = require('node-restful')
const mongoose = restful.mongoose
const tarefaSchema = new mongoose.Schema({
descricao: { type: String, required: true },
dataCriacao: { type: Date, default: Date.now }
})
module.exports = restful.model('Tarefa', tarefaSchema)
|
aec7ddce2352e53e344f338e477c695798f4fdca
|
[
"Markdown",
"JavaScript"
] | 3
|
Markdown
|
uneluneravie/tecweb-demo-express
|
cd2760536c6b20ff9be02aafe6af1e051f825703
|
c5a61d0c43728195cf9c3f9e7d37cea6b91c9995
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.