commit stringlengths 40 40 | subject stringlengths 4 1.73k | repos stringlengths 5 127k | old_file stringlengths 2 751 | new_file stringlengths 2 751 | new_contents stringlengths 1 8.98k | old_contents stringlengths 0 6.59k | license stringclasses 13 values | lang stringclasses 23 values |
|---|---|---|---|---|---|---|---|---|
82637fe28e3272010dcbc8e74d7c7ed854d145c5 | Remove obsolete ICONS_FOLDER_PATH | PhannGor/unity3d-rainbow-folders | Assets/RainbowItems/Editor/CustomBrowserIcons.cs | Assets/RainbowItems/Editor/CustomBrowserIcons.cs | /*
* 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.IO;
using Borodar.RainbowItems.Editor.Settings;
using UnityEditor;
using UnityEngine;
namespace Borodar.RainbowItems.Editor
{
/*
* This script allows you to set custom icons for folders in project browser.
* Recommended icon sizes - small: 16x16 px, large: 64x64 px;
*/
[InitializeOnLoad]
public class CustomBrowserIcons
{
#region reserved_folder_names
private const string EDITOR_FOLDER_NAME = "Editor";
private const string PLUGINS_FOLDER_NAME = "Plugins";
private const string RESOURCES_FOLDER_NAME = "Resources";
private const string GIZMOS_FOLDER_NAME = "Gizmos";
private const string STREAMING_ASSETS_FOLDER_NAME = "StreamingAssets";
#endregion
private static CustomBrowserIconSettings _settings;
static CustomBrowserIcons()
{
EditorApplication.projectWindowItemOnGUI += ReplaceFolderIcon;
}
static void ReplaceFolderIcon(string guid, Rect rect)
{
var path = AssetDatabase.GUIDToAssetPath(guid);
if (!AssetDatabase.IsValidFolder(path)) return;
var isSmall = rect.width > rect.height;
if (isSmall)
{
rect.width = rect.height;
}
else
{
rect.height = rect.width;
}
_settings = _settings ?? LoadSettings();
var sprite = _settings.GetSprite(Path.GetFileName(path), isSmall);
if (sprite != null) CustomEditorUtility.DrawTextureGUI(rect, sprite);
}
//---------------------------------------------------------------------
// Helpers
//---------------------------------------------------------------------
private static CustomBrowserIconSettings LoadSettings()
{
return Resources.Load<CustomBrowserIconSettings>("RainbowItemsSettings");
}
}
}
| /*
* 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.IO;
using Borodar.RainbowItems.Editor.Settings;
using UnityEditor;
using UnityEngine;
namespace Borodar.RainbowItems.Editor
{
/*
* This script allows you to set custom icons for folders in project browser.
* Recommended icon sizes - small: 16x16 px, large: 64x64 px;
*/
[InitializeOnLoad]
public class CustomBrowserIcons
{
private const string ICONS_FOLDER_PATH = "Assets/RainbowItems/Editor/Sprites/";
#region reserved_folder_names
private const string EDITOR_FOLDER_NAME = "Editor";
private const string PLUGINS_FOLDER_NAME = "Plugins";
private const string RESOURCES_FOLDER_NAME = "Resources";
private const string GIZMOS_FOLDER_NAME = "Gizmos";
private const string STREAMING_ASSETS_FOLDER_NAME = "StreamingAssets";
#endregion
private static CustomBrowserIconSettings _settings;
static CustomBrowserIcons()
{
EditorApplication.projectWindowItemOnGUI += ReplaceFolderIcon;
}
static void ReplaceFolderIcon(string guid, Rect rect)
{
var path = AssetDatabase.GUIDToAssetPath(guid);
if (!AssetDatabase.IsValidFolder(path)) return;
var isSmall = rect.width > rect.height;
if (isSmall)
{
rect.width = rect.height;
}
else
{
rect.height = rect.width;
}
_settings = _settings ?? LoadSettings();
var sprite = _settings.GetSprite(Path.GetFileName(path), isSmall);
if (sprite != null) CustomEditorUtility.DrawTextureGUI(rect, sprite);
}
//---------------------------------------------------------------------
// Helpers
//---------------------------------------------------------------------
private static CustomBrowserIconSettings LoadSettings()
{
return Resources.Load<CustomBrowserIconSettings>("RainbowItemsSettings");
}
}
}
| apache-2.0 | C# |
4168e8ee45b7914765898ae8c0e12bfe7e8a0c79 | use correct tools version, visual studio 2010 uses 4.0 | dnauck/AspSQLProvider,dnauck/AspSQLProvider | src/CommonAssemblyInfo.cs | src/CommonAssemblyInfo.cs | using System.Reflection;
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.454
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
[assembly: AssemblyCompanyAttribute("Nauck IT KG")]
[assembly: AssemblyProductAttribute("AspSQLProvider")]
[assembly: AssemblyCopyrightAttribute("Copyright 2006 - 2011 Nauck IT KG")]
[assembly: AssemblyTrademarkAttribute("")]
[assembly: AssemblyVersionAttribute("0.0.0.0")]
[assembly: AssemblyFileVersionAttribute("0.0.0.0")]
| using System.Reflection;
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:2.0.50727.5446
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
[assembly: AssemblyCompanyAttribute("Nauck IT KG")]
[assembly: AssemblyProductAttribute("AspSQLProvider")]
[assembly: AssemblyCopyrightAttribute("Copyright 2006 - 2011 Nauck IT KG")]
[assembly: AssemblyTrademarkAttribute("")]
[assembly: AssemblyVersionAttribute("0.0.0.0")]
[assembly: AssemblyFileVersionAttribute("0.0.0.0")]
| mit | C# |
8908bfabe59c4de0169761ff5592278f76caead3 | Add "logout" alias to LogoutAuthCommand | appharbor/appharbor-cli | src/AppHarbor/Commands/LogoutAuthCommand.cs | src/AppHarbor/Commands/LogoutAuthCommand.cs | using System.IO;
namespace AppHarbor.Commands
{
[CommandHelp("Logout of AppHarbor", alias: "logout")]
public class LogoutAuthCommand : ICommand
{
private readonly IAccessTokenConfiguration _accessTokenConfiguration;
private readonly TextWriter _writer;
public LogoutAuthCommand(IAccessTokenConfiguration accessTokenConfiguration, TextWriter writer)
{
_accessTokenConfiguration = accessTokenConfiguration;
_writer = writer;
}
public void Execute(string[] arguments)
{
_accessTokenConfiguration.DeleteAccessToken();
_writer.WriteLine("Successfully logged out.");
}
}
}
| using System.IO;
namespace AppHarbor.Commands
{
[CommandHelp("Logout of AppHarbor")]
public class LogoutAuthCommand : ICommand
{
private readonly IAccessTokenConfiguration _accessTokenConfiguration;
private readonly TextWriter _writer;
public LogoutAuthCommand(IAccessTokenConfiguration accessTokenConfiguration, TextWriter writer)
{
_accessTokenConfiguration = accessTokenConfiguration;
_writer = writer;
}
public void Execute(string[] arguments)
{
_accessTokenConfiguration.DeleteAccessToken();
_writer.WriteLine("Successfully logged out.");
}
}
}
| mit | C# |
44d3442492ad90567e12e251a38380fc6dd92047 | Document PoEStashTabColor | jcmoyer/Yeena | Yeena/PathOfExile/PoEStashTabColor.cs | Yeena/PathOfExile/PoEStashTabColor.cs | // Copyright 2013 J.C. Moyer
//
// 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.
#pragma warning disable 649
using System;
using System.Drawing;
using Newtonsoft.Json;
namespace Yeena.PathOfExile {
/// <summary>
/// Represents the color of a stash tab.
/// </summary>
[JsonObject]
class PoEStashTabColor {
[JsonProperty("r")]
private readonly int _r;
[JsonProperty("g")]
private readonly int _g;
[JsonProperty("b")]
private readonly int _b;
private readonly Lazy<Color> _color;
/// <summary>
/// Returns the color of a stash tab.
/// </summary>
/// <see cref="System.Drawing.Color"/>
public Color Color {
get { return _color.Value; }
}
[JsonConstructor]
private PoEStashTabColor() {
_color = new Lazy<Color>(() => Color.FromArgb(_r, _g, _b));
}
public static implicit operator Color(PoEStashTabColor c) {
return c.Color;
}
}
}
| // Copyright 2013 J.C. Moyer
//
// 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.
#pragma warning disable 649
using System;
using System.Drawing;
using Newtonsoft.Json;
namespace Yeena.PathOfExile {
[JsonObject]
class PoEStashTabColor {
[JsonProperty("r")]
private readonly int _r;
[JsonProperty("g")]
private readonly int _g;
[JsonProperty("b")]
private readonly int _b;
private readonly Lazy<Color> _color;
public Color Color {
get { return _color.Value; }
}
[JsonConstructor]
private PoEStashTabColor() {
_color = new Lazy<Color>(() => Color.FromArgb(_r, _g, _b));
}
public static implicit operator Color(PoEStashTabColor c) {
return c.Color;
}
}
}
| apache-2.0 | C# |
ebdc98a90974a0d09fed49eb673ce7fa66b98a3b | Debug keys | AppCreativity/Kliva | src/Kliva/Models/StravaIdentityConstants.cs | src/Kliva/Models/StravaIdentityConstants.cs | namespace Kliva.Models
{
public static class StravaIdentityConstants
{
// These keys should be used for testing/debugging purposes only.
public const string STRAVA_AUTHORITY_CLIENT_ID = "14473";
public const string STRAVA_AUTHORITY_CLIENT_SECRET = "2d438723e18ffe0a4a2711d1e873013407129515";
public const string GOOGLE_MAP_API = "bliep bliep";
}
}
| namespace Kliva.Models
{
public static class StravaIdentityConstants
{
public const string STRAVA_AUTHORITY_CLIENT_ID = "0";
public const string STRAVA_AUTHORITY_CLIENT_SECRET = "riiiiight :)";
public const string GOOGLE_MAP_API = "bliep bliep";
}
}
| mit | C# |
2332db49a227cc0e2ac90fa35ba77e389e25dd0a | Fix a typo | openmedicus/gtk-sharp,Gankov/gtk-sharp,sillsdev/gtk-sharp,openmedicus/gtk-sharp,openmedicus/gtk-sharp,Gankov/gtk-sharp,sillsdev/gtk-sharp,akrisiun/gtk-sharp,orion75/gtk-sharp,akrisiun/gtk-sharp,sillsdev/gtk-sharp,openmedicus/gtk-sharp,sillsdev/gtk-sharp,Gankov/gtk-sharp,orion75/gtk-sharp,openmedicus/gtk-sharp,akrisiun/gtk-sharp,sillsdev/gtk-sharp,antoniusriha/gtk-sharp,orion75/gtk-sharp,akrisiun/gtk-sharp,akrisiun/gtk-sharp,orion75/gtk-sharp,antoniusriha/gtk-sharp,Gankov/gtk-sharp,antoniusriha/gtk-sharp,openmedicus/gtk-sharp,antoniusriha/gtk-sharp,orion75/gtk-sharp,Gankov/gtk-sharp,Gankov/gtk-sharp,antoniusriha/gtk-sharp,openmedicus/gtk-sharp | gio/FileFactory.cs | gio/FileFactory.cs | //
// FileFactory.cs
//
// Author(s):
// Stephane Delcroix <stephane@delcroix.org>
//
// Copyright (c) 2008 Stephane Delcroix
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the Lesser GNU General
// Public License as published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
using System;
using System.Runtime.InteropServices;
namespace GLib
{
public class FileFactory
{
[DllImport ("libgio-2.0-0.dll")]
private static extern IntPtr g_file_new_for_uri (string uri);
public static File NewForUri (string uri)
{
return GLib.FileAdapter.GetObject (g_file_new_for_uri (uri), false) as File;
}
public static File NewForUri (Uri uri)
{
return GLib.FileAdapter.GetObject (g_file_new_for_uri (uri.ToString ()), false) as File;
}
[DllImport ("libgio-2.0-0.dll")]
private static extern IntPtr g_file_new_for_path (string path);
public static File NewForPath (string path)
{
return GLib.FileAdapter.GetObject (g_file_new_for_path (path), false) as File;
}
[DllImport ("libgio-2.0-0.dll")]
private static extern IntPtr g_file_new_for_commandline_arg (string arg);
public static File NewFromCommandlineArg (string arg)
{
return GLib.FileAdapter.GetObject (g_file_new_for_commandline_arg (arg), false) as File;
}
}
}
| //
// FileFactory.cs
//
// Author(s):
// Stephane Delcroix <stephane@delcroix.org>
//
// Copyright (c) 2008 Stephane Delcroix
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the Lesser GNU General
// Public License as published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
using System;
using System.Runtime.InteropServices;
namespace GLib
{
public class FileFactory
{
[DllImport ("libgio-2.0-0.dll")]
private static extern IntPtr g_file_new_for_uri (string uri);
public static File NewForUri (string uri)
{
return GLib.FileAdapter.GetObject (g_file_new_for_uri (uri), false) as File;
}
public static File NewForUri (Uri uri)
{
return GLib.FileAdapter.GetObject (g_file_new_for_uri (uri.ToString ()), false) as File;
}
[DllImport ("libgio-2.0-0.dll")]
private static extern IntPtr g_file_new_for_path (string path);
public static File NewForPath (string path)
{
return GLib.FileAdapter.GetObject (g_file_new_for_path (path), false) as File;
}
[DllImport ("libgio-2.0-0.dll")]
private static extern IntPtr g_file_new_for_commandline_args (string args);
public static File NewForCommandlineArgs (string args)
{
return GLib.FileAdapter.GetObject (g_file_new_for_commandline_args (args), false) as File;
}
}
}
| lgpl-2.1 | C# |
e9e16c6eefe0e10ed19da15187b42501393d323a | bump to v0.2.1 | peters/assemblyinfo | src/assemblyinfo/Properties/AssemblyInfo.cs | src/assemblyinfo/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("assemblyinfo")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("assemblyinfo")]
[assembly: AssemblyCopyright("Copyright © Peter Sunde 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("d2587fde-ac26-43a1-bde3-920ae0fa540b")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.2.1")]
[assembly: AssemblyFileVersion("0.2.1")]
[assembly: AssemblyInformationalVersion("0.2.1")]
[assembly: InternalsVisibleTo("assemblyinfo.tests, PublicKey=00240000048000009400000006020000002400005253413100040000010001003f1fddfeafe99f552f4449650bd29ea429b00839864ebcd3313c9f15f095016cd22b37704d8fe005d978b8996877f6e73550131d78eb916f466d3dc80b9b2410f85287e1b6d3179d1621ddd2ed90624192f0979e35eadf2ee49158a496e4b278d5725b30e9d2679e07fe8f6cb528dc4460d472e0f44b663a75c4347924784cce")] | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("assemblyinfo")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("assemblyinfo")]
[assembly: AssemblyCopyright("Copyright © Peter Sunde 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("d2587fde-ac26-43a1-bde3-920ae0fa540b")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.2.0")]
[assembly: AssemblyFileVersion("0.2.0")]
[assembly: AssemblyInformationalVersion("0.2.0")]
[assembly: InternalsVisibleTo("assemblyinfo.tests, PublicKey=00240000048000009400000006020000002400005253413100040000010001003f1fddfeafe99f552f4449650bd29ea429b00839864ebcd3313c9f15f095016cd22b37704d8fe005d978b8996877f6e73550131d78eb916f466d3dc80b9b2410f85287e1b6d3179d1621ddd2ed90624192f0979e35eadf2ee49158a496e4b278d5725b30e9d2679e07fe8f6cb528dc4460d472e0f44b663a75c4347924784cce")] | mit | C# |
598fd73e4c6052c64aa539898352eae88931a55e | Update detection sample web app | wangkanai/Detection | sample/Detection/Views/Home/Index.cshtml | sample/Detection/Views/Home/Index.cshtml | @model Wangkanai.Detection.Services.IDetectionService
@{
ViewData["Title"] = "Detection";
}
<h3>UserAgent</h3>
<code>@Model.UserAgent</code>
<h3>Results</h3>
<table>
<thead>
<tr>
<th>Resolver</th>
<th>Type</th>
<th>Version</th>
</tr>
</thead>
<tbody>
<tr>
<th>Device</th>
<td>@Model.Device?.Type</td>
<td></td>
</tr>
<tr>
<th>Platform</th>
<td>@Model.Platform?.OperatingSystem</td>
<td>@Model.Platform?.Processor</td>
</tr>
<tr>
<th>Engine</th>
<td>@Model.Engine?.Type</td>
<td></td>
</tr>
<tr>
<th>Browser</th>
<td>@Model.Browser?.Type</td>
<td></td>
</tr>
<tr>
<th>Crawler</th>
<td>@Model.Crawler?.Type</td>
<td>@Model.Crawler?.Version</td>
</tr>
</tbody>
</table>
| @model Wangkanai.Detection.Services.IDetectionService
@{
ViewData["Title"] = "Detection";
}
<h3>UserAgent</h3>
<code>@Model.UserAgent</code>
<h3>Results</h3>
<table>
<thead>
<tr>
<th>Resolver</th>
<th>Type</th>
<th>Version</th>
</tr>
</thead>
<tbody>
<tr>
<th>Device</th>
<td>@Model.Device?.Type</td>
<td></td>
</tr>
<tr>
<th>Platform</th>
<td>@Model.Platform?.OperatingSystem</td>
<td>@Model.Platform?.Processor</td>
</tr>
<tr>
<th>Engine</th>
<td>@Model.Engine?.Type</td>
<td></td>
</tr>
<tr>
<th>Browser</th>
<td>@Model.Browser?.Type</td>
<td></td>
</tr>
<tr>
<th>Crawler</th>
<td>@Model.Crawler?.Type.ToString()</td>
<td>@Model.Crawler?.Version</td>
</tr>
</tbody>
</table>
| apache-2.0 | C# |
622cd17393238df2fea2e58493ab6b765b68e71a | Use cached images if available | MilenPavlov/PortableRazorStarterKit,MilenPavlov/PortableRazorStarterKit,xamarin/PortableRazorStarterKit,xamarin/PortableRazorStarterKit | PortableCongress/AndroidCongress/MainActivity.cs | PortableCongress/AndroidCongress/MainActivity.cs | using System;
using Android.App;
using Android.Content;
using Android.Webkit;
using Android.OS;
using Congress;
using PortableCongress;
namespace AndroidCongress
{
[Activity (Label = "@string/app_name", MainLauncher = true, ScreenOrientation = Android.Content.PM.ScreenOrientation.Portrait)]
public class MainActivity : Activity
{
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
Congress.ResourceManager.EnsureResources (
typeof(PortableCongress.Politician).Assembly,
String.Format ("/data/data/{0}/files", Application.Context.PackageName));
// Set our view from the "main" layout resource
SetContentView (Resource.Layout.Main);
var webView = FindViewById<WebView> (Resource.Id.webView);
// Use subclassed WebViewClient to intercept hybrid native calls
var webViewClient = new HybridWebViewClient ();
var politicianController = new PoliticianController (
new HybridWebView (webView),
new DataAccess ());
webViewClient.SetPoliticianController (politicianController);
PortableRazor.RouteHandler.RegisterController ("Politician", politicianController);
webView.SetWebViewClient (webViewClient);
webView.Settings.CacheMode = CacheModes.CacheElseNetwork;
webView.Settings.JavaScriptEnabled = true;
webView.SetWebChromeClient (new HybridWebChromeClient (this));
webViewClient.ShowPoliticianList ();
}
class HybridWebViewClient : WebViewClient {
PoliticianController politicianController;
public void SetPoliticianController(PoliticianController controller) {
politicianController = controller;
}
public void ShowPoliticianList() {
politicianController.ShowPoliticianList ();
}
public override bool ShouldOverrideUrlLoading (WebView webView, string url) {
var handled = PortableRazor.RouteHandler.HandleRequest (url);
return handled;
}
}
class HybridWebChromeClient : WebChromeClient {
Context context;
public HybridWebChromeClient (Context context) : base () {
this.context = context;
}
public override bool OnJsAlert (WebView view, string url, string message, JsResult result) {
var alertDialogBuilder = new AlertDialog.Builder (context)
.SetMessage (message)
.SetCancelable (false)
.SetPositiveButton ("Ok", (sender, args) => {
result.Confirm ();
});
alertDialogBuilder.Create().Show();
return true;
}
public override bool OnJsConfirm (WebView view, string url, string message, JsResult result) {
var alertDialogBuilder = new AlertDialog.Builder (context)
.SetMessage (message)
.SetCancelable (false)
.SetPositiveButton ("Ok", (sender, args) => {
result.Confirm();
})
.SetNegativeButton ("Cancel", (sender, args) => {
result.Cancel();
});
alertDialogBuilder.Create().Show();
return true;
}
}
}
}
| using System;
using Android.App;
using Android.Content;
using Android.Webkit;
using Android.OS;
using Congress;
using PortableCongress;
namespace AndroidCongress
{
[Activity (Label = "@string/app_name", MainLauncher = true, ScreenOrientation = Android.Content.PM.ScreenOrientation.Portrait)]
public class MainActivity : Activity
{
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
Congress.ResourceManager.EnsureResources (
typeof(PortableCongress.Politician).Assembly,
String.Format ("/data/data/{0}/files", Application.Context.PackageName));
// Set our view from the "main" layout resource
SetContentView (Resource.Layout.Main);
var webView = FindViewById<WebView> (Resource.Id.webView);
// Use subclassed WebViewClient to intercept hybrid native calls
var webViewClient = new HybridWebViewClient ();
var politicianController = new PoliticianController (
new HybridWebView (webView),
new DataAccess ());
webViewClient.SetPoliticianController (politicianController);
PortableRazor.RouteHandler.RegisterController ("Politician", politicianController);
webView.SetWebViewClient (webViewClient);
webView.Settings.JavaScriptEnabled = true;
webView.SetWebChromeClient (new HybridWebChromeClient (this));
webViewClient.ShowPoliticianList ();
}
class HybridWebViewClient : WebViewClient {
PoliticianController politicianController;
public void SetPoliticianController(PoliticianController controller) {
politicianController = controller;
}
public void ShowPoliticianList() {
politicianController.ShowPoliticianList ();
}
public override bool ShouldOverrideUrlLoading (WebView webView, string url) {
var handled = PortableRazor.RouteHandler.HandleRequest (url);
return handled;
}
}
class HybridWebChromeClient : WebChromeClient {
Context context;
public HybridWebChromeClient (Context context) : base () {
this.context = context;
}
public override bool OnJsAlert (WebView view, string url, string message, JsResult result) {
var alertDialogBuilder = new AlertDialog.Builder (context)
.SetMessage (message)
.SetCancelable (false)
.SetPositiveButton ("Ok", (sender, args) => {
result.Confirm ();
});
alertDialogBuilder.Create().Show();
return true;
}
public override bool OnJsConfirm (WebView view, string url, string message, JsResult result) {
var alertDialogBuilder = new AlertDialog.Builder (context)
.SetMessage (message)
.SetCancelable (false)
.SetPositiveButton ("Ok", (sender, args) => {
result.Confirm();
})
.SetNegativeButton ("Cancel", (sender, args) => {
result.Cancel();
});
alertDialogBuilder.Create().Show();
return true;
}
}
}
}
| mit | C# |
4a24ec2c197d3abbfe8ec6f3e9b33a954a98c79b | Update test namespace | codeforamerica/denver-schedules-api,codeforamerica/denver-schedules-api,schlos/denver-schedules-api,schlos/denver-schedules-api | Schedules.API.Tests/Models/StreetSweepingTest.cs | Schedules.API.Tests/Models/StreetSweepingTest.cs | using NUnit.Framework;
using Schedules.API.Models;
namespace Schedules.API.Tests.Models
{
[TestFixture]
public class StreetSweepingTest
{
[Test]
public void ShouldHandleNullSweepingData()
{
var ss = new StreetSweeping () {
FullName = "hello"
};
Assert.DoesNotThrow(() => ss.CreateSchedules());
}
}
}
| using NUnit.Framework;
using Schedules.API.Models;
namespace Schedules.API.Tests
{
[TestFixture]
public class StreetSweepingTest
{
[Test]
public void ShouldHandleNullSweepingData()
{
var ss = new StreetSweeping () {
FullName = "hello"
};
Assert.DoesNotThrow(() => ss.CreateSchedules());
}
}
}
| mit | C# |
9fffea9d57d888be2db568991eedc15329fed3a9 | Update LoggingSetupBase.cs | tiksn/TIKSN-Framework | TIKSN.Core/Analytics/Logging/LoggingSetupBase.cs | TIKSN.Core/Analytics/Logging/LoggingSetupBase.cs | using Microsoft.Extensions.Logging;
namespace TIKSN.Analytics.Logging
{
public abstract class LoggingSetupBase : ILoggingSetup
{
public virtual void Setup(ILoggingBuilder loggingBuilder)
{
loggingBuilder.AddDebug();
}
}
} | using Microsoft.Extensions.Logging;
namespace TIKSN.Analytics.Logging
{
public abstract class LoggingSetupBase : ILoggingSetup
{
protected readonly ILoggerFactory _loggerFactory;
protected LoggingSetupBase(ILoggerFactory loggerFactory)
{
_loggerFactory = loggerFactory;
}
public virtual void Setup()
{
_loggerFactory.AddDebug(LogLevel.Trace);
}
}
} | mit | C# |
8df646acca06a78e999faf6183162251dfd5bd21 | Add drop-down menu for concerts. | alastairs/cgowebsite,alastairs/cgowebsite | src/CGO.Web/Views/Shared/_MenuBar.cshtml | src/CGO.Web/Views/Shared/_MenuBar.cshtml | @functions {
private string GetCssClass(string actionName, string controllerName)
{
var currentControllerName = ViewContext.RouteData.Values["controller"].ToString();
var isCurrentController = currentControllerName == controllerName;
if (currentControllerName == "Home")
{
return GetHomeControllerLinksCssClass(actionName, isCurrentController);
}
return isCurrentController ? "active" : string.Empty;
}
private string GetHomeControllerLinksCssClass(string actionName, bool isCurrentController)
{
if (!isCurrentController)
{
return string.Empty;
}
var isCurrentAction = ViewContext.RouteData.Values["action"].ToString() == actionName;
return isCurrentAction ? "active" : string.Empty;
}
}
@helper GetMenuBarLink(string linkText, string actionName, string controllerName)
{
<li class="dropdown @GetCssClass(actionName, controllerName)">
@if (controllerName == "Concerts" && Request.IsAuthenticated)
{
<a href="@Url.Action(actionName, controllerName)" class="dropdown-toggle" data-toggle="dropdown">
@linkText
<b class="caret"></b>
</a>
<ul class="dropdown-menu">
<li>@Html.ActionLink("Administer Concerts", "List", "Concerts")</li>
</ul>
}
else
{
@Html.ActionLink(linkText, actionName, controllerName)
}
</li>
}
<ul class="nav">
@GetMenuBarLink("Home", "Index", "Home")
@GetMenuBarLink("Concerts", "Index", "Concerts")
@GetMenuBarLink("Rehearsals", "Index", "Rehearsals")
@GetMenuBarLink("About", "About", "Home")
@GetMenuBarLink("Contact", "Contact", "Home")
</ul>
| @functions {
private string GetCssClass(string actionName, string controllerName)
{
var currentControllerName = ViewContext.RouteData.Values["controller"].ToString();
var isCurrentController = currentControllerName == controllerName;
if (currentControllerName == "Home")
{
return GetHomeControllerLinksCssClass(actionName, isCurrentController);
}
return isCurrentController ? "active" : string.Empty;
}
private string GetHomeControllerLinksCssClass(string actionName, bool isCurrentController)
{
if (!isCurrentController)
{
return string.Empty;
}
var isCurrentAction = ViewContext.RouteData.Values["action"].ToString() == actionName;
return isCurrentAction ? "active" : string.Empty;
}
}
@helper GetMenuBarLink(string linkText, string actionName, string controllerName)
{
<li class="@GetCssClass(actionName, controllerName)">@Html.ActionLink(linkText, actionName, controllerName)</li>
}
<ul class="nav">
@GetMenuBarLink("Home", "Index", "Home")
@GetMenuBarLink("Concerts", "Index", "Concerts")
@GetMenuBarLink("Rehearsals", "Index", "Rehearsals")
@GetMenuBarLink("About", "About", "Home")
@GetMenuBarLink("Contact", "Contact", "Home")
</ul>
| mit | C# |
93589f2a44094cbe0582644d1696da1f6f81da34 | Change to use ThreadLocal<T> from TheadStatic (#28) | dennisroche/DateTimeProvider | src/DateTimeProvider/DateTimeProvider.cs | src/DateTimeProvider/DateTimeProvider.cs | using System;
using System.Threading;
using DateTimeProviders;
// ReSharper disable CheckNamespace
// Using global:: namespace
public static class DateTimeProvider
{
private static readonly ThreadLocal<IDateTimeProvider> ProviderThreadLocal;
static DateTimeProvider()
{
ProviderThreadLocal = new ThreadLocal<IDateTimeProvider>(() => new UtcDateTimeProvider());
}
public static DateTimeOffset Now => ProviderThreadLocal.Value.Now;
public static DateTime LocalNow => ProviderThreadLocal.Value.Now.LocalDateTime;
public static DateTime UtcNow => ProviderThreadLocal.Value.Now.UtcDateTime;
public static IDateTimeProvider Provider
{
get => ProviderThreadLocal.Value;
set => ProviderThreadLocal.Value = value;
}
} | using System;
using DateTimeProviders;
// ReSharper disable CheckNamespace
// Using global:: namespace
public static class DateTimeProvider
{
[ThreadStatic]
private static IDateTimeProvider _provider;
static DateTimeProvider()
{
Provider = new UtcDateTimeProvider();
}
public static DateTimeOffset Now => Provider.Now;
public static DateTime LocalNow => Provider.Now.LocalDateTime;
public static DateTime UtcNow => Provider.Now.UtcDateTime;
public static IDateTimeProvider Provider { get => _provider; set => _provider = value; }
} | mit | C# |
88c29fe2c11f6311c332321d133bc0be10ab9b2e | Refactor - Move Skip, Take duplicate code | umutozel/DynamicQueryable | src/DynamicQueryable/DynamicQueryable.cs | src/DynamicQueryable/DynamicQueryable.cs | using System.Collections.Generic;
using System.Linq.Expressions;
using Jokenizer.Net;
namespace System.Linq.Dynamic {
public static partial class DynamicQueryable {
public static IQueryable<T> As<T>(this IQueryable source) {
return (IQueryable<T>)source;
}
public static IQueryable Take(this IQueryable source, int count) {
return HandleConstant(source, "Take", count);
}
public static IQueryable Skip(this IQueryable source, int count) {
return HandleConstant(source, "Skip", count);
}
public static IQueryable HandleConstant(this IQueryable source, string method, int count) {
if (source == null) throw new ArgumentNullException(nameof(source));
return source.Provider.CreateQuery(
Expression.Call(
typeof(Queryable),
method,
new[] { source.ElementType },
source.Expression,
Expression.Constant(count)
)
);
}
}
}
| using System.Collections.Generic;
using System.Linq.Expressions;
using Jokenizer.Net;
namespace System.Linq.Dynamic {
public static partial class DynamicQueryable {
public static IQueryable<T> As<T>(this IQueryable source) {
return (IQueryable<T>)source;
}
public static IQueryable Take(this IQueryable source, int count) {
if (source == null) throw new ArgumentNullException(nameof(source));
return source.Provider.CreateQuery(
Expression.Call(
typeof(Queryable),
"Take",
new[] { source.ElementType },
source.Expression,
Expression.Constant(count))
);
}
public static IQueryable Skip(this IQueryable source, int count) {
if (source == null) throw new ArgumentNullException(nameof(source));
return source.Provider.CreateQuery(
Expression.Call(
typeof(Queryable),
"Skip",
new[] { source.ElementType },
source.Expression,
Expression.Constant(count)
)
);
}
}
}
| mit | C# |
5496abdc7e0b9a5c54be26c1a8ad964a3eae03e3 | Change cache version | JetBrains/resharper-unity,JetBrains/resharper-unity,JetBrains/resharper-unity | resharper/resharper-unity/src/CacheVersion.cs | resharper/resharper-unity/src/CacheVersion.cs | using JetBrains.Annotations;
using JetBrains.Application.PersistentMap;
using JetBrains.Serialization;
namespace JetBrains.ReSharper.Plugins.Unity
{
// Cache version
[PolymorphicMarshaller(19)]
public class CacheVersion
{
[UsedImplicitly] public static UnsafeReader.ReadDelegate<object> ReadDelegate = r => new CacheVersion();
[UsedImplicitly] public static UnsafeWriter.WriteDelegate<object> WriteDelegate = (w, o) => { };
}
} | using JetBrains.Annotations;
using JetBrains.Application.PersistentMap;
using JetBrains.Serialization;
namespace JetBrains.ReSharper.Plugins.Unity
{
// Cache version
[PolymorphicMarshaller(35)]
public class CacheVersion
{
[UsedImplicitly] public static UnsafeReader.ReadDelegate<object> ReadDelegate = r => new CacheVersion();
[UsedImplicitly] public static UnsafeWriter.WriteDelegate<object> WriteDelegate = (w, o) => { };
}
} | apache-2.0 | C# |
b01e2ce24cee465f97126c41c23f1d7140ad69db | Fix NH-2480 | nhibernate/nhibernate-core,ManufacturingIntelligence/nhibernate-core,nhibernate/nhibernate-core,RogerKratz/nhibernate-core,livioc/nhibernate-core,ngbrown/nhibernate-core,gliljas/nhibernate-core,ManufacturingIntelligence/nhibernate-core,nkreipke/nhibernate-core,hazzik/nhibernate-core,fredericDelaporte/nhibernate-core,fredericDelaporte/nhibernate-core,nhibernate/nhibernate-core,nkreipke/nhibernate-core,hazzik/nhibernate-core,gliljas/nhibernate-core,lnu/nhibernate-core,fredericDelaporte/nhibernate-core,gliljas/nhibernate-core,ManufacturingIntelligence/nhibernate-core,livioc/nhibernate-core,hazzik/nhibernate-core,RogerKratz/nhibernate-core,livioc/nhibernate-core,ngbrown/nhibernate-core,fredericDelaporte/nhibernate-core,nkreipke/nhibernate-core,ngbrown/nhibernate-core,lnu/nhibernate-core,RogerKratz/nhibernate-core,gliljas/nhibernate-core,RogerKratz/nhibernate-core,alobakov/nhibernate-core,alobakov/nhibernate-core,hazzik/nhibernate-core,alobakov/nhibernate-core,lnu/nhibernate-core,nhibernate/nhibernate-core | src/NHibernate.Test/Linq/LinqTestCase.cs | src/NHibernate.Test/Linq/LinqTestCase.cs | using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using NHibernate.DomainModel.Northwind.Entities;
using NUnit.Framework;
using SharpTestsEx;
namespace NHibernate.Test.Linq
{
public class LinqTestCase : ReadonlyTestCase
{
private Northwind _northwind;
private ISession _session;
protected override IList Mappings
{
get
{
return new[]
{
"Northwind.Mappings.Customer.hbm.xml",
"Northwind.Mappings.Employee.hbm.xml",
"Northwind.Mappings.Order.hbm.xml",
"Northwind.Mappings.OrderLine.hbm.xml",
"Northwind.Mappings.Product.hbm.xml",
"Northwind.Mappings.ProductCategory.hbm.xml",
"Northwind.Mappings.Region.hbm.xml",
"Northwind.Mappings.Shipper.hbm.xml",
"Northwind.Mappings.Supplier.hbm.xml",
"Northwind.Mappings.Territory.hbm.xml",
"Northwind.Mappings.AnotherEntity.hbm.xml",
"Northwind.Mappings.Role.hbm.xml",
"Northwind.Mappings.User.hbm.xml",
"Northwind.Mappings.TimeSheet.hbm.xml",
"Northwind.Mappings.Animal.hbm.xml",
"Northwind.Mappings.Patient.hbm.xml"
};
}
}
protected Northwind db
{
get { return _northwind; }
}
protected ISession session
{
get { return _session; }
}
protected override void OnSetUp()
{
base.OnSetUp();
_session = OpenSession();
_northwind = new Northwind(_session);
}
protected override void OnTearDown()
{
if (_session.IsOpen)
{
_session.Close();
}
}
public void AssertByIds<TEntity, TId>(IEnumerable<TEntity> entities, TId[] expectedIds, Converter<TEntity, TId> entityIdGetter)
{
entities.Select(x => entityIdGetter(x)).Should().Have.SameValuesAs(expectedIds);
}
}
} | using System;
using System.Collections;
using System.Collections.Generic;
using NHibernate.DomainModel.Northwind.Entities;
using NUnit.Framework;
namespace NHibernate.Test.Linq
{
public class LinqTestCase : ReadonlyTestCase
{
private Northwind _northwind;
private ISession _session;
protected override IList Mappings
{
get
{
return new[]
{
"Northwind.Mappings.Customer.hbm.xml",
"Northwind.Mappings.Employee.hbm.xml",
"Northwind.Mappings.Order.hbm.xml",
"Northwind.Mappings.OrderLine.hbm.xml",
"Northwind.Mappings.Product.hbm.xml",
"Northwind.Mappings.ProductCategory.hbm.xml",
"Northwind.Mappings.Region.hbm.xml",
"Northwind.Mappings.Shipper.hbm.xml",
"Northwind.Mappings.Supplier.hbm.xml",
"Northwind.Mappings.Territory.hbm.xml",
"Northwind.Mappings.AnotherEntity.hbm.xml",
"Northwind.Mappings.Role.hbm.xml",
"Northwind.Mappings.User.hbm.xml",
"Northwind.Mappings.TimeSheet.hbm.xml",
"Northwind.Mappings.Animal.hbm.xml",
"Northwind.Mappings.Patient.hbm.xml"
};
}
}
protected Northwind db
{
get { return _northwind; }
}
protected ISession session
{
get { return _session; }
}
protected override void OnSetUp()
{
base.OnSetUp();
_session = OpenSession();
_northwind = new Northwind(_session);
}
protected override void OnTearDown()
{
if (_session.IsOpen)
{
_session.Close();
}
}
public void AssertByIds<T, K>(IEnumerable<T> q, K[] ids, Converter<T, K> getId)
{
int current = 0;
foreach (T customer in q)
{
Assert.AreEqual(ids[current], getId(customer));
current += 1;
}
Assert.AreEqual(current, ids.Length);
}
}
} | lgpl-2.1 | C# |
9ae6d9d632fbe7a604d842d20d732fbff916de03 | Allow html descriptions | spadger/patent-spoiler,spadger/patent-spoiler,spadger/patent-spoiler | src/PatentSpoiler/Views/Item/View.cshtml | src/PatentSpoiler/Views/Item/View.cshtml | @model PatentSpoiler.App.DTOs.Item.DisplayItemViewModel
@{
ViewBag.Title = Model.Name;
Layout = "~/Views/Shared/_Layout.cshtml";
Bundles.Reference("scripts/custom/item", "end");
}
@section head{
}
@if (Model.LatestId.HasValue)
{
<p class="bg-warning">You are looking at an old verison of this item. Please go @Html.ActionLink("here", "View", new{id=Model.LatestId.Value}) to see the latest</p>
}
<div ng-app="item" ng-controller="ViewItemController">
<h2>@Model.Name</h2>
<div class="row">
<div class="col-md-1">Owner</div>
<div class="col-md-11"><a href="/user/@Model.Owner">@Model.Owner</a></div>
@if (ViewBag.CanEdit)
{
<div class="col-md-11"><a href="@Url.Action("View")/edit">Edit</a></div>
}
</div>
<div class="row">
<div class="col-md-1">Categories</div>
<div class="col-md-4">
<ul style="">
@foreach (var category in Model.Categories)
{
<li>@category</li>
}
</ul>
</div>
</div>
<div class="row">
@Html.Raw(Model.Description)
</div>
<div class="row">
<ul>
@foreach (var attachment in Model.Attachments)
{
<li>
@Html.RouteLink(@attachment.LinkText(), "GetAttachment", new {id = attachment.Id})
</li>
}
</ul>
</div>
<div class="btn-group" dropdown is-open="open">
<a href="javascript:void" ng-click="initHistory()" dropdown-toggle>Previous Versions</a>
<div class="dropdown-menu" role="menu" ng-click="$event.stopPropagation();initHistory()" style="min-width: 500px;">
<item-history set-id="@Model.SetId"></item-history>
</div>
</div>
</div> | @model PatentSpoiler.App.DTOs.Item.DisplayItemViewModel
@{
ViewBag.Title = Model.Name;
Layout = "~/Views/Shared/_Layout.cshtml";
Bundles.Reference("scripts/custom/item", "end");
}
@section head{
}
@if (Model.LatestId.HasValue)
{
<p class="bg-warning">You are looking at an old verison of this item. Please go @Html.ActionLink("here", "View", new{id=Model.LatestId.Value}) to see the latest</p>
}
<div ng-app="item" ng-controller="ViewItemController">
<h2>@Model.Name</h2>
<div class="row">
<div class="col-md-1">Owner</div>
<div class="col-md-11"><a href="/user/@Model.Owner">@Model.Owner</a></div>
@if (ViewBag.CanEdit)
{
<div class="col-md-11"><a href="@Url.Action("View")/edit">Edit</a></div>
}
</div>
<div class="row">
<div class="col-md-1">Categories</div>
<div class="col-md-4">
<ul style="">
@foreach (var category in Model.Categories)
{
<li>@category</li>
}
</ul>
</div>
</div>
<div class="row">
<pre>@Model.Description</pre>
</div>
<div class="row">
<ul>
@foreach (var attachment in Model.Attachments)
{
<li>
@Html.RouteLink(@attachment.LinkText(), "GetAttachment", new {id = attachment.Id})
</li>
}
</ul>
</div>
<div class="btn-group" dropdown is-open="open">
<a href="javascript:void" ng-click="initHistory()" dropdown-toggle>Previous Versions</a>
<div class="dropdown-menu" role="menu" ng-click="$event.stopPropagation();initHistory()" style="min-width: 500px;">
<item-history set-id="@Model.SetId"></item-history>
</div>
</div>
</div> | apache-2.0 | C# |
484478110e52c653f0dba98a7c7a8f47a0a57217 | Add null checker | inputfalken/Sharpy | src/Sharpy/src/Implementation/ExtensionMethods/ReadOnlyListExtensions.cs | src/Sharpy/src/Implementation/ExtensionMethods/ReadOnlyListExtensions.cs | using System;
using System.Collections.Generic;
namespace Sharpy.Implementation.ExtensionMethods {
internal static class ReadOnlyListExtensions {
internal static T RandomItem<T>(this IReadOnlyList<T> list, Random random) => list != null
? random != null
? list[random.Next(list.Count)]
: throw new ArgumentNullException(nameof(random))
: throw new ArgumentNullException(nameof(list));
}
} | using System;
using System.Collections.Generic;
namespace Sharpy.Implementation.ExtensionMethods {
internal static class ReadOnlyListExtensions {
internal static T RandomItem<T>(this IReadOnlyList<T> list, Random random) => list[random.Next(list.Count)];
}
} | mit | C# |
5fa308888de7f33f592b09563be71014d59b0190 | Fix start video | octoblu/meshblu-connector-skype,octoblu/meshblu-connector-skype | src/csharp/start-video.cs | src/csharp/start-video.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Lync.Model;
using Microsoft.Lync.Model.Conversation;
using Microsoft.Lync.Model.Conversation.AudioVideo;
using Microsoft.Lync.Model.Extensibility;
public class Startup
{
public Conversation GetConversation()
{
return LyncClient.GetClient().ConversationManager.Conversations.FirstOrDefault();
}
public Task WaitToConnect()
{
var conversation = GetConversation();
var avModality = ((AVModality)conversation.Modalities[ModalityTypes.AudioVideo]);
var tcs = new TaskCompletionSource<bool>();
EventHandler<ModalityStateChangedEventArgs> handler = null;
handler = (sender, e) => {
if (e.NewState != ModalityState.Connected) return;
if (!((AVModality)sender).VideoChannel.CanInvoke(ChannelAction.Start)) return;
avModality.ModalityStateChanged -= handler;
tcs.TrySetResult(true);
};
avModality.ModalityStateChanged += handler;
return tcs.Task;
}
public async Task<VideoChannel> GetVideoChannel()
{
var conversation = GetConversation();
if (conversation == null) throw new System.InvalidOperationException("Cannot enable video on non-extant conversation");
var avModality = ((AVModality)conversation.Modalities[ModalityTypes.AudioVideo]);
if (avModality.State != ModalityState.Connected) {
await WaitToConnect();
}
return avModality.VideoChannel;
}
private Task waitTillConnected(VideoChannel videoChannel)
{
var tcs = new TaskCompletionSource<bool>();
videoChannel.StateChanged += (sender, e) => {
if (e.NewState == ChannelState.Connecting) return;
tcs.TrySetResult(true);
};
return tcs.Task;
}
public async Task<object> Invoke(string ignored)
{
var videoChannel = await GetVideoChannel();
if (videoChannel.State == ChannelState.Connecting) await waitTillConnected(videoChannel);
if (videoChannel.State == ChannelState.Send) return null;
if (videoChannel.State == ChannelState.SendReceive) return null;
videoChannel.BeginStart(null, null);
return null;
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Lync.Model;
using Microsoft.Lync.Model.Conversation;
using Microsoft.Lync.Model.Conversation.AudioVideo;
using Microsoft.Lync.Model.Extensibility;
public class Startup
{
public Conversation GetConversation()
{
return LyncClient.GetClient().ConversationManager.Conversations.FirstOrDefault();
}
public Task WaitToConnect()
{
var conversation = GetConversation();
var avModality = ((AVModality)conversation.Modalities[ModalityTypes.AudioVideo]);
var tcs = new TaskCompletionSource<bool>();
EventHandler<ModalityStateChangedEventArgs> handler = null;
handler = (sender, e) => {
if (e.NewState != ModalityState.Connected) return;
if (!((AVModality)sender).VideoChannel.CanInvoke(ChannelAction.Start)) return;
avModality.ModalityStateChanged -= handler;
tcs.TrySetResult(true);
};
avModality.ModalityStateChanged += handler;
return tcs.Task;
}
public async Task<VideoChannel> GetVideoChannel()
{
var conversation = GetConversation();
if (conversation == null) throw new System.InvalidOperationException("Cannot enable video on non-extant conversation");
var avModality = ((AVModality)conversation.Modalities[ModalityTypes.AudioVideo]);
if (avModality.State != ModalityState.Connected) {
await WaitToConnect();
}
return avModality.VideoChannel;
}
private Task waitTillConnected(VideoChannel videoChannel)
{
var tcs = new TaskCompletionSource<bool>();
videoChannel.StateChanged += (sender, e) => {
if (e.NewState == ChannelState.Connecting) return;
tcs.TrySetResult(true);
};
return tcs.Task;
}
public async Task<object> Invoke(string ignored)
{
var videoChannel = await GetVideoChannel();
if (videoChannel.State == ChannelState.Connecting) await waitTillConnected(videoChannel);
if (videoChannel.State == ChannelState.Receive) return null;
if (videoChannel.State == ChannelState.SendReceive) return null;
videoChannel.BeginStart(null, null);
return null;
}
}
| mit | C# |
7e38c1e80348b516aa89c0f1110fc551c879da78 | use NRT | physhi/roslyn,wvdd007/roslyn,CyrusNajmabadi/roslyn,KevinRansom/roslyn,eriawan/roslyn,bartdesmet/roslyn,mavasani/roslyn,physhi/roslyn,KevinRansom/roslyn,AmadeusW/roslyn,jasonmalinowski/roslyn,weltkante/roslyn,AmadeusW/roslyn,eriawan/roslyn,weltkante/roslyn,diryboy/roslyn,dotnet/roslyn,mavasani/roslyn,sharwell/roslyn,eriawan/roslyn,sharwell/roslyn,diryboy/roslyn,shyamnamboodiripad/roslyn,weltkante/roslyn,shyamnamboodiripad/roslyn,mavasani/roslyn,shyamnamboodiripad/roslyn,AmadeusW/roslyn,diryboy/roslyn,wvdd007/roslyn,CyrusNajmabadi/roslyn,bartdesmet/roslyn,physhi/roslyn,sharwell/roslyn,bartdesmet/roslyn,wvdd007/roslyn,jasonmalinowski/roslyn,dotnet/roslyn,CyrusNajmabadi/roslyn,KevinRansom/roslyn,jasonmalinowski/roslyn,dotnet/roslyn | src/Features/Core/Portable/AddParameter/IAddParameterService.cs | src/Features/Core/Portable/AddParameter/IAddParameterService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.AddParameter
{
internal interface IAddParameterService
{
/// <summary>
/// Checks if there are indications that there might be more than one declarations that need to be fixed.
/// The check does not look-up if there are other declarations (this is done later in the CodeAction).
/// </summary>
bool HasCascadingDeclarations(IMethodSymbol method);
/// <summary>
/// Adds a parameter to a method.
/// </summary>
/// <param name="newParameterIndex"><see langword="null"/> to add as the final parameter</param>
/// <returns></returns>
Task<Solution> AddParameterAsync(
Document invocationDocument,
IMethodSymbol method,
ITypeSymbol newParamaterType,
RefKind refKind,
string parameterName,
int? newParameterIndex,
bool fixAllReferences,
CancellationToken cancellationToken);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.AddParameter
{
internal interface IAddParameterService
{
/// <summary>
/// Checks if there are indications that there might be more than one declarations that need to be fixed.
/// The check does not look-up if there are other declarations (this is done later in the CodeAction).
/// </summary>
bool HasCascadingDeclarations(IMethodSymbol method);
/// <summary>
/// Adds a parameter to a method.
/// </summary>
/// <param name="newParameterIndex"><see langword="null"/> to add as the final parameter</param>
/// <returns></returns>
Task<Solution> AddParameterAsync(
Document invocationDocument,
IMethodSymbol method,
ITypeSymbol newParamaterType,
RefKind refKind,
string parameterName,
int? newParameterIndex,
bool fixAllReferences,
CancellationToken cancellationToken);
}
}
| mit | C# |
fe7933af541dadd468e81823e49ea3837faebb1e | Revert "MemoryCacheの設定を親クラスに移動" | SunriseDigital/cs-sdx | Sdx/Web/DeviceRedirectHttpModule.cs | Sdx/Web/DeviceRedirectHttpModule.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Caching;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;
namespace Sdx.Web
{
public abstract class DeviceRedirectHttpModule : IHttpModule
{
private string mobileUa = @"DoCoMo|UP.Browser|SoftBank|WILLCOM";
private string smartPhoneUa = @"iPhone|Android.*Mobile|Windows.*Phone";
protected static MemoryCache memCache;
private void Application_BeginRequest(object source, EventArgs a)
{
var currentPageDevice = DetectUrlDevice(HttpContext.Current.Request.RawUrl);
var settingPath = GetSettingPath();
memCache = MemoryCacheSetting();
Sdx.Web.DeviceTable.Current = new Sdx.Web.DeviceTable(currentPageDevice, HttpContext.Current.Request.RawUrl, settingPath, memCache);
var currentUserAgentDevice = DetectUserAgentDevice();
if (currentPageDevice == currentUserAgentDevice)
{
return;
}
var url = Sdx.Web.DeviceTable.Current.GetUrl(currentUserAgentDevice);
if (!string.IsNullOrEmpty(url))
{
HttpContext.Current.Response.Redirect(url, false);
}
}
public void Init(HttpApplication application)
{
application.BeginRequest += new EventHandler(Application_BeginRequest);
}
public void Dispose() { }
protected abstract Sdx.Web.DeviceTable.Device DetectUrlDevice(string url);
private Sdx.Web.DeviceTable.Device DetectUserAgentDevice()
{
string userAgent = HttpContext.Current.Request.UserAgent;
Regex reg = new Regex(smartPhoneUa, RegexOptions.Compiled);
if (reg.IsMatch(userAgent))
{
return DeviceTable.Device.Sp;
}
reg = new Regex(mobileUa, RegexOptions.Compiled);
if (reg.IsMatch(userAgent))
{
return DeviceTable.Device.Mb;
}
return DeviceTable.Device.Pc;
}
protected abstract string GetSettingPath();
protected abstract MemoryCache MemoryCacheSetting();
}
}
| using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Runtime.Caching;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;
namespace Sdx.Web
{
public abstract class DeviceRedirectHttpModule : IHttpModule
{
private string mobileUa = @"DoCoMo|UP.Browser|SoftBank|WILLCOM";
private string smartPhoneUa = @"iPhone|Android.*Mobile|Windows.*Phone";
private string cacheKey = "DeviceTable";
protected static MemoryCache memCache;
private void Application_BeginRequest(object source, EventArgs a)
{
var currentPageDevice = DetectUrlDevice(HttpContext.Current.Request.RawUrl);
var settingPath = GetSettingPath();
memCache = MemoryCacheSetting();
Sdx.Web.DeviceTable.Current = new Sdx.Web.DeviceTable(currentPageDevice, HttpContext.Current.Request.RawUrl, settingPath, memCache);
var currentUserAgentDevice = DetectUserAgentDevice();
if (currentPageDevice == currentUserAgentDevice)
{
return;
}
var url = Sdx.Web.DeviceTable.Current.GetUrl(currentUserAgentDevice);
if (!string.IsNullOrEmpty(url))
{
HttpContext.Current.Response.Redirect(url, false);
}
}
public void Init(HttpApplication application)
{
application.BeginRequest += new EventHandler(Application_BeginRequest);
}
public void Dispose() { }
protected abstract Sdx.Web.DeviceTable.Device DetectUrlDevice(string url);
private Sdx.Web.DeviceTable.Device DetectUserAgentDevice()
{
string userAgent = HttpContext.Current.Request.UserAgent;
Regex reg = new Regex(smartPhoneUa, RegexOptions.Compiled);
if (reg.IsMatch(userAgent))
{
return DeviceTable.Device.Sp;
}
reg = new Regex(mobileUa, RegexOptions.Compiled);
if (reg.IsMatch(userAgent))
{
return DeviceTable.Device.Mb;
}
return DeviceTable.Device.Pc;
}
protected abstract string GetSettingPath();
protected MemoryCache MemoryCacheSetting()
{
if(memCache == null)
{
var config = new NameValueCollection();
config.Add("cacheMemoryLimitMegabytes", "10");
config.Add("pollingInterval", "00:02:00");
return new MemoryCache(cacheKey, config);
}
return memCache;
}
}
}
| mit | C# |
d06b5d7d03d4fe0047d1d346172ed45177e4a3b9 | Update ElementBase.cs | genusP/linq2db,giuliohome/linq2db,jogibear9988/linq2db,genusP/linq2db,LinqToDB4iSeries/linq2db,sdanyliv/linq2db,inickvel/linq2db,MaceWindu/linq2db,MaceWindu/linq2db,linq2db/linq2db,AK107/linq2db,AK107/linq2db,jogibear9988/linq2db,sdanyliv/linq2db,ronnyek/linq2db,LinqToDB4iSeries/linq2db,lvaleriu/linq2db,enginekit/linq2db,lvaleriu/linq2db,rechkalov/linq2db,barsgroup/bars2db,linq2db/linq2db,barsgroup/linq2db | Source/Configuration/ElementBase.cs | Source/Configuration/ElementBase.cs | using System;
using System.Collections.Specialized;
using System.Configuration;
namespace LinqToDB.Configuration
{
public abstract class ElementBase : ConfigurationElement
{
private readonly ConfigurationPropertyCollection _properties = new ConfigurationPropertyCollection();
protected override ConfigurationPropertyCollection Properties
{
get { return _properties; }
}
/// <summary>
/// Gets a value indicating whether an unknown attribute is encountered during deserialization.
/// </summary>
/// <returns>
/// True when an unknown attribute is encountered while deserializing.
/// </returns>
/// <param name="name">The name of the unrecognized attribute.</param>
/// <param name="value">The value of the unrecognized attribute.</param>
protected override bool OnDeserializeUnrecognizedAttribute(string name, string value)
{
var property = new ConfigurationProperty(name, typeof(string), value);
_properties.Add(property);
base[property] = value;
Attributes.Add(name, value);
return true;
}
readonly NameValueCollection _attributes = new NameValueCollection(StringComparer.OrdinalIgnoreCase);
public NameValueCollection Attributes
{
get { return _attributes; }
}
}
}
| using System;
using System.Collections.Specialized;
using System.Configuration;
namespace LinqToDB.Configuration
{
internal abstract class ElementBase : ConfigurationElement
{
private readonly ConfigurationPropertyCollection _properties = new ConfigurationPropertyCollection();
protected override ConfigurationPropertyCollection Properties
{
get { return _properties; }
}
/// <summary>
/// Gets a value indicating whether an unknown attribute is encountered during deserialization.
/// </summary>
/// <returns>
/// True when an unknown attribute is encountered while deserializing.
/// </returns>
/// <param name="name">The name of the unrecognized attribute.</param>
/// <param name="value">The value of the unrecognized attribute.</param>
protected override bool OnDeserializeUnrecognizedAttribute(string name, string value)
{
var property = new ConfigurationProperty(name, typeof(string), value);
_properties.Add(property);
base[property] = value;
Attributes.Add(name, value);
return true;
}
readonly NameValueCollection _attributes = new NameValueCollection(StringComparer.OrdinalIgnoreCase);
public NameValueCollection Attributes
{
get { return _attributes; }
}
}
} | mit | C# |
06198fc0fb402b249fab6fb3a64521c345a5ce42 | Remove unused Bus constructor. | fixie/fixie | src/Fixie/Internal/Bus.cs | src/Fixie/Internal/Bus.cs | namespace Fixie.Internal
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Reports;
class Bus
{
readonly TextWriter console;
readonly List<IReport> reports;
public Bus(TextWriter console, IReadOnlyList<IReport> reports)
{
this.console = console;
this.reports = new List<IReport>(reports);
}
public async Task Publish<TMessage>(TMessage message) where TMessage : IMessage
{
foreach (var report in reports)
{
try
{
if (report is IHandler<TMessage> handler)
await handler.Handle(message);
}
catch (Exception exception)
{
using (Foreground.Yellow)
console.WriteLine(
$"{report.GetType().FullName} threw an exception while " +
$"attempting to handle a message of type {typeof(TMessage).FullName}:");
console.WriteLine();
console.WriteLine(exception.ToString());
console.WriteLine();
}
}
}
}
} | namespace Fixie.Internal
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Reports;
class Bus
{
readonly TextWriter console;
readonly List<IReport> reports;
public Bus(TextWriter console, IReport report)
: this(console, new[] { report })
{
}
public Bus(TextWriter console, IReadOnlyList<IReport> reports)
{
this.console = console;
this.reports = new List<IReport>(reports);
}
public async Task Publish<TMessage>(TMessage message) where TMessage : IMessage
{
foreach (var report in reports)
{
try
{
if (report is IHandler<TMessage> handler)
await handler.Handle(message);
}
catch (Exception exception)
{
using (Foreground.Yellow)
console.WriteLine(
$"{report.GetType().FullName} threw an exception while " +
$"attempting to handle a message of type {typeof(TMessage).FullName}:");
console.WriteLine();
console.WriteLine(exception.ToString());
console.WriteLine();
}
}
}
}
} | mit | C# |
a0c6c73ff8aef5d50483287ca4036141153169ac | bump version | airbrake/SharpBrake,kayoom/SharpBrake,cbtnuggets/SharpBrake,airbrake/SharpBrake | SharpBrake/Properties/AssemblyInfo.cs | SharpBrake/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly : AssemblyTitle("SharpBrake")]
[assembly : AssemblyDescription("Airbrake Notifier for .NET")]
[assembly : AssemblyConfiguration("")]
[assembly : AssemblyCompany("")]
[assembly : AssemblyProduct("SharpBrake")]
[assembly : AssemblyCopyright("")]
[assembly : AssemblyTrademark("")]
[assembly : AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly : ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly : Guid("25ce95a4-58dd-4408-8484-e71f3c03549c")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly : AssemblyVersion("2.1.2")]
[assembly : AssemblyFileVersion("2.1.2")] | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly : AssemblyTitle("SharpBrake")]
[assembly : AssemblyDescription("Airbrake Notifier for .NET")]
[assembly : AssemblyConfiguration("")]
[assembly : AssemblyCompany("")]
[assembly : AssemblyProduct("SharpBrake")]
[assembly : AssemblyCopyright("")]
[assembly : AssemblyTrademark("")]
[assembly : AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly : ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly : Guid("25ce95a4-58dd-4408-8484-e71f3c03549c")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly : AssemblyVersion("2.1.1.0")]
[assembly : AssemblyFileVersion("2.1.1.0")] | mit | C# |
d22f557a3bd074ff4ee29128f7d8a3375dece37d | Remove possibility of double-disposal interference | UselessToucan/osu,ppy/osu,NeoAdonis/osu,NeoAdonis/osu,smoogipooo/osu,peppy/osu,ppy/osu,smoogipoo/osu,peppy/osu,ppy/osu,peppy/osu-new,smoogipoo/osu,UselessToucan/osu,NeoAdonis/osu,UselessToucan/osu,peppy/osu,smoogipoo/osu | osu.Game/Screens/OnlinePlay/OngoingOperationTracker.cs | osu.Game/Screens/OnlinePlay/OngoingOperationTracker.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
namespace osu.Game.Screens.OnlinePlay
{
/// <summary>
/// Utility class to track ongoing online operations' progress.
/// Can be used to disable interactivity while waiting for a response from online sources.
/// </summary>
public class OngoingOperationTracker : Component
{
/// <summary>
/// Whether there is an online operation in progress.
/// </summary>
public IBindable<bool> InProgress => inProgress;
private readonly Bindable<bool> inProgress = new BindableBool();
private LeasedBindable<bool> leasedInProgress;
public OngoingOperationTracker()
{
AlwaysPresent = true;
}
/// <summary>
/// Begins tracking a new online operation.
/// </summary>
/// <returns>
/// An <see cref="IDisposable"/> that will automatically mark the operation as ended on disposal.
/// </returns>
/// <exception cref="InvalidOperationException">An operation has already been started.</exception>
public IDisposable BeginOperation()
{
if (leasedInProgress != null)
throw new InvalidOperationException("Cannot begin operation while another is in progress.");
leasedInProgress = inProgress.BeginLease(true);
leasedInProgress.Value = true;
// for extra safety, marshal the end of operation back to the update thread if necessary.
return new OngoingOperation(() => Scheduler.Add(endOperation, false));
}
private void endOperation()
{
leasedInProgress?.Return();
leasedInProgress = null;
}
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
// base call does an UnbindAllBindables().
// clean up the leased reference here so that it doesn't get returned twice.
leasedInProgress = null;
}
private class OngoingOperation : InvokeOnDisposal
{
private bool isDisposed;
public OngoingOperation(Action action)
: base(action)
{
}
public override void Dispose()
{
// base class does not check disposal state for performance reasons which aren't relevant here.
// track locally, to avoid interfering with other operations in case of a potential double-disposal.
if (isDisposed)
return;
base.Dispose();
isDisposed = true;
}
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
namespace osu.Game.Screens.OnlinePlay
{
/// <summary>
/// Utility class to track ongoing online operations' progress.
/// Can be used to disable interactivity while waiting for a response from online sources.
/// </summary>
public class OngoingOperationTracker : Component
{
/// <summary>
/// Whether there is an online operation in progress.
/// </summary>
public IBindable<bool> InProgress => inProgress;
private readonly Bindable<bool> inProgress = new BindableBool();
private LeasedBindable<bool> leasedInProgress;
public OngoingOperationTracker()
{
AlwaysPresent = true;
}
/// <summary>
/// Begins tracking a new online operation.
/// </summary>
/// <returns>
/// An <see cref="IDisposable"/> that will automatically mark the operation as ended on disposal.
/// </returns>
/// <exception cref="InvalidOperationException">An operation has already been started.</exception>
public IDisposable BeginOperation()
{
if (leasedInProgress != null)
throw new InvalidOperationException("Cannot begin operation while another is in progress.");
leasedInProgress = inProgress.BeginLease(true);
leasedInProgress.Value = true;
// for extra safety, marshal the end of operation back to the update thread if necessary.
return new InvokeOnDisposal(() => Scheduler.Add(endOperation, false));
}
private void endOperation()
{
leasedInProgress?.Return();
leasedInProgress = null;
}
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
// base call does an UnbindAllBindables().
// clean up the leased reference here so that it doesn't get returned twice.
leasedInProgress = null;
}
}
}
| mit | C# |
d8bb72dd7811ecf1039ee8a377f30f8b995664c3 | remove unused using-directive | smoogipoo/osu,RedNesto/osu,DrabWeb/osu,ppy/osu,naoey/osu,UselessToucan/osu,peppy/osu,naoey/osu,peppy/osu-new,tacchinotacchi/osu,UselessToucan/osu,Frontear/osuKyzer,naoey/osu,Drezi126/osu,EVAST9919/osu,EVAST9919/osu,smoogipoo/osu,2yangk23/osu,johnneijzen/osu,NeoAdonis/osu,ZLima12/osu,Damnae/osu,johnneijzen/osu,DrabWeb/osu,nyaamara/osu,UselessToucan/osu,peppy/osu,NeoAdonis/osu,ZLima12/osu,Nabile-Rahmani/osu,ppy/osu,NeoAdonis/osu,peppy/osu,smoogipooo/osu,osu-RP/osu-RP,ppy/osu,2yangk23/osu,DrabWeb/osu,smoogipoo/osu | osu.Game/Screens/Select/Details/BeatmapDetailsGraph.cs | osu.Game/Screens/Select/Details/BeatmapDetailsGraph.cs | // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using OpenTK.Graphics;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using System.Collections.Generic;
namespace osu.Game.Screens.Select.Details
{
public class BeatmapDetailsGraph : FillFlowContainer<BeatmapDetailsBar>
{
public IEnumerable<float> Values
{
set
{
List<float> values = value.ToList();
List<BeatmapDetailsBar> graphBars = Children.ToList();
for (int i = 0; i < values.Count; i++)
if (graphBars.Count > i)
{
graphBars[i].Length = values[i] / values.Max();
graphBars[i].Width = 1.0f / values.Count;
}
else
Add(new BeatmapDetailsBar
{
RelativeSizeAxes = Axes.Both,
Width = 1.0f / values.Count,
Length = values[i] / values.Max(),
Direction = BarDirection.BottomToTop,
BackgroundColour = new Color4(0, 0, 0, 0),
});
}
}
}
}
| // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using OpenTK.Graphics;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using System.Collections.Generic;
using System.Linq;
namespace osu.Game.Screens.Select.Details
{
public class BeatmapDetailsGraph : FillFlowContainer<BeatmapDetailsBar>
{
public IEnumerable<float> Values
{
set
{
List<float> values = value.ToList();
List<BeatmapDetailsBar> graphBars = Children.ToList();
for (int i = 0; i < values.Count; i++)
if (graphBars.Count > i)
{
graphBars[i].Length = values[i] / values.Max();
graphBars[i].Width = 1.0f / values.Count;
}
else
Add(new BeatmapDetailsBar
{
RelativeSizeAxes = Axes.Both,
Width = 1.0f / values.Count,
Length = values[i] / values.Max(),
Direction = BarDirection.BottomToTop,
BackgroundColour = new Color4(0, 0, 0, 0),
});
}
}
}
}
| mit | C# |
22847b1a6f1ecdf7a7b70c0c2d589d7855c4a94d | Bump to version 1.4 | toehead2001/pdn-barcode | Barcode/Properties/AssemblyInfo.cs | Barcode/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Barcode Effect")]
[assembly: AssemblyDescription("Barcode Generator")]
[assembly: AssemblyConfiguration("Barcode|Code 39|POSTNET|UPC")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Barcode Effect")]
[assembly: AssemblyCopyright("Copyright © Michael J. Sepcot & toe_head2001")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("1.4.0.0")] | using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Barcode Effect")]
[assembly: AssemblyDescription("Barcode Generator")]
[assembly: AssemblyConfiguration("Barcode|Code 39|POSTNET|UPC")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Barcode Effect")]
[assembly: AssemblyCopyright("Copyright © Michael J. Sepcot & toe_head2001")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("1.3.0.0")] | mit | C# |
a15496db1b30696155e3c8697d6c0631342ca800 | Update Index.cshtml | ucdavis/Anlab,ucdavis/Anlab,ucdavis/Anlab,ucdavis/Anlab | Anlab.Mvc/Views/Home/Index.cshtml | Anlab.Mvc/Views/Home/Index.cshtml | @{
ViewData["Title"] = "Home Page";
}
<div class="col-8">
<div class="alert alert-info">
<button type="button" class="close" data-dismiss="alert">×</button>
Posted: April 6, 2020<br /><br />
We are continuing to work with limited staffing to comply with physical distancing for safety. The Receiving Area is
currently open for sample submission from 9am to noon. If you need to drop samples off outside of these hours, please
email the lab at anlab@ucdavis.edu to arrange a drop-off time. Please continue to email us with the expected delivery
date if you ship samples.<br /><br />
As time passes, samples previously submitted and not considered critical for immediate analysis may become more important
to your research. Please do not hesitate to email us at anlab@ucdavis.edu to let us know your needs. We hope to be able
to increase staffing levels soon.<br /><br />
Please monitor our home page for updates and thank you for your patience!<br /><br />
Please be safe.
</div>
<p class="lead">The UC Davis Analytical Laboratory is a core support facility of the UC Davis College of Agriculture and Environmental Sciences.</p>
<p>Analytical Laboratory clients are University of California academics, other educational institutions, government agencies, and research-based businesses.
</p>
<p>In addition to analytical services, the Laboratory provides project assistance in the areas of analytical, agricultural and environmental chemistry. The Laboratory has an educational role, providing training to students and researchers in the
operation of a number of analytical methods and instruments.</p>
<p>Please Note: Dirk Holstege has recently retired as Laboratory Director of the UC Davis Analytical Laboratory.
We thank him for his nearly twenty years of service as Director of the Analytical Lab and his thirty-two years of service
as a UC Davis employee. We wish him all the best in his retirement.<br/> <br/>
Traci Francis, Laboratory Supervisor, is serving as Interim Director. </p>
</div>
<div class="col-4">
<address>
<p>UC Davis Analytical Lab<br> University of California Davis, California <br> 95616-5270 <br> Phone: <span style="white-space: nowrap">(530) 752-0147</span> <br> Fax: <span style="white-space: nowrap">(530) 752-9892</span> <br> Email: <a href="mailto:anlab@ucdavis.edu">anlab@ucdavis.edu</a></p>
</address>
</div>
| @{
ViewData["Title"] = "Home Page";
}
<div class="col-8">
<div class="alert alert-info">
<button type="button" class="close" data-dismiss="alert">×</button>
Posted: April 6, 2020<br /><br />
We are scaling back to a bare minimum staff at this time. We will only be working on samples where immediate testing is essential. Assisting you with your research is very important to us and we are eager to return to full staffing as soon as it is safe.<br /> <br />
For the week of April 6-10, receiving will be open from 9am to noon.<br /><br />
Starting April 13th for sample drop-off please email us at <a href="mailto:anlab@ucdavis.edu">anlab@ucdavis.edu</a> to arrange a time to meet at receiving. If you need to ship samples to us, please email us with the expected delivery date.<br /><br />
Please use this option for samples requiring immediate testing for essential research. We can also arrange for receipt of more routine samples if proper storage of samples cannot be arranged in your own facility as we await a return to normal business operations.<br /><br />
Please monitor our homepage for updates and thank you for your patience!<br /><br />
Please be safe.
</div>
<p class="lead">The UC Davis Analytical Laboratory is a core support facility of the UC Davis College of Agriculture and Environmental Sciences.</p>
<p>Analytical Laboratory clients are University of California academics, other educational institutions, government agencies, and research-based businesses.
</p>
<p>In addition to analytical services, the Laboratory provides project assistance in the areas of analytical, agricultural and environmental chemistry. The Laboratory has an educational role, providing training to students and researchers in the
operation of a number of analytical methods and instruments.</p>
<p>Please Note: Dirk Holstege has recently retired as Laboratory Director of the UC Davis Analytical Laboratory.
We thank him for his nearly twenty years of service as Director of the Analytical Lab and his thirty-two years of service
as a UC Davis employee. We wish him all the best in his retirement.<br/> <br/>
Traci Francis, Laboratory Supervisor, is serving as Interim Director. </p>
</div>
<div class="col-4">
<address>
<p>UC Davis Analytical Lab<br> University of California Davis, California <br> 95616-5270 <br> Phone: <span style="white-space: nowrap">(530) 752-0147</span> <br> Fax: <span style="white-space: nowrap">(530) 752-9892</span> <br> Email: <a href="mailto:anlab@ucdavis.edu">anlab@ucdavis.edu</a></p>
</address>
</div>
| mit | C# |
cc7fadd8809900cfbb54a718f30e0cb31deecae9 | create group validation test | Simocracy/CLSim | CLSim-Test/ChampionsLeagueTest.cs | CLSim-Test/ChampionsLeagueTest.cs | using System;
using System.Collections.ObjectModel;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Simocracy.CLSim.Simulation;
namespace Simocracy.CLSim.Test
{
[TestClass]
public class ChampionsLeagueTest
{
private ChampionsLeague _Cl;
[TestInitialize]
public void InitTests()
{
_Cl = null;
_Cl = new ChampionsLeague();
var groupA = new FootballLeague("A",
new FootballTeam("{{UNS}} Seattle", "12"),
new FootballTeam("{{UNS}} SRFC", "12"),
new FootballTeam("{{GRA}} SV", "12"));
var groupB = new FootballLeague("B",
new FootballTeam("{{FRC}} BAM", "12"),
new FootballTeam("{{MAC}} Tesoro", "12"),
new FootballTeam("{{GRA}} GS", "12"));
_Cl.Groups = new ObservableCollection<FootballLeague> {groupA, groupB};
}
[TestMethod]
public void TestGroupValidation()
{
_Cl.ValidateGroups();
Assert.AreEqual("BAM", _Cl.Groups[0].Teams[0].Name);
Assert.AreEqual("Seattle", _Cl.Groups[1].Teams[0].Name);
}
}
}
| using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Simocracy.CLSim.Simulation;
namespace Simocracy.CLSim.Test
{
[TestClass]
public class ChampionsLeagueTest
{
[TestMethod]
public void TestMethod1()
{
}
}
}
| mit | C# |
3966feaf81087ad06c9e8af03c7444ca0c14da9a | use ienumerable | SimonCropp/CaptureSnippets | CaptureSnippets/SnippetGrouper.cs | CaptureSnippets/SnippetGrouper.cs | using System.Collections.Generic;
using System.Linq;
namespace CaptureSnippets
{
public static class SnippetGrouper
{
public static IEnumerable<SnippetGroup> Group(IEnumerable<ReadSnippet> snippets)
{
Guard.AgainstNull(snippets, "snippets");
foreach (var grouping in snippets.GroupBy(x => x.Key))
{
var versions = GetVersionGroups(grouping).ToList();
if (versions.Count > 1)
{
versions = versions.OrderByDescending(x => x.Version, VersionComparer.Instance).ToList();
}
yield return new SnippetGroup(key: grouping.Key, versions: versions);
}
}
static IEnumerable<VersionGroup> GetVersionGroups(IEnumerable<ReadSnippet> keyGrouping)
{
return keyGrouping.GroupBy(x => x.Version, VersionEquator.Instance)
.Select(versionGrouping => new VersionGroup(versionGrouping.Key, GetSnippets(versionGrouping)));
}
static IEnumerable<Snippet> GetSnippets(IEnumerable<ReadSnippet> versionGrouping)
{
return versionGrouping.Select(readSnippet =>
new Snippet(value: readSnippet.Value,
endLine: readSnippet.EndLine,
file: readSnippet.File,
language: readSnippet.Language,
startLine: readSnippet.StartLine));
}
}
} | using System.Collections.Generic;
using System.Linq;
namespace CaptureSnippets
{
public static class SnippetGrouper
{
public static IEnumerable<SnippetGroup> Group(IEnumerable<ReadSnippet> snippets)
{
Guard.AgainstNull(snippets, "snippets");
foreach (var grouping in snippets.GroupBy(x => x.Key))
{
var versions = GetVersionGroups(grouping).ToList();
if (versions.Count > 1)
{
versions = versions.OrderByDescending(x => x.Version, VersionComparer.Instance).ToList();
}
yield return new SnippetGroup(key: grouping.Key, versions: versions);
}
}
static IEnumerable<VersionGroup> GetVersionGroups(IGrouping<string, ReadSnippet> keyGrouping)
{
return keyGrouping.GroupBy(x => x.Version, VersionEquator.Instance)
.Select(versionGrouping => new VersionGroup(versionGrouping.Key, GetSnippets(versionGrouping)));
}
static IEnumerable<Snippet> GetSnippets(IGrouping<Version, ReadSnippet> versionGrouping)
{
return versionGrouping.Select(readSnippet =>
new Snippet(value: readSnippet.Value,
endLine: readSnippet.EndLine,
file: readSnippet.File,
language: readSnippet.Language,
startLine: readSnippet.StartLine));
}
}
} | mit | C# |
dce7e084cffb2b2c37a369797121d973aedb56cc | Ajuste no método FormataLogradouro | BoletoNet/boleto2net,rafd75/boleto2net | Boleto2.Net/Boleto/Endereco.cs | Boleto2.Net/Boleto/Endereco.cs | namespace Boleto2Net
{
/// <summary>
/// Representa o endereço do Cedente ou Sacado.
/// </summary>
public class Endereco
{
public string LogradouroEndereco { get; set; } = string.Empty;
public string LogradouroNumero { get; set; } = string.Empty;
public string LogradouroComplemento { get; set; } = string.Empty;
public string Bairro { get; set; } = string.Empty;
public string Cidade { get; set; } = string.Empty;
public string UF { get; set; } = string.Empty;
public string CEP { get; set; } = string.Empty;
public string FormataLogradouro(int tamanhoFinal)
{
var logradouroCompleto = string.Empty;
if (!string.IsNullOrEmpty(LogradouroNumero))
logradouroCompleto += " " + LogradouroNumero;
if (!string.IsNullOrEmpty(LogradouroComplemento))
logradouroCompleto += " " + (LogradouroComplemento.Length > 20 ? LogradouroComplemento.Substring(0, 20) : LogradouroComplemento);
if (tamanhoFinal == 0)
return LogradouroEndereco + logradouroCompleto;
if (LogradouroEndereco.Length + logradouroCompleto.Length <= tamanhoFinal)
return LogradouroEndereco + logradouroCompleto;
return LogradouroEndereco.Substring(0, tamanhoFinal - logradouroCompleto.Length) + logradouroCompleto;
}
}
}
| namespace Boleto2Net
{
/// <summary>
/// Representa o endereço do Cedente ou Sacado.
/// </summary>
public class Endereco
{
public string LogradouroEndereco { get; set; } = string.Empty;
public string LogradouroNumero { get; set; } = string.Empty;
public string LogradouroComplemento { get; set; } = string.Empty;
public string Bairro { get; set; } = string.Empty;
public string Cidade { get; set; } = string.Empty;
public string UF { get; set; } = string.Empty;
public string CEP { get; set; } = string.Empty;
public string FormataLogradouro(int tamanhoFinal)
{
var logradouroCompleto = string.Empty;
if (!string.IsNullOrEmpty(LogradouroNumero))
logradouroCompleto += " " + LogradouroNumero;
if (!string.IsNullOrEmpty(LogradouroComplemento))
logradouroCompleto += " " + LogradouroComplemento;
if (tamanhoFinal == 0)
return LogradouroEndereco + logradouroCompleto;
if (LogradouroEndereco.Length + logradouroCompleto.Length <= tamanhoFinal)
return LogradouroEndereco + logradouroCompleto;
return LogradouroEndereco.Substring(0, tamanhoFinal - logradouroCompleto.Length) + logradouroCompleto;
}
}
}
| apache-2.0 | C# |
8c87538a7160d8e426f7e5d33cb7a97db5f4c0f8 | bump version | Fody/Fody,GeertvanHorrik/Fody,jasonholloway/Fody,distantcam/Fody,furesoft/Fody,PKRoma/Fody,ichengzi/Fody,ColinDabritzViewpoint/Fody,huoxudong125/Fody | CommonAssemblyInfo.cs | CommonAssemblyInfo.cs | using System.Reflection;
[assembly: AssemblyTitle("Fody")]
[assembly: AssemblyProduct("Fody")]
[assembly: AssemblyVersion("1.19.1")]
[assembly: AssemblyFileVersion("1.19.1")]
| using System.Reflection;
[assembly: AssemblyTitle("Fody")]
[assembly: AssemblyProduct("Fody")]
[assembly: AssemblyVersion("1.19.0")]
[assembly: AssemblyFileVersion("1.19.0")]
| mit | C# |
552226c63c7d61392ed6a182641a766edf9f31b6 | Update CurrencylayerDotComTests.cs | tiksn/TIKSN-Framework | TIKSN.Framework.IntegrationTests/Finance/ForeignExchange/CurrencylayerDotComTests.cs | TIKSN.Framework.IntegrationTests/Finance/ForeignExchange/CurrencylayerDotComTests.cs | using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using TIKSN.Finance.ForeignExchange.Cumulative;
using TIKSN.Framework.IntegrationTests;
using TIKSN.Globalization;
using TIKSN.Time;
using Xunit;
using Xunit.Abstractions;
namespace TIKSN.Finance.Tests.ForeignExchange
{
[Collection("ServiceProviderCollection")]
public class CurrencylayerDotComTests
{
private readonly string accessKey = "<put your access key here>";
private readonly ICurrencyFactory currencyFactory;
private readonly ITimeProvider timeProvider;
private readonly ServiceProviderFixture serviceProviderFixture;
public CurrencylayerDotComTests(ITestOutputHelper testOutputHelper, ServiceProviderFixture serviceProviderFixture)
{
this.currencyFactory = serviceProviderFixture.Services.GetRequiredService<ICurrencyFactory>();
this.timeProvider = serviceProviderFixture.Services.GetRequiredService<ITimeProvider>();
this.serviceProviderFixture = serviceProviderFixture ?? throw new ArgumentNullException(nameof(serviceProviderFixture));
}
//[Fact]
public async Task GetCurrencyPairs001()
{
var exchange = new CurrencylayerDotCom(this.currencyFactory, this.timeProvider, this.accessKey);
var pairs = await exchange.GetCurrencyPairsAsync(DateTimeOffset.Now, default);
Assert.True(pairs.Count() > 0);
}
//[Fact]
public async Task GetExchangeRateAsync001()
{
var exchange = new CurrencylayerDotCom(this.currencyFactory, this.timeProvider, this.accessKey);
var pair = new CurrencyPair(new CurrencyInfo("USD"), new CurrencyInfo("UAH"));
var rate = await exchange.GetExchangeRateAsync(pair, DateTimeOffset.Now, default);
Assert.True(rate > decimal.Zero);
}
}
}
| using Microsoft.Extensions.DependencyInjection;
using System;
using System.Linq;
using System.Threading.Tasks;
using TIKSN.DependencyInjection.Tests;
using TIKSN.Finance.ForeignExchange.Cumulative;
using TIKSN.Globalization;
using TIKSN.Time;
using Xunit;
using Xunit.Abstractions;
namespace TIKSN.Finance.Tests.ForeignExchange
{
public class CurrencylayerDotComTests
{
private string accessKey = "<put your access key here>";
private readonly IServiceProvider _serviceProvider;
private readonly ICurrencyFactory _currencyFactory;
private readonly ITimeProvider _timeProvider;
public CurrencylayerDotComTests(ITestOutputHelper testOutputHelper)
{
_serviceProvider = new TestCompositionRootSetup(testOutputHelper).CreateServiceProvider();
_currencyFactory = _serviceProvider.GetRequiredService<ICurrencyFactory>();
_timeProvider = _serviceProvider.GetRequiredService<ITimeProvider>();
}
//[Fact]
public async Task GetCurrencyPairs001()
{
var exchange = new CurrencylayerDotCom(_currencyFactory, _timeProvider, accessKey);
var pairs = await exchange.GetCurrencyPairsAsync(DateTimeOffset.Now, default);
Assert.True(pairs.Count() > 0);
}
//[Fact]
public async Task GetExchangeRateAsync001()
{
var exchange = new CurrencylayerDotCom(_currencyFactory, _timeProvider, accessKey);
var pair = new CurrencyPair(new CurrencyInfo("USD"), new CurrencyInfo("UAH"));
var rate = await exchange.GetExchangeRateAsync(pair, DateTimeOffset.Now, default);
Assert.True(rate > decimal.Zero);
}
}
} | mit | C# |
40af81094c28dba35f33914f10b4e1ea91d4a58d | Remove unused Arguments property. | neuecc/MagicOnion | src/MagicOnion/Server/FromServiceFilterAttribute.cs | src/MagicOnion/Server/FromServiceFilterAttribute.cs | using MagicOnion.Server.Hubs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace MagicOnion.Server
{
/// <summary>
/// A MagicOnion filter that provided another filter via <see cref="IServiceLocator"/>.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
public class FromServiceFilterAttribute : Attribute,
IMagicOnionFilterFactory<MagicOnionFilterAttribute>,
IMagicOnionFilterFactory<StreamingHubFilterAttribute>
{
public Type Type { get; }
public int Order { get; set; }
public FromServiceFilterAttribute(Type type)
{
if (!typeof(MagicOnionFilterAttribute).IsAssignableFrom(type) &&
!typeof(StreamingHubFilterAttribute).IsAssignableFrom(type))
{
throw new ArgumentException($"{type.FullName} doesn't inherit from MagicOnionFilterAttribute or StreamingHubFilterAttribute.", nameof(type));
}
Type = type;
}
MagicOnionFilterAttribute IMagicOnionFilterFactory<MagicOnionFilterAttribute>.CreateInstance(IServiceLocator serviceLocator)
{
if (!typeof(MagicOnionFilterAttribute).IsAssignableFrom(Type)) throw new InvalidOperationException($"Type '{Type.FullName}' doesn't inherit from {nameof(MagicOnionFilterAttribute)}.");
return CreateInstance<MagicOnionFilterAttribute>(serviceLocator);
}
StreamingHubFilterAttribute IMagicOnionFilterFactory<StreamingHubFilterAttribute>.CreateInstance(IServiceLocator serviceLocator)
{
if (!typeof(StreamingHubFilterAttribute).IsAssignableFrom(Type)) throw new InvalidOperationException($"Type '{Type.FullName}' doesn't inherit from {nameof(StreamingHubFilterAttribute)}.");
return CreateInstance<StreamingHubFilterAttribute>(serviceLocator);
}
protected T CreateInstance<T>(IServiceLocator serviceLocator)
{
return serviceLocator.GetService<T>();
}
}
}
| using MagicOnion.Server.Hubs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace MagicOnion.Server
{
/// <summary>
/// A MagicOnion filter that provided another filter via <see cref="IServiceLocator"/>.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
public class FromServiceFilterAttribute : Attribute,
IMagicOnionFilterFactory<MagicOnionFilterAttribute>,
IMagicOnionFilterFactory<StreamingHubFilterAttribute>
{
public Type Type { get; }
public int Order { get; set; }
public object[] Arguments { get; set; } = Array.Empty<object>();
public FromServiceFilterAttribute(Type type)
{
if (!typeof(MagicOnionFilterAttribute).IsAssignableFrom(type) &&
!typeof(StreamingHubFilterAttribute).IsAssignableFrom(type))
{
throw new ArgumentException($"{type.FullName} doesn't inherit from MagicOnionFilterAttribute or StreamingHubFilterAttribute.", nameof(type));
}
Type = type;
}
MagicOnionFilterAttribute IMagicOnionFilterFactory<MagicOnionFilterAttribute>.CreateInstance(IServiceLocator serviceLocator)
{
if (!typeof(MagicOnionFilterAttribute).IsAssignableFrom(Type)) throw new InvalidOperationException($"Type '{Type.FullName}' doesn't inherit from {nameof(MagicOnionFilterAttribute)}.");
return CreateInstance<MagicOnionFilterAttribute>(serviceLocator);
}
StreamingHubFilterAttribute IMagicOnionFilterFactory<StreamingHubFilterAttribute>.CreateInstance(IServiceLocator serviceLocator)
{
if (!typeof(StreamingHubFilterAttribute).IsAssignableFrom(Type)) throw new InvalidOperationException($"Type '{Type.FullName}' doesn't inherit from {nameof(StreamingHubFilterAttribute)}.");
return CreateInstance<StreamingHubFilterAttribute>(serviceLocator);
}
protected T CreateInstance<T>(IServiceLocator serviceLocator)
{
return serviceLocator.GetService<T>();
}
}
}
| mit | C# |
f2c72f7c0ea6fa04c118c71ad2b26922005d81a0 | Fix last test | space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14 | Content.Server/Chemistry/EntitySystems/ChemicalReactionSystem.cs | Content.Server/Chemistry/EntitySystems/ChemicalReactionSystem.cs | using Content.Shared.Chemistry.Components;
using Content.Shared.Chemistry.Reaction;
using Content.Shared.Chemistry.Reagent;
using Content.Shared.Database;
using Content.Shared.FixedPoint;
using Robust.Shared.Audio;
using Robust.Shared.GameObjects;
using Robust.Shared.Player;
namespace Content.Server.Chemistry.EntitySystems
{
public class ChemicalReactionSystem : SharedChemicalReactionSystem
{
protected override void OnReaction(Solution solution, ReactionPrototype reaction, ReagentPrototype randomReagent, EntityUid Owner, FixedPoint2 unitReactions)
{
base.OnReaction(solution, reaction, randomReagent, Owner, unitReactions);
var coordinates = EntityManager.GetComponent<TransformComponent>(Owner).Coordinates;
_logSystem.Add(LogType.ChemicalReaction, reaction.Impact,
$"Chemical reaction {reaction.ID} occurred with strength {unitReactions:strength} on entity {Owner} at {coordinates}");
SoundSystem.Play(Filter.Pvs(Owner, entityManager:EntityManager), reaction.Sound.GetSound(), Owner);
}
}
}
| using Content.Shared.Chemistry.Components;
using Content.Shared.Chemistry.Reaction;
using Content.Shared.Chemistry.Reagent;
using Content.Shared.Database;
using Content.Shared.FixedPoint;
using Robust.Shared.Audio;
using Robust.Shared.GameObjects;
using Robust.Shared.Player;
namespace Content.Server.Chemistry.EntitySystems
{
public class ChemicalReactionSystem : SharedChemicalReactionSystem
{
protected override void OnReaction(Solution solution, ReactionPrototype reaction, ReagentPrototype randomReagent, EntityUid Owner, FixedPoint2 unitReactions)
{
base.OnReaction(solution, reaction, randomReagent, Owner, unitReactions);
var coordinates = EntityManager.GetComponent<TransformComponent>(Owner);
_logSystem.Add(LogType.ChemicalReaction, reaction.Impact,
$"Chemical reaction {reaction.ID} occurred with strength {unitReactions:strength} on entity {Owner} at {coordinates}");
SoundSystem.Play(Filter.Pvs(Owner, entityManager:EntityManager), reaction.Sound.GetSound(), Owner);
}
}
}
| mit | C# |
41e2a5b907a2c0573386cb0b00bca782fac954fc | Bump version for NuGet publish. | realartists/chargebee-dotnet | ChargeBee/Properties/AssemblyInfo.cs | ChargeBee/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("RealArtists.ChargeBee")]
[assembly: AssemblyDescription("Modern .NET client library for integrating with the ChargeBee service.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("da556ed8-6c79-415f-97e0-6c37c83ef84b")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.4.2")]
[assembly: AssemblyFileVersion("2.4.2")]
[assembly: AssemblyCompany("Real Artists, Inc.")]
[assembly: AssemblyProduct("RealArtists.ChargeBee")]
[assembly: AssemblyCopyright("©ChargeBee Inc. and Nick Sivo. See LICENSE.")]
| using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("RealArtists.ChargeBee")]
[assembly: AssemblyDescription("Modern .NET client library for integrating with the ChargeBee service.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("da556ed8-6c79-415f-97e0-6c37c83ef84b")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.0.0")]
[assembly: AssemblyFileVersion("2.4.2")]
[assembly: AssemblyCompany("Real Artists, Inc.")]
[assembly: AssemblyProduct("RealArtists.ChargeBee")]
[assembly: AssemblyCopyright("©ChargeBee Inc. and Nick Sivo. See LICENSE.")]
| mit | C# |
222bf1c9ca89814614c2313c7cd4fc8f6cbedc30 | Test voice sample | AfricasTalkingLtd/africastalking.Net | Examples/Voice.MakeCall/Program.cs | Examples/Voice.MakeCall/Program.cs | using System;
using AfricasTalkingCS;
namespace Voice.MakeCall
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
var username = "sandbox";
var apiKey = "afd635a4f295dd936312836c0b944d55f2a836e8ff2b63987da5e717cd5ff745";
var from = "+254724545678";
var to = "+254725587654";
var gateway = new AfricasTalkingGateway(username, apiKey);
try
{
var results = gateway.Call(from, to);
Console.WriteLine(results);
}
catch (AfricasTalkingGatewayException exception)
{
Console.WriteLine("Something went horribly wrong: " + exception.Message + ".\nCaused by :" + exception.StackTrace);
}
Console.ReadLine();
}
}
}
| using System;
using AfricasTalkingCS;
namespace Voice.MakeCall
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
var username = "sandbox";
var apiKey = "Key";
var env = "sandbox";
var from = "+254724545678";
var to = "+254724587654";
var gateway = new AfricasTalkingGateway(username, apiKey, env);
try
{
var results = gateway.Call(from, to);
Console.WriteLine(results);
}
catch (AfricasTalkingGatewayException exception)
{
Console.WriteLine("Something went horribly wrong: " + exception.Message + ".\nCaused by :" + exception.StackTrace);
}
Console.ReadLine();
}
}
}
| mit | C# |
a34d1641b310b9afee3464aff9991c10e1c6f2dc | Set disable registration as default true. | btcpayserver/btcpayserver,btcpayserver/btcpayserver,btcpayserver/btcpayserver,btcpayserver/btcpayserver | BTCPayServer/Services/PoliciesSettings.cs | BTCPayServer/Services/PoliciesSettings.cs | using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace BTCPayServer.Services
{
public class PoliciesSettings
{
[Display(Name = "Requires a confirmation mail for registering")]
public bool RequiresConfirmedEmail
{
get; set;
}
[JsonProperty(DefaultValueHandling = DefaultValueHandling.Populate)]
[Display(Name = "Disable registration")]
public bool LockSubscription { get; set; } = true;
}
}
| using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace BTCPayServer.Services
{
public class PoliciesSettings
{
[Display(Name = "Requires a confirmation mail for registering")]
public bool RequiresConfirmedEmail
{
get; set;
}
[JsonProperty(DefaultValueHandling = DefaultValueHandling.Populate)]
[Display(Name = "Disable registration")]
public bool LockSubscription { get; set; }
}
}
| mit | C# |
7fb71ab51061cd02e864194e63c4332962c1cb2f | Change editor version to 2.0.1.0 (same as core module) | unvell/ReoGrid,unvell/ReoGrid | Editor/Properties/AssemblyInfo.cs | Editor/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ReoGrid Editor")]
[assembly: AssemblyDescription(".NET Spreadsheet Control")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("unvell.com")]
[assembly: AssemblyProduct("ReoGrid")]
[assembly: AssemblyCopyright("Copyright © 2012-2016 unvell.com, All Rights Seserved.")]
[assembly: AssemblyTrademark("ReoGrid.NET")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("f16dd6fe-47b0-4159-870e-53eaa59f8428")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.0.1.0")]
[assembly: AssemblyFileVersion("2.0.1.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ReoGrid Editor")]
[assembly: AssemblyDescription(".NET Spreadsheet Control")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("unvell.com")]
[assembly: AssemblyProduct("ReoGrid")]
[assembly: AssemblyCopyright("Copyright © 2012-2016 unvell.com, All Rights Seserved.")]
[assembly: AssemblyTrademark("ReoGrid.NET")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("f16dd6fe-47b0-4159-870e-53eaa59f8428")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.0.0.0")]
[assembly: AssemblyFileVersion("2.0.0.0")]
| mit | C# |
875e831b1daa60a6be77417057e16a4274c44031 | Make paths of text files to write verbatim, so that slashes are not misinterpreted under Windows as escape characters | markfinal/BuildAMation,markfinal/BuildAMation,markfinal/BuildAMation,markfinal/BuildAMation,markfinal/BuildAMation | packages/XmlUtilities/dev/Scripts/TextFile/TextToPythonScript.cs | packages/XmlUtilities/dev/Scripts/TextFile/TextToPythonScript.cs | // <copyright file="TextToPythonScript.cs" company="Mark Final">
// Opus package
// </copyright>
// <summary>XmlUtilities package</summary>
// <author>Mark Final</author>
namespace XmlUtilities
{
public static class TextToPythonScript
{
public static void
Write(
System.Text.StringBuilder content,
string pythonScriptPath,
string pathToGeneratedFile)
{
using (var writer = new System.IO.StreamWriter(pythonScriptPath))
{
writer.WriteLine("#!usr/bin/python");
writer.WriteLine(System.String.Format("with open(r'{0}', 'wt') as script:", pathToGeneratedFile));
foreach (var line in content.ToString().Split('\n'))
{
writer.WriteLine("\tscript.write('{0}\\n')", line);
}
}
}
}
}
| // <copyright file="TextToPythonScript.cs" company="Mark Final">
// Opus package
// </copyright>
// <summary>XmlUtilities package</summary>
// <author>Mark Final</author>
namespace XmlUtilities
{
public static class TextToPythonScript
{
public static void
Write(
System.Text.StringBuilder content,
string pythonScriptPath,
string pathToGeneratedFile)
{
using (var writer = new System.IO.StreamWriter(pythonScriptPath))
{
writer.WriteLine("#!usr/bin/python");
writer.WriteLine(System.String.Format("with open('{0}', 'wt') as script:", pathToGeneratedFile));
foreach (var line in content.ToString().Split('\n'))
{
writer.WriteLine("\tscript.write('{0}\\n')", line);
}
}
}
}
}
| bsd-3-clause | C# |
7504d033b3ffbeee76a82fb9a897b7debd563997 | Test commit. | Rossoner40/it-tests,Rossoner40/it-tests,DimitarBakardzhiev/it-tests,DimitarBakardzhiev/it-tests,DimitarBakardzhiev/it-tests,Rossoner40/it-tests | IT-Tests.Data/ITTestsDbContext.cs | IT-Tests.Data/ITTestsDbContext.cs | namespace IT_Tests.Data
{
using System.Data.Entity;
using IT_Tests.Data.Migrations;
using IT_Tests.Models;
using Microsoft.AspNet.Identity.EntityFramework;
public class ITTestsDbContext : IdentityDbContext<User>
{
public ITTestsDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion<ITTestsDbContext, Configuration>());
}
// IDbSet...
public static ITTestsDbContext Create()
{
return new ITTestsDbContext();
}
}
}
| namespace IT_Tests.Data
{
using System.Data.Entity;
using IT_Tests.Data.Migrations;
using IT_Tests.Models;
using Microsoft.AspNet.Identity.EntityFramework;
public class ITTestsDbContext : IdentityDbContext<User>
{
public ITTestsDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion<ITTestsDbContext, Configuration>());
}
public static ITTestsDbContext Create()
{
return new ITTestsDbContext();
}
}
}
| mit | C# |
5b9652f7662f167cdf80cc49e5dbfc029a26e947 | Rename some base action settings | danielchalmers/DesktopWidgets | DesktopWidgets/Actions/ActionBase.cs | DesktopWidgets/Actions/ActionBase.cs | using System;
using System.ComponentModel;
using System.Windows;
using DesktopWidgets.Classes;
using DesktopWidgets.Helpers;
using Xceed.Wpf.Toolkit.PropertyGrid.Attributes;
namespace DesktopWidgets.Actions
{
public abstract class ActionBase
{
[PropertyOrder(0)]
[DisplayName("Delay")]
public TimeSpan Delay { get; set; } = TimeSpan.FromSeconds(0);
[PropertyOrder(1)]
[DisplayName("Trigger If Foreground Is Fullscreen")]
public bool WorksIfForegroundIsFullscreen { get; set; }
[PropertyOrder(2)]
[DisplayName("Trigger If Muted")]
public bool WorksIfMuted { get; set; }
[PropertyOrder(3)]
[DisplayName("Show Error Popups")]
public bool ShowErrors { get; set; } = false;
public void Execute()
{
if (!WorksIfMuted && App.IsMuted ||
(!WorksIfForegroundIsFullscreen && FullScreenHelper.DoesAnyMonitorHaveFullscreenApp()))
{
return;
}
DelayedAction.RunAction((int)Delay.TotalMilliseconds, () =>
{
try
{
ExecuteAction();
}
catch (Exception ex)
{
if (ShowErrors)
{
Popup.ShowAsync($"{GetType().Name} failed to execute.\n\n{ex.Message}",
image: MessageBoxImage.Error);
}
}
});
}
protected virtual void ExecuteAction()
{
}
}
} | using System;
using System.ComponentModel;
using System.Windows;
using DesktopWidgets.Classes;
using DesktopWidgets.Helpers;
using Xceed.Wpf.Toolkit.PropertyGrid.Attributes;
namespace DesktopWidgets.Actions
{
public abstract class ActionBase
{
[PropertyOrder(0)]
[DisplayName("Delay")]
public TimeSpan Delay { get; set; } = TimeSpan.FromSeconds(0);
[PropertyOrder(1)]
[DisplayName("Works If Foreground Is Fullscreen")]
public bool WorksIfForegroundIsFullscreen { get; set; }
[PropertyOrder(2)]
[DisplayName("Works If Muted")]
public bool WorksIfMuted { get; set; }
[PropertyOrder(3)]
[DisplayName("Show Errors")]
public bool ShowErrors { get; set; } = false;
public void Execute()
{
if (!WorksIfMuted && App.IsMuted ||
(!WorksIfForegroundIsFullscreen && FullScreenHelper.DoesAnyMonitorHaveFullscreenApp()))
{
return;
}
DelayedAction.RunAction((int)Delay.TotalMilliseconds, () =>
{
try
{
ExecuteAction();
}
catch (Exception ex)
{
if (ShowErrors)
{
Popup.ShowAsync($"{GetType().Name} failed to execute.\n\n{ex.Message}",
image: MessageBoxImage.Error);
}
}
});
}
protected virtual void ExecuteAction()
{
}
}
} | apache-2.0 | C# |
2264d9a98b87bb914410757bc0007739c7e8de7b | Update to test | AlexisArce/MvcRouteTester,AnthonySteele/MvcRouteTester | src/MvcRouteTester.Test/ApiRoute/DuplicateNameTests.cs | src/MvcRouteTester.Test/ApiRoute/DuplicateNameTests.cs | using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Routing;
using MvcRouteTester.Test.Assertions;
using NUnit.Framework;
namespace MvcRouteTester.Test.ApiRoute
{
public class Item
{
public int Id { get; set; }
}
public class ItemController : ApiController
{
[HttpPost]
public void CreateItem(string id, [FromBody] Item item)
{
}
}
[TestFixture]
public class DuplicateNameTests
{
private HttpConfiguration config;
[SetUp]
public void MakeRouteTable()
{
RouteAssert.UseAssertEngine(new NunitAssertEngine());
config = new HttpConfiguration();
config.Routes.MapHttpRoute("Create Item", "items/{id}",
new { controller = "Item", action = "CreateItem" },
new { httpMethod = new HttpMethodConstraint(HttpMethod.Post) });
}
[Test]
public void TestCreateMap()
{
var item = new Item { Id = 42 };
config
.ShouldMap(string.Format("http://localhost/items/aid"))
.WithBody("id=42")
.To<ItemController>(HttpMethod.Post, x => x.CreateItem("aid", item));
}
}
}
| using System.Net.Http;
using System.Web;
using System.Web.Helpers;
using System.Web.Http;
using System.Web.Http.Routing;
using MvcRouteTester.Test.Assertions;
using NUnit.Framework;
namespace MvcRouteTester.Test.ApiRoute
{
public class Item
{
public int Id { get; set; }
}
public class ItemController : ApiController
{
[HttpPost]
public void CreateItem(string id, [FromBody] Item item)
{
}
}
[TestFixture]
public class DuplicateNameTests
{
private HttpConfiguration config;
[SetUp]
public void MakeRouteTable()
{
RouteAssert.UseAssertEngine(new NunitAssertEngine());
config = new HttpConfiguration();
config.Routes.MapHttpRoute("Create Item", "items/{id}",
new { controller = "Item", action = "CreateItem" },
new { httpMethod = new HttpMethodConstraint(HttpMethod.Post) });
}
[Test]
[Ignore("has duplicate route param 'id', not working yet")]
public void TestCreateMap()
{
var item = new Item { Id = 42 };
config
.ShouldMap(string.Format("http://localhost/items/aid"))
.WithBody(HttpUtility.UrlEncode(Json.Encode(item)))
.To<ItemController>(HttpMethod.Post, x => x.CreateItem("aid", item));
}
}
}
| apache-2.0 | C# |
640e1be8fe60d066c2f41f04917d9a1c1cf54574 | fix request parameter missing | kaedei/aliyun-ddns-client-csharp | Kaedei.AliyunDDNSClient/Program.cs | Kaedei.AliyunDDNSClient/Program.cs | using System;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading;
using Aliyun.Api;
using Aliyun.Api.DNS.DNS20150109.Request;
using Newtonsoft.Json;
namespace Kaedei.AliyunDDNSClient
{
class Program
{
private static void Main(string[] args)
{
try
{
var configs = File.ReadAllLines("config.txt");
var accessKeyId = configs[0].Trim(); //Access Key ID,如 DR2DPjKmg4ww0e79
var accessKeySecret = configs[1].Trim(); //Access Key Secret,如 ysHnd1dhWvoOmbdWKx04evlVEdXEW7
var domainName = configs[2].Trim(); //域名,如 google.com
var rr = configs[3].Trim(); //子域名,如 www
Console.WriteLine("Updating {0} of domain {1}", rr, domainName);
var aliyunClient = new DefaultAliyunClient("http://dns.aliyuncs.com/", accessKeyId, accessKeySecret);
var req = new DescribeDomainRecordsRequest() { DomainName = domainName };
var response = aliyunClient.Execute(req);
var updateRecord = response.DomainRecords.FirstOrDefault(rec => rec.RR == rr && rec.Type == "A");
if (updateRecord == null)
return;
Console.WriteLine("Domain record IP is " + updateRecord.Value);
//获取IP
var ipJson = new HttpClient().GetStringAsync("http://ip-api.com/json").Result;
var ip = JsonConvert.DeserializeObject<IpApiResponse>(ipJson).query;
Console.WriteLine("Current IP is " + ip);
if (updateRecord.Value != ip)
{
var changeValueRequest = new UpdateDomainRecordRequest()
{
RecordId = updateRecord.RecordId,
Value = ip,
Type = "A",
RR = rr
};
aliyunClient.Execute(changeValueRequest);
Console.WriteLine("Update finished.");
}
else
{
Console.WriteLine("IPs are same now. Exiting");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Thread.Sleep(5000);
}
}
} | using System;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading;
using Aliyun.Api;
using Aliyun.Api.DNS.DNS20150109.Request;
using Newtonsoft.Json;
namespace Kaedei.AliyunDDNSClient
{
class Program
{
private static void Main(string[] args)
{
try
{
var configs = File.ReadAllLines("config.txt");
var accessKeyId = configs[0].Trim(); //Access Key ID,如 DR2DPjKmg4ww0e79
var accessKeySecret = configs[1].Trim(); //Access Key Secret,如 ysHnd1dhWvoOmbdWKx04evlVEdXEW7
var domainName = configs[2].Trim(); //域名,如 google.com
var rr = configs[3].Trim(); //子域名,如 www
Console.WriteLine("Updating {0} of domain {1}", rr, domainName);
var aliyunClient = new DefaultAliyunClient("http://dns.aliyuncs.com/", accessKeyId, accessKeySecret);
var req = new DescribeDomainRecordsRequest() { DomainName = domainName };
var response = aliyunClient.Execute(req);
var updateRecord = response.DomainRecords.FirstOrDefault(rec => rec.RR == rr && rec.Type == "A");
if (updateRecord == null)
return;
Console.WriteLine("Domain record IP is " + updateRecord.Value);
//获取IP
var ipJson = new HttpClient().GetStringAsync("http://ip-api.com/json").Result;
var ip = JsonConvert.DeserializeObject<IpApiResponse>(ipJson).query;
Console.WriteLine("Current IP is " + ip);
if (updateRecord.Value != ip)
{
var changeValueRequest = new UpdateDomainRecordRequest()
{
RecordId = updateRecord.RecordId,
Value = ip
};
aliyunClient.Execute(changeValueRequest);
Console.WriteLine("Update finished.");
}
else
{
Console.WriteLine("IPs are same now. Exiting");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Thread.Sleep(5000);
}
}
} | apache-2.0 | C# |
9bb175751b0b0777cda246fd7a2e2ec7dcabcfe3 | make public | mlittle/avaya-moagent-client | AvayaMoagentClient/Commands/AvailableWork.cs | AvayaMoagentClient/Commands/AvailableWork.cs | using System;
namespace AvayaMoagentClient.Commands
{
public class AvailableWork : Message
{
private const string COMMAND = "AGTAvailWork";
public AvailableWork()
: this(false)
{ }
public AvailableWork(bool cacheRawMessage)
: base(COMMAND, Message.MessageType.Command, cacheRawMessage)
{ }
}
}
| using System;
namespace AvayaMoagentClient.Commands
{
class AvailableWork : Message
{
private const string COMMAND = "AGTAvailWork";
public AvailableWork()
: this(false)
{ }
public AvailableWork(bool cacheRawMessage)
: base(COMMAND, Message.MessageType.Command, cacheRawMessage)
{ }
}
}
| bsd-2-clause | C# |
d7b9fd480765bdc01f06441f308fb288e6001049 | Update TFM to include netcoreapp3.0 | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | src/Microsoft.AspNetCore.Server.IntegrationTesting/Common/Tfm.cs | src/Microsoft.AspNetCore.Server.IntegrationTesting/Common/Tfm.cs | // 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;
namespace Microsoft.AspNetCore.Server.IntegrationTesting
{
public static class Tfm
{
public const string Net461 = "net461";
public const string NetCoreApp20 = "netcoreapp2.0";
public const string NetCoreApp21 = "netcoreapp2.1";
public const string NetCoreApp22 = "netcoreapp2.2";
public const string NetCoreApp30 = "netcoreapp3.0";
public static bool Matches(string tfm1, string tfm2)
{
return string.Equals(tfm1, tfm2, StringComparison.OrdinalIgnoreCase);
}
}
}
| // 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;
namespace Microsoft.AspNetCore.Server.IntegrationTesting
{
public static class Tfm
{
public const string Net461 = "net461";
public const string NetCoreApp20 = "netcoreapp2.0";
public const string NetCoreApp21 = "netcoreapp2.1";
public const string NetCoreApp22 = "netcoreapp2.2";
public static bool Matches(string tfm1, string tfm2)
{
return string.Equals(tfm1, tfm2, StringComparison.OrdinalIgnoreCase);
}
}
}
| apache-2.0 | C# |
7d0285cc54444c67e496103d3043df1c84afb01d | Fix for Get all tasks | justinSelf/cqrsworkshop,justinSelf/cqrsworkshop,justinSelf/cqrsworkshop | src/TeamTasker.Web/TeamTasker.Web/Controllers/TasksController.cs | src/TeamTasker.Web/TeamTasker.Web/Controllers/TasksController.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TeamTasker.Web.Domain;
namespace TeamTasker.Web.Controllers
{
public class TasksController : Controller
{
private TaskerContext db = new TaskerContext();
[HttpPost]
public JsonResult Create(string name, DateTime dueDate, string instructions)
{
var task = new Task
{
Name = name,
DueDate = dueDate,
Instructions = instructions
};
db.Tasks.Add(task);
db.SaveChanges();
return Json(task.Id);
}
[HttpPost]
public JsonResult Assign(int taskId, int memberId)
{
var task = db.Tasks.Where(t => t.Id == taskId).Single();
var member = db.TeamMembers.Where(m => m.Id == memberId).Single();
task.AssignedMembers.Add(member);
db.SaveChanges();
return Json("success");
}
[HttpGet]
public JsonResult AllTasks()
{
var tasks = (from t in db.Tasks select new { Id = t.Id, Name = t.Name }).OrderBy(t => t.Name).ToList();
return Json(tasks, JsonRequestBehavior.AllowGet);
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TeamTasker.Web.Domain;
namespace TeamTasker.Web.Controllers
{
public class TasksController : Controller
{
private TaskerContext db = new TaskerContext();
[HttpPost]
public JsonResult Create(string name, DateTime dueDate, string instructions)
{
var task = new Task
{
Name = name,
DueDate = dueDate,
Instructions = instructions
};
db.Tasks.Add(task);
db.SaveChanges();
return Json(task.Id);
}
[HttpPost]
public JsonResult Assign(int taskId, int memberId)
{
var task = db.Tasks.Where(t => t.Id == taskId).Single();
var member = db.TeamMembers.Where(m => m.Id == memberId).Single();
task.AssignedMembers.Add(member);
db.SaveChanges();
return Json("success");
}
[HttpGet]
public JsonResult AllTasks()
{
var tasks = (from t in db.Tasks select new { Id = t.Id, Name = t.Name }).OrderBy(t => t.Name).ToList();
return Json(tasks);
}
}
} | mit | C# |
ccd7c71819a225f11b5bde7ecb016ad958deef8f | update for deploy | tolu/tobiaslundin.se | source/Views/Home/Index.cshtml | source/Views/Home/Index.cshtml | @{
ViewBag.Title = "Tobias Lundin";
}
<div class="jumbotron">
<h1>Welcome!</h1>
<p class="lead">To my internet lair of ... me x 3.</p>
</div>
<div class="row">
<div class="col-md-4">
<h2>A Binary Home</h2>
<p>
This location has been in the works but never really working since dawn of apes but at least now it's a shiny solution built with ASP.NET vNext.
</p>
<p>
I try to fill this space with fun playgrounds, contact information and a portfolio. Hopefully a blog will take shape some day whe I really figure out what to write about :)
</p>
</div>
</div> | @{
ViewBag.Title = "Tobias Lundin";
}
<div class="jumbotron">
<h1>Welcome!</h1>
<p class="lead">To my internet lair of ... me me me.</p>
</div>
<div class="row">
<div class="col-md-4">
<h2>A Binary Home</h2>
<p>
This location has been in the works but never really working since dawn of apes but at least now it's a shiny solution built with ASP.NET vNext.
</p>
<p>
I try to fill this space with fun playgrounds, contact information and a portfolio. Hopefully a blog will take shape some day whe I really figure out what to write about :)
</p>
</div>
</div> | mit | C# |
7bbaf726e73d1b8159be833aed2a6a7e12a9149e | Add ArrayIndexResolution_CorrectSetup_Success test | Domysee/Pather.CSharp | test/Pather.CSharp.UnitTests/ResolverTests.cs | test/Pather.CSharp.UnitTests/ResolverTests.cs | using FluentAssertions;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
namespace Pather.CSharp.UnitTests
{
public class ResolverTests
{
public ResolverTests()
{
}
[Fact]
public void SinglePropertyResolution_CorrectSetup_Success()
{
var value = "1";
var r = new Resolver();
var o = new { Property = value };
var path = "Property";
var result = r.Resolve(o, path);
result.Should().Be(value);
}
[Fact]
public void MultiplePropertyResolution_CorrectSetup_Success()
{
var value = "1";
var r = new Resolver();
var o = new { Property1 = new { Property2 = value } };
var path = "Property1.Property2";
var result = r.Resolve(o, path);
result.Should().Be(value);
}
[Fact]
public void ArrayIndexResolution_CorrectSetup_Success()
{
System.Diagnostics.Debugger.Launch();
var r = new Resolver();
var array = new[] { "1", "2" };
var o = new { Array = array };
var path = "Array[0]";
var result = r.Resolve(o, path);
result.Should().Be("1");
}
[Fact]
public void SinglePropertyResolution_NoPathElementTypeForPath_FailWithNoApplicablePathElementType()
{
var value = "1";
var r = new Resolver();
var o = new { Property = value };
var path = "Property^%#";
r.Invoking(re => re.Resolve(o, path)).ShouldThrow<InvalidOperationException>();
}
}
}
| using FluentAssertions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
namespace Pather.CSharp.UnitTests
{
public class ResolverTests
{
public ResolverTests()
{
}
[Fact]
public void SinglePropertyResolution_CorrectSetup_Success()
{
var value = "1";
var r = new Resolver();
var o = new { Property = value };
var path = "Property";
var result = r.Resolve(o, path);
result.Should().Be(value);
}
[Fact]
public void MultiplePropertyResolution_CorrectSetup_Success()
{
var value = "1";
var r = new Resolver();
var o = new { Property1 = new { Property2 = value } };
var path = "Property1.Property2";
var result = r.Resolve(o, path);
result.Should().Be(value);
}
[Fact]
public void SinglePropertyResolution_NoPathElementTypeForPath_FailWithNoApplicablePathElementType()
{
var value = "1";
var r = new Resolver();
var o = new { Property = value };
var path = "Property^%#";
r.Invoking(re => re.Resolve(o, path)).ShouldThrow<InvalidOperationException>();
}
}
}
| mit | C# |
a7882868f956be1720fdfcf5dd9cc93428709c8a | Fix single tap recognition | NView/NView.Controls,NView/NView.Controls | NView.Controls.iOS/Controls/Map.cs | NView.Controls.iOS/Controls/Map.cs | using System;
using UIKit;
using Foundation;
using MapKit;
using CoreLocation;
namespace NView.Controls
{
public class Map : IView
{
MKMapView map;
UIGestureRecognizer singleTap;
UIGestureRecognizer doubleTap;
MapCoordinate setRegionCoord;
double setRegionDistance = 100000;
public event EventHandler<MapTappedEventArgs> Tapped = delegate {};
public Map ()
{
}
CLLocationCoordinate2D GetCoord (MapCoordinate c)
{
return new CLLocationCoordinate2D (c.Latitude, c.Longitude);
}
public void SetCenterCoordinate (MapCoordinate centerCoord, bool animated = false)
{
setRegionCoord = centerCoord;
if (map == null)
return;
map.SetCenterCoordinate (GetCoord (centerCoord), animated);
}
public void SetRegion (MapCoordinate centerCoord, double visibleMeters, bool animated = false)
{
setRegionCoord = centerCoord;
setRegionDistance = visibleMeters;
if (map == null)
return;
map.SetRegion (MKCoordinateRegion.FromDistance (GetCoord (centerCoord), visibleMeters, visibleMeters), animated);
}
#region IView implementation
void HandleTap (UITapGestureRecognizer g)
{
if (map == null)
return;
if (g.State != UIGestureRecognizerState.Recognized)
return;
var c = map.ConvertPoint (g.LocationInView (map), map);
Tapped (this, new MapTappedEventArgs { Coordinate = new MapCoordinate (c.Latitude, c.Longitude) });
}
public object CreateNative (object context = null)
{
return new MKMapView {
ZoomEnabled = true,
PitchEnabled = true,
RotateEnabled = true,
};
}
public void BindToNative (object native, BindOptions options = BindOptions.None)
{
UnbindFromNative ();
map = ViewHelpers.GetView<MKMapView> (native);
singleTap = new UITapGestureRecognizer (HandleTap) {
NumberOfTapsRequired = 1,
};
map.AddGestureRecognizer (singleTap);
doubleTap = new UITapGestureRecognizer {
NumberOfTapsRequired = 2,
};
map.AddGestureRecognizer (doubleTap);
singleTap.RequireGestureRecognizerToFail (doubleTap);
map.SetRegion (MKCoordinateRegion.FromDistance (
GetCoord (setRegionCoord), setRegionDistance, setRegionDistance),
false);
}
public void UnbindFromNative ()
{
if (map != null) {
if (singleTap != null)
map.RemoveGestureRecognizer (singleTap);
if (doubleTap != null)
map.RemoveGestureRecognizer (doubleTap);
}
singleTap = null;
doubleTap = null;
map = null;
}
#endregion
}
}
| using System;
using UIKit;
using Foundation;
using MapKit;
using CoreLocation;
namespace NView.Controls
{
public class Map : IView
{
MKMapView map;
UIGestureRecognizer tap;
MapCoordinate setRegionCoord;
double setRegionDistance = 100000;
public event EventHandler<MapTappedEventArgs> Tapped = delegate {};
public Map ()
{
}
CLLocationCoordinate2D GetCoord (MapCoordinate c)
{
return new CLLocationCoordinate2D (c.Latitude, c.Longitude);
}
public void SetCenterCoordinate (MapCoordinate centerCoord, bool animated = false)
{
setRegionCoord = centerCoord;
if (map == null)
return;
map.SetCenterCoordinate (GetCoord (centerCoord), animated);
}
public void SetRegion (MapCoordinate centerCoord, double visibleMeters, bool animated = false)
{
setRegionCoord = centerCoord;
setRegionDistance = visibleMeters;
if (map == null)
return;
map.SetRegion (MKCoordinateRegion.FromDistance (GetCoord (centerCoord), visibleMeters, visibleMeters), animated);
}
#region IView implementation
void HandleTap (UITapGestureRecognizer g)
{
if (map == null)
return;
var c = map.ConvertPoint (g.LocationInView (map), map);
Tapped (this, new MapTappedEventArgs { Coordinate = new MapCoordinate (c.Latitude, c.Longitude) });
}
public object CreateNative (object context = null)
{
return new MKMapView {
ZoomEnabled = true,
PitchEnabled = true,
RotateEnabled = true,
};
}
public void BindToNative (object native, BindOptions options = BindOptions.None)
{
UnbindFromNative ();
map = ViewHelpers.GetView<MKMapView> (native);
tap = new UITapGestureRecognizer (HandleTap);
map.AddGestureRecognizer (tap);
map.SetRegion (MKCoordinateRegion.FromDistance (
GetCoord (setRegionCoord), setRegionDistance, setRegionDistance),
false);
}
public void UnbindFromNative ()
{
if (map != null && tap != null) {
map.RemoveGestureRecognizer (tap);
}
tap = null;
map = null;
}
#endregion
}
}
| mit | C# |
4097a7e9c81ac9084769212b7b0011edba4dd3b2 | Bump dev version to v0.13 | hifi/monodevelop-justenoughvi | JustEnoughVi/Properties/AddinInfo.cs | JustEnoughVi/Properties/AddinInfo.cs | using Mono.Addins;
using Mono.Addins.Description;
[assembly: Addin(
"JustEnoughVi",
Namespace = "JustEnoughVi",
Version = "0.13"
)]
[assembly: AddinName("Just Enough Vi")]
[assembly: AddinCategory("IDE extensions")]
[assembly: AddinDescription("Simplified Vi/Vim mode for MonoDevelop/Xamarin Studio.")]
[assembly: AddinAuthor("Toni Spets")]
| using Mono.Addins;
using Mono.Addins.Description;
[assembly: Addin(
"JustEnoughVi",
Namespace = "JustEnoughVi",
Version = "0.12"
)]
[assembly: AddinName("Just Enough Vi")]
[assembly: AddinCategory("IDE extensions")]
[assembly: AddinDescription("Simplified Vi/Vim mode for MonoDevelop/Xamarin Studio.")]
[assembly: AddinAuthor("Toni Spets")]
| mit | C# |
b943449c782c982b92853506167460d7cc1bc559 | Add inlinde docs for the PushNpgsqlDB command. | jacksonh/MCloud,jacksonh/MCloud | MCloud/MCloud.Deploy/PushNpgsqlDB.cs | MCloud/MCloud.Deploy/PushNpgsqlDB.cs |
using System;
using System.IO;
using System.Diagnostics;
using ICSharpCode.SharpZipLib;
using ICSharpCode.SharpZipLib.GZip;
namespace MCloud.Deploy
{
/// <summary>
/// Push a local database to the node. If the remote node already has
/// a database with the same name it will be destroyed and all of its
/// data will be lost.
/// This will push the schema and all data, it will not push any privilege
/// information.
/// The remote server must already have postgresql installed and running.
/// </summary>
public class PushNpgsqlDB : SSHDeployment
{
private string database;
private string dump_file;
/// <summary>
/// Create a PushNpgsqlDB deployment command with the specified database name.
/// </summary>
/// <param name="db_name">
/// A <see cref="System.String"/>
/// The name of the database to pull from and push to.
/// </param>
public PushNpgsqlDB (string db_name)
{
Database = db_name;
}
/// <summary>
/// The name of the database to pull data from.
/// </summary>
public string Database {
get { return database; }
set {
if (database != value)
SetDumpFile (null);
database = value;
}
}
protected override void RunImpl (Node node, NodeAuth auth)
{
string host = node.PublicIPs [0].ToString ();
string file = GetDumpFile ();
PutFile (host, auth, file, "/root/dump.sql.gz");
RunCommand ("gunzip -d -f /root/dump.sql.gz", host, auth);
RunCommand ("mv /root/dump.sql ~postgres/.", host, auth);
RunCommand ("sudo -u postgres psql -f ~postgres/dump.sql", host, auth);
}
private string GetDumpFile ()
{
if (dump_file != null)
return dump_file;
string file = Path.GetTempFileName ();
Process p = new Process ();
// how the hell do i find this on windows?
p.StartInfo.FileName = "pg_dump";
p.StartInfo.Arguments = String.Format ("-f {0} -x {1}", file, Database);
p.StartInfo.UseShellExecute = true;
p.Start ();
p.WaitForExit ();
string zip = Path.GetTempFileName () + ".sql.gz";
FileStream s = File.OpenWrite (zip);
FileStream dump_stream = File.OpenRead (file);
GZipOutputStream zstream = new GZipOutputStream (s);
int size;
byte [] buffer = new byte [1000];
do {
size = dump_stream.Read (buffer, 0, buffer.Length);
zstream.Write (buffer, 0, size);
} while (size > 0);
zstream.Close();
dump_stream.Close();
dump_file = zip;
return zip;
}
private void SetDumpFile (string file)
{
if (file == null && dump_file != null)
File.Delete (dump_file);
dump_file = file;
}
}
}
|
using System;
using System.IO;
using System.Diagnostics;
using ICSharpCode.SharpZipLib;
using ICSharpCode.SharpZipLib.GZip;
namespace MCloud.Deploy
{
public class PushNpgsqlDB : SSHDeployment
{
private string database;
private string dump_file;
public PushNpgsqlDB (string db_name)
{
Database = db_name;
}
public string Database {
get { return database; }
set {
if (database != value)
SetDumpFile (null);
database = value;
}
}
protected override void RunImpl (Node node, NodeAuth auth)
{
string host = node.PublicIPs [0].ToString ();
string file = GetDumpFile ();
PutFile (host, auth, file, "/root/dump.sql.gz");
RunCommand ("gunzip -d -f /root/dump.sql.gz", host, auth);
RunCommand ("mv /root/dump.sql ~postgres/.", host, auth);
RunCommand ("sudo -u postgres psql -f ~postgres/dump.sql", host, auth);
}
private string GetDumpFile ()
{
if (dump_file != null)
return dump_file;
string file = Path.GetTempFileName ();
Process p = new Process ();
// how the hell do i find this on windows?
p.StartInfo.FileName = "pg_dump";
p.StartInfo.Arguments = String.Format ("-f {0} -x {1}", file, Database);
p.StartInfo.UseShellExecute = true;
p.Start ();
p.WaitForExit ();
string zip = Path.GetTempFileName () + ".sql.gz";
FileStream s = File.OpenWrite (zip);
FileStream dump_stream = File.OpenRead (file);
GZipOutputStream zstream = new GZipOutputStream (s);
int size;
byte [] buffer = new byte [1000];
do {
size = dump_stream.Read (buffer, 0, buffer.Length);
zstream.Write (buffer, 0, size);
} while (size > 0);
zstream.Close();
dump_stream.Close();
dump_file = zip;
return zip;
}
private void SetDumpFile (string file)
{
if (file == null && dump_file != null)
File.Delete (dump_file);
dump_file = file;
}
}
}
| mit | C# |
10ad4bdb7bc67913507a5d2c4269ee915194b4e0 | Make text work better on Nexus One. | bklimt/LandTheEagleUnity | Assets/Gui.cs | Assets/Gui.cs | using UnityEngine;
using System.Collections;
public class Gui : MonoBehaviour {
public GUISkin defaultSkin;
public GUISkin stateSkin;
private bool started = false;
private bool startingToShowButtons = false;
private bool showButtons = false;
void Start() {
}
void Update() {
if (Input.GetMouseButtonDown(0)) {
started = true;
}
}
private IEnumerator ShowButtons() {
yield return new WaitForSeconds(1.5f);
showButtons = true;
}
private void DrawStatus() {
GUI.skin = stateSkin;
GameState state = GameState.Instance;
if (state.IsHighDpi()) {
GUI.skin.label.fontSize = 48;
}
float x = Screen.width * 0.1f;
float y = Screen.height * 0.05f;
float width = Screen.width - 2.0f * x;
float height = Screen.height * 0.15f;
string statusText =
"Level: " + (state.Level + 1) + "\n" +
((state.Speed >= 3)
? ("<color=#ff0000>Speed: " + state.Speed + "</color>\n")
: ("Speed: " + state.Speed + "\n")) +
"Fuel: " + state.Fuel;
GUI.Label(new Rect(x, y, width, height), statusText);
}
void OnGUI() {
GameState state = GameState.Instance;
if (started) {
DrawStatus();
}
GUI.skin = defaultSkin;
if (state.IsHighDpi()) {
GUI.skin.label.fontSize = 72;
GUI.skin.button.fontSize = 48;
}
if (!started) {
GUI.Label(new Rect(0, 0, Screen.width, Screen.height),
"Tap to thrust.\nLand where flat.\nNot too fast.");
}
Rect button1Rect = GameState.GetGUIButtonRect(0);
Rect button2Rect = GameState.GetGUIButtonRect(1);
if (!state.Grounded) {
return;
}
if (!startingToShowButtons) {
startingToShowButtons = true;
StartCoroutine(ShowButtons());
}
if (state.Crashed) {
GUI.Label(new Rect(0, 0, Screen.width, Screen.height), "You crashed.");
if (showButtons) {
if (GUI.Button(button1Rect, "Retry")) {
state.RestartLevel();
}
if (GUI.Button(button2Rect, "Give Up")) {
state.GiveUp();
}
}
} else {
GUI.Label(new Rect(0, 0, Screen.width, Screen.height), "You landed!");
if (showButtons) {
if (GUI.Button(button1Rect, "Next Level")) {
state.LoadNextLevel();
}
if (GUI.Button(button2Rect, "Give Up")) {
state.Quit();
}
}
}
}
}
| using UnityEngine;
using System.Collections;
public class Gui : MonoBehaviour {
public GUISkin defaultSkin;
public GUISkin stateSkin;
private bool started = false;
private bool startingToShowButtons = false;
private bool showButtons = false;
void Start() {
}
void Update() {
if (Input.GetMouseButtonDown(0)) {
started = true;
}
}
private IEnumerator ShowButtons() {
yield return new WaitForSeconds(1.5f);
showButtons = true;
}
private void DrawStatus() {
GUI.skin = stateSkin;
GameState state = GameState.Instance;
if (state.IsHighDpi()) {
GUI.skin.label.fontSize = 48;
}
float x = Screen.width * 0.1f;
float y = Screen.height * 0.05f;
float width = Screen.width - 2.0f * x;
float height = Screen.height * 0.05f;
GUI.Label(new Rect(x, y, width, height), "Level: " + (state.Level + 1));
if (state.Speed >= 3) {
GUI.Label(new Rect(x, y + height, width, height),
"<color=#ff0000>Speed: " + state.Speed + "</color>");
} else {
GUI.Label(new Rect(x, y + height, width, height), "Speed: " + state.Speed);
}
GUI.Label(new Rect(x, y + 2 * height, width, height), "Fuel: " + state.Fuel);
}
void OnGUI() {
GameState state = GameState.Instance;
DrawStatus();
GUI.skin = defaultSkin;
if (state.IsHighDpi()) {
GUI.skin.label.fontSize = 72;
GUI.skin.button.fontSize = 48;
}
if (!started) {
GUI.Label(new Rect(0, 0, Screen.width, Screen.height),
"Tap to thrust.\nLand where flat.\nNot too fast.");
}
Rect button1Rect = GameState.GetGUIButtonRect(0);
Rect button2Rect = GameState.GetGUIButtonRect(1);
if (!state.Grounded) {
return;
}
if (!startingToShowButtons) {
startingToShowButtons = true;
StartCoroutine(ShowButtons());
}
if (state.Crashed) {
GUI.Label(new Rect(0, 0, Screen.width, Screen.height), "You crashed.");
if (showButtons) {
if (GUI.Button(button1Rect, "Retry")) {
state.RestartLevel();
}
if (GUI.Button(button2Rect, "Give Up")) {
state.GiveUp();
}
}
} else {
GUI.Label(new Rect(0, 0, Screen.width, Screen.height), "You landed!");
if (showButtons) {
if (GUI.Button(button1Rect, "Next Level")) {
state.LoadNextLevel();
}
if (GUI.Button(button2Rect, "Give Up")) {
state.Quit();
}
}
}
}
}
| mit | C# |
54ea8f905f5fe618275d318b763368e9e6a87c54 | Put explicit blit in its own Execute func, added inspector button | SoylentGraham/PopUnityCommon | ShaderBlit.cs | ShaderBlit.cs | using UnityEngine;
using System.Collections;
[ExecuteInEditMode]
public class ShaderBlit : MonoBehaviour {
[InspectorButton("Execute")]
public bool Dirty = true;
public bool AlwaysDirtyInEditor = true;
public Texture Input;
public Shader BlitShader;
public Material BlitMaterial;
public RenderTexture Output;
public UnityEngine.Events.UnityEvent OnClean;
public void SetDirty()
{
Dirty = true;
}
public void Execute()
{
if (BlitShader != null)
{
if ( BlitMaterial == null )
BlitMaterial = new Material( BlitShader );
}
if ( BlitMaterial == null )
return;
Graphics.Blit( Input, Output, BlitMaterial );
}
void Update ()
{
if ( Application.isEditor && !Application.isPlaying && AlwaysDirtyInEditor )
Dirty = true;
if ( !Dirty )
return;
if ( Input == null )
return;
Execute();
Dirty = false;
if ( OnClean != null )
OnClean.Invoke();
}
}
| using UnityEngine;
using System.Collections;
[ExecuteInEditMode]
public class ShaderBlit : MonoBehaviour {
public bool Dirty = true;
public bool AlwaysDirtyInEditor = true;
public Texture Input;
public Shader BlitShader;
public Material BlitMaterial;
public RenderTexture Output;
public UnityEngine.Events.UnityEvent OnClean;
public void SetDirty()
{
Dirty = true;
}
void Update ()
{
if ( Application.isEditor && !Application.isPlaying && AlwaysDirtyInEditor )
Dirty = true;
if ( !Dirty )
return;
if ( Input == null )
return;
if (BlitShader != null)
{
if ( BlitMaterial == null )
BlitMaterial = new Material( BlitShader );
}
if ( BlitMaterial == null )
return;
Graphics.Blit( Input, Output, BlitMaterial );
Dirty = false;
if ( OnClean != null )
OnClean.Invoke();
}
}
| mit | C# |
44d4d6f7b6e0f2c12680d5b1fb15422ef3163896 | Update AG_Program.cs | sooperdex/code-dojo,sooperdex/code-dojo,sooperdex/code-dojo | kata/anagrams/csharp/AG_Program.cs | kata/anagrams/csharp/AG_Program.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace Anagrams
{
class Program
{
static void Main()
{
Console.WriteLine("Please Enter a String: ");
string input = Console.ReadLine();
AnagramProcessor anagramBuilder = new AnagramProcessor();
IEnumerable<string> results = anagramBuilder.GenerateAnagram(input);
OutputList(results);
}
static void OutputList(IEnumerable<string> list)
{
foreach (string item in list)
{
Console.WriteLine(item);
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Anagrams
{
class Program
{
static void Main(string[] args)
{
string input;
AnagramProcessor anagram = new AnagramProcessor();
Console.WriteLine("Enter String: ");
input = Console.ReadLine();
anagram.ProcessString(input);
}
}
}
| mit | C# |
685fec07612204011054fc4bd3a4c341e4cc9fb2 | test if the sockets are released properly when the failure policy overrides the pool's decision. | couchbase/EnyimMemcached,DukeCheng/EnyimMemcachedCore,enyim/EnyimMemcached,cnblogs/EnyimMemcachedCore,oceanho/EnyimMemcached,haizhixing126/EnyimMemcached,DukeCheng/EnyimMemcachedCore,cnblogs/EnyimMemcachedCore,haizhixing126/EnyimMemcached,oceanho/EnyimMemcached | MemcachedTest/FailurePolicyTest.cs | MemcachedTest/FailurePolicyTest.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using Enyim.Caching.Memcached;
using Enyim.Caching.Configuration;
using Enyim.Caching;
using System.Threading;
namespace MemcachedTest
{
[TestFixture]
public class FailurePolicyTest
{
[TestFixtureSetUp]
public void Setup()
{
log4net.Config.XmlConfigurator.Configure();
}
[TestCase]
public void TestIfCalled()
{
var config = new MemcachedClientConfiguration();
config.AddServer("nonexisting.enyim.com:2244");
config.SocketPool.FailurePolicyFactory = new FakePolicy();
config.SocketPool.ConnectionTimeout = TimeSpan.FromSeconds(4);
config.SocketPool.ReceiveTimeout = TimeSpan.FromSeconds(6);
var client = new MemcachedClient(config);
Assert.IsNull(client.Get("a"), "Get should have failed.");
}
class FakePolicy : INodeFailurePolicy, INodeFailurePolicyFactory
{
bool INodeFailurePolicy.ShouldFail()
{
Assert.IsTrue(true);
return true;
}
INodeFailurePolicy INodeFailurePolicyFactory.Create(IMemcachedNode node)
{
return new FakePolicy();
}
}
[TestCase]
public void TestThrottlingFailurePolicy()
{
var config = new MemcachedClientConfiguration();
config.AddServer("nonexisting.enyim.com:2244");
config.SocketPool.FailurePolicyFactory = new ThrottlingFailurePolicyFactory(4, TimeSpan.FromMilliseconds(2000));
config.SocketPool.ConnectionTimeout = TimeSpan.FromMilliseconds(10);
config.SocketPool.ReceiveTimeout = TimeSpan.FromMilliseconds(10);
config.SocketPool.MinPoolSize = 1;
config.SocketPool.MaxPoolSize = 1;
var client = new MemcachedClient(config);
var canFail = false;
var didFail = false;
client.NodeFailed += node =>
{
Assert.IsTrue(canFail, "canfail");
didFail = true;
};
Assert.IsNull(client.Get("a"), "Get should have failed. 1");
Assert.IsNull(client.Get("a"), "Get should have failed. 2");
canFail = true;
Thread.Sleep(2000);
Assert.IsNull(client.Get("a"), "Get should have failed. 3");
Assert.IsNull(client.Get("a"), "Get should have failed. 4");
Assert.IsNull(client.Get("a"), "Get should have failed. 5");
Assert.IsNull(client.Get("a"), "Get should have failed. 6");
Assert.IsTrue(didFail, "didfail");
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using Enyim.Caching.Memcached;
using Enyim.Caching.Configuration;
using Enyim.Caching;
using System.Threading;
namespace MemcachedTest
{
[TestFixture]
public class FailurePolicyTest
{
[TestFixtureSetUp]
public void Setup()
{
log4net.Config.XmlConfigurator.Configure();
}
[TestCase]
public void TestIfCalled()
{
var config = new MemcachedClientConfiguration();
config.AddServer("nonexisting.enyim.com:2244");
config.SocketPool.FailurePolicyFactory = new FakePolicy();
config.SocketPool.ConnectionTimeout = TimeSpan.FromSeconds(4);
config.SocketPool.ReceiveTimeout = TimeSpan.FromSeconds(6);
var client = new MemcachedClient(config);
Assert.IsNull(client.Get("a"), "Get should have failed.");
}
class FakePolicy : INodeFailurePolicy, INodeFailurePolicyFactory
{
bool INodeFailurePolicy.ShouldFail()
{
Assert.IsTrue(true);
return true;
}
INodeFailurePolicy INodeFailurePolicyFactory.Create(IMemcachedNode node)
{
return new FakePolicy();
}
}
[TestCase]
public void TestThrottlingFailurePolicy()
{
var config = new MemcachedClientConfiguration();
config.AddServer("nonexisting.enyim.com:2244");
config.SocketPool.FailurePolicyFactory = new ThrottlingFailurePolicyFactory(4, TimeSpan.FromMilliseconds(2000));
config.SocketPool.ConnectionTimeout = TimeSpan.FromMilliseconds(10);
config.SocketPool.ReceiveTimeout = TimeSpan.FromMilliseconds(10);
var client = new MemcachedClient(config);
var canFail = false;
var didFail = false;
client.NodeFailed += node =>
{
Assert.IsTrue(canFail, "canfail");
didFail = true;
};
Assert.IsNull(client.Get("a"), "Get should have failed. 1");
Assert.IsNull(client.Get("a"), "Get should have failed. 2");
canFail = true;
Thread.Sleep(2000);
Assert.IsNull(client.Get("a"), "Get should have failed. 3");
Assert.IsNull(client.Get("a"), "Get should have failed. 4");
Assert.IsNull(client.Get("a"), "Get should have failed. 5");
Assert.IsNull(client.Get("a"), "Get should have failed. 6");
Assert.IsTrue(didFail, "didfail");
}
}
}
| apache-2.0 | C# |
27e04506925b166339a44be1356dc6aa1be4f7de | Add threading to test server | tmds/Tmds.DBus | TestServer.cs | TestServer.cs | // Copyright 2006 Alp Toker <alp@atoker.com>
// This software is made available under the MIT License
// See COPYING for details
using System;
using NDesk.DBus;
using org.freedesktop.DBus;
using System.IO;
using System.Net;
using System.Net.Sockets;
using Mono.Unix;
using System.Threading;
public class TestServer
{
//TODO: complete this test daemon/server example, and a client
//TODO: maybe generalise it and integrate it into the core
public static void Main (string[] args)
{
bool isServer;
if (args.Length == 1 && args[0] == "server")
isServer = true;
else if (args.Length == 1 && args[0] == "client")
isServer = false;
else {
Console.Error.WriteLine ("Usage: test-server [server|client]");
return;
}
string addr = "unix:abstract=/tmp/dbus-ABCDEFGHIJ";
Connection conn;
ObjectPath myOpath = new ObjectPath ("/test");
string myNameReq = "org.ndesk.test";
if (!isServer) {
conn = new Connection (false);
conn.Open (addr);
DemoObject demo = conn.GetObject<DemoObject> (myNameReq, myOpath);
//float ret = demo.Hello ("hi from test client", 21);
float ret = 200;
while (ret > 5) {
ret = demo.Hello ("hi from test client", (int)ret);
Console.WriteLine ("Returned float: " + ret);
System.Threading.Thread.Sleep (1000);
}
} else {
string path;
bool abstr;
Address.Parse (addr, out path, out abstr);
AbstractUnixEndPoint ep = new AbstractUnixEndPoint (path);
Socket server = new Socket (AddressFamily.Unix, SocketType.Stream, 0);
server.Bind (ep);
//server.Listen (1);
server.Listen (5);
while (true) {
Console.WriteLine ("Waiting for client on " + addr);
Socket client = server.Accept ();
Console.WriteLine ("Client accepted");
//this might well be wrong, untested and doesn't yet work here onwards
conn = new Connection (false);
//conn.Open (path, @abstract);
conn.sock = client;
conn.sock.Blocking = true;
conn.ns = new NetworkStream (conn.sock);
//ConnectionHandler.Handle (conn);
//in reality a thread per connection is of course too expensive
ConnectionHandler hnd = new ConnectionHandler (conn);
new Thread (new ThreadStart (hnd.Handle)).Start ();
Console.WriteLine ();
}
}
}
}
public class ConnectionHandler
{
protected Connection conn;
public ConnectionHandler (Connection conn)
{
this.conn = conn;
}
public void Handle ()
{
ConnectionHandler.Handle (conn);
}
public static void Handle (Connection conn)
{
//Connection.tmpConn = conn;
DemoObject demo = new DemoObject ();
conn.Marshal (demo, "org.ndesk.test");
//TODO: handle lost connections etc. properly instead of stupido try/catch
try {
while (true)
conn.Iterate ();
} catch (Exception e) {
//Console.Error.WriteLine (e);
}
}
}
[Interface ("org.ndesk.test")]
public class DemoObject : MarshalByRefObject
{
public float Hello (string arg0, int arg1)
{
Console.WriteLine ("Got a Hello(" + arg0 + ", " + arg1 +")");
return (float)arg1/2;
}
}
| // Copyright 2006 Alp Toker <alp@atoker.com>
// This software is made available under the MIT License
// See COPYING for details
using System;
using NDesk.DBus;
using org.freedesktop.DBus;
using System.IO;
using System.Net;
using System.Net.Sockets;
using Mono.Unix;
public class TestServer
{
//TODO: complete this test daemon/server example, and a client
//TODO: maybe generalise it and integrate it into the core
public static void Main (string[] args)
{
bool isServer;
if (args.Length == 1 && args[0] == "server")
isServer = true;
else if (args.Length == 1 && args[0] == "client")
isServer = false;
else {
Console.Error.WriteLine ("Usage: test-server [server|client]");
return;
}
string addr = "unix:abstract=/tmp/dbus-ABCDEFGHIJ";
Connection conn;
DemoObject demo;
ObjectPath myOpath = new ObjectPath ("/test");
string myNameReq = "org.ndesk.test";
if (!isServer) {
conn = new Connection (false);
conn.Open (addr);
demo = conn.GetObject<DemoObject> (myNameReq, myOpath);
float ret = demo.Hello ("hi from test client", 21);
Console.WriteLine ("Returned float: " + ret);
} else {
string path;
bool abstr;
Address.Parse (addr, out path, out abstr);
AbstractUnixEndPoint ep = new AbstractUnixEndPoint (path);
Socket server = new Socket (AddressFamily.Unix, SocketType.Stream, 0);
server.Bind (ep);
server.Listen (1);
Console.WriteLine ("Waiting for client on " + addr);
Socket client = server.Accept ();
Console.WriteLine ("Client accepted");
//this might well be wrong, untested and doesn't yet work here onwards
conn = new Connection (false);
//conn.Open (path, @abstract);
conn.sock = client;
conn.sock.Blocking = true;
conn.ns = new NetworkStream (conn.sock);
Connection.tmpConn = conn;
demo = new DemoObject ();
conn.Marshal (demo, "org.ndesk.test");
//TODO: handle lost connections etc.
while (true)
conn.Iterate ();
}
}
}
[Interface ("org.ndesk.test")]
public class DemoObject : MarshalByRefObject
{
public float Hello (string arg0, int arg1)
{
Console.WriteLine ("Got a Hello(" + arg0 + ", " + arg1 +")");
return (float)arg1/2;
}
}
| mit | C# |
68ab1fd40cf8c69b2a1031d5e1ecff0b23a6ae37 | Use Instrument.Preset to detect preset instruments rather than a null InstrumentGroup | jskeet/DemoCode,jskeet/DemoCode,jskeet/DemoCode,jskeet/DemoCode | Drums/VDrumExplorer.Proto/InstrumentAudio.cs | Drums/VDrumExplorer.Proto/InstrumentAudio.cs | // Copyright 2020 Jon Skeet. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using Google.Protobuf;
using VDrumExplorer.Model;
namespace VDrumExplorer.Proto
{
internal partial class InstrumentAudio
{
internal Model.Audio.InstrumentAudio ToModel(ModuleSchema schema)
{
var bank = Preset ? schema.PresetInstruments : schema.UserSampleInstruments;
var instrument = bank[InstrumentId];
return new Model.Audio.InstrumentAudio(instrument, AudioData.ToByteArray());
}
internal static InstrumentAudio FromModel(Model.Audio.InstrumentAudio audio) =>
new InstrumentAudio
{
AudioData = ByteString.CopyFrom(audio.Audio),
InstrumentId = audio.Instrument.Id,
Preset = audio.Instrument.Group.Preset
};
}
}
| // Copyright 2020 Jon Skeet. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using Google.Protobuf;
using VDrumExplorer.Model;
namespace VDrumExplorer.Proto
{
internal partial class InstrumentAudio
{
internal Model.Audio.InstrumentAudio ToModel(ModuleSchema schema)
{
var bank = Preset ? schema.PresetInstruments : schema.UserSampleInstruments;
var instrument = bank[InstrumentId];
return new Model.Audio.InstrumentAudio(instrument, AudioData.ToByteArray());
}
internal static InstrumentAudio FromModel(Model.Audio.InstrumentAudio audio) =>
new InstrumentAudio
{
AudioData = ByteString.CopyFrom(audio.Audio),
InstrumentId = audio.Instrument.Id,
Preset = audio.Instrument.Group != null
};
}
}
| apache-2.0 | C# |
ac6914e2768fd53ffe1cad5961a1361fcdb00b1a | Clean tests | phnx47/Prometheus.Client | tests/Prometheus.Client.Tests/ThreadSafeDoubleTests.cs | tests/Prometheus.Client.Tests/ThreadSafeDoubleTests.cs | using Prometheus.Client.Tools;
using Xunit;
namespace Prometheus.Client.Tests
{
public class ThreadSafeDoubleTests
{
[Fact]
public void ThreadSafeDouble_Add()
{
var tsdouble = new ThreadSafeDouble(3.10);
tsdouble.Add(0.50);
tsdouble.Add(2.00);
Assert.Equal(5.6, tsdouble.Value);
}
[Fact]
public void ThreadSafeDouble_Constructors()
{
var tsdouble = new ThreadSafeDouble(0.0);
Assert.Equal(0.0, tsdouble.Value);
tsdouble = new ThreadSafeDouble(1.42);
Assert.Equal(1.42, tsdouble.Value);
}
[Fact]
public void ThreadSafeDouble_Overrides()
{
var tsdouble = new ThreadSafeDouble(9.15);
var equaltsdouble = new ThreadSafeDouble(9.15);
var notequaltsdouble = new ThreadSafeDouble(10.11);
Assert.Equal("9.15", tsdouble.ToString());
Assert.True(tsdouble.Equals(equaltsdouble));
Assert.False(tsdouble.Equals(notequaltsdouble));
Assert.False(tsdouble.Equals(null));
Assert.True(tsdouble.Equals(9.15));
Assert.False(tsdouble.Equals(10.11));
Assert.Equal(9.15.GetHashCode(), tsdouble.GetHashCode());
}
[Fact]
public void ThreadSafeDouble_ValueSet()
{
var tsdouble = new ThreadSafeDouble(3.14);
Assert.Equal(3.14, tsdouble.Value);
}
}
}
| using Prometheus.Client.Tools;
using Xunit;
namespace Prometheus.Client.Tests
{
public class ThreadSafeDoubleTests
{
[Fact]
public void ThreadSafeDouble_Add()
{
var tsdouble = new ThreadSafeDouble(3.10);
tsdouble.Add(0.50);
tsdouble.Add(2.00);
Assert.Equal(5.6, tsdouble.Value);
}
[Fact]
public void ThreadSafeDouble_Constructors()
{
var tsdouble = new ThreadSafeDouble();
Assert.Equal(0.0, tsdouble.Value);
tsdouble = new ThreadSafeDouble(1.42);
Assert.Equal(1.42, tsdouble.Value);
}
[Fact]
public void ThreadSafeDouble_Overrides()
{
var tsdouble = new ThreadSafeDouble(9.15);
var equaltsdouble = new ThreadSafeDouble(9.15);
var notequaltsdouble = new ThreadSafeDouble(10.11);
Assert.Equal("9.15", tsdouble.ToString());
Assert.True(tsdouble.Equals(equaltsdouble));
Assert.False(tsdouble.Equals(notequaltsdouble));
Assert.False(tsdouble.Equals(null));
Assert.True(tsdouble.Equals(9.15));
Assert.False(tsdouble.Equals(10.11));
Assert.Equal(9.15.GetHashCode(), tsdouble.GetHashCode());
}
[Fact]
public void ThreadSafeDouble_ValueSet()
{
var tsdouble = new ThreadSafeDouble();
tsdouble.Value = 3.14;
Assert.Equal(3.14, tsdouble.Value);
}
}
}
| mit | C# |
e8d967cfc23c7a702aa4cef9dd36e98981017070 | Improve ConsoleLogger output for exceptions | sapek/bond,sapek/bond,chwarr/bond,Microsoft/bond,tstein/bond,Microsoft/bond,gencer/bond,gencer/bond,jdubrule/bond,Microsoft/bond,tstein/bond,jdubrule/bond,gencer/bond,ant0nsc/bond,tstein/bond,sapek/bond,sapek/bond,chwarr/bond,jdubrule/bond,ant0nsc/bond,chwarr/bond,chwarr/bond,sapek/bond,Microsoft/bond,Microsoft/bond,jdubrule/bond,tstein/bond,gencer/bond,Microsoft/bond,tstein/bond,gencer/bond,sapek/bond,ant0nsc/bond,tstein/bond,chwarr/bond,jdubrule/bond,chwarr/bond,jdubrule/bond,ant0nsc/bond | examples/cs/comm/logging/ConsoleLogger.cs | examples/cs/comm/logging/ConsoleLogger.cs | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Bond.Examples.Logging
{
using System;
using Bond.Comm;
public class ConsoleLogger : LogHandler
{
public void Handle(LogSeverity severity, Exception exception, String format, params object[] args)
{
if (severity < LogSeverity.Information) { return; }
var message = string.Format(format, args);
Console.WriteLine($"[bond] {severity.ToString().ToUpper()}: {message}");
if (exception != null)
{
Console.WriteLine(exception);
}
}
}
}
| // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Bond.Examples.Logging
{
using System;
using Bond.Comm;
public class ConsoleLogger : LogHandler
{
public void Handle(LogSeverity severity, Exception exception, String format, params object[] args)
{
if (severity < LogSeverity.Information) { return; }
var message = string.Format(format, args);
Console.WriteLine($"[bond] {severity.ToString().ToUpper()}: {message}");
if (exception != null)
{
Console.Write(exception);
}
}
}
}
| mit | C# |
c2c7ca8f916d70a01f17e0ea3b633ecaf9d32cfa | Implement drawing | sakapon/Tutorials-2014 | LeapTutorial01/AirCanvas2/MainWindow.xaml.cs | LeapTutorial01/AirCanvas2/MainWindow.xaml.cs | using Leap;
using System;
using System.Collections.Generic;
using System.ComponentModel;
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.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace AirCanvas2
{
/// <summary>
/// MainWindow.xaml の相互作用ロジック
/// </summary>
public partial class MainWindow : Window
{
const int ScreenWidth = 1920;
const int ScreenHeight = 1080;
const int MappingRate = 3;
Controller controller;
Dictionary<int, Stroke> strokes = new Dictionary<int, Stroke>();
public MainWindow()
{
InitializeComponent();
Loaded += MainWindow_Loaded;
Closing += MainWindow_Closing;
}
void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
controller = new Controller();
CompositionTarget.Rendering += CompositionTarget_Rendering;
}
void MainWindow_Closing(object sender, CancelEventArgs e)
{
controller.Dispose();
}
void CompositionTarget_Rendering(object sender, EventArgs e)
{
var frame = controller.Frame();
var positions = frame.Pointables
.Where(p => p.IsValid)
.Where(p => p.StabilizedTipPosition.IsValid())
.Where(p => p.StabilizedTipPosition.z < 0)
.ToDictionary(p => p.Id, p => ToStylusPoint(p.StabilizedTipPosition));
var idsToRemove = strokes.Keys.Except(positions.Keys).ToArray();
foreach (var id in idsToRemove)
{
strokes.Remove(id);
}
foreach (var item in positions)
{
if (strokes.ContainsKey(item.Key))
{
strokes[item.Key].StylusPoints.Add(item.Value);
}
else
{
var stroke = new Stroke(new StylusPointCollection(new[] { item.Value }));
strokes[item.Key] = stroke;
TheCanvas.Strokes.Add(stroke);
}
}
}
static StylusPoint ToStylusPoint(Leap.Vector v)
{
return new StylusPoint(ScreenWidth / 2 + MappingRate * v.x, ScreenHeight - MappingRate * v.y);
}
}
}
| 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 AirCanvas2
{
/// <summary>
/// MainWindow.xaml の相互作用ロジック
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}
}
| mit | C# |
61d9e1bc1163607e5b6406e3c54ebc8c92621409 | Send emails as html | dlidstrom/Snittlistan,dlidstrom/Snittlistan,dlidstrom/Snittlistan | SnittListan/Services/EmailService.cs | SnittListan/Services/EmailService.cs | using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Configuration;
using System.Net.Mail;
using System.Threading.Tasks;
using System.Web;
using System.Web.Configuration;
using Elmah;
namespace SnittListan.Services
{
public class EmailService : IEmailService
{
private string host;
private int port;
private string username;
private string password;
private MailAddress from;
private List<MailAddress> moderatorEmails;
public EmailService()
{
// fetch settings from web.config
var config = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
var settings = (MailSettingsSectionGroup)config.GetSectionGroup("system.net/mailSettings");
this.host = settings.Smtp.Network.Host;
this.port = settings.Smtp.Network.Port;
this.username = settings.Smtp.Network.UserName;
this.password = settings.Smtp.Network.Password;
this.from = new MailAddress(this.username);
this.moderatorEmails = ConfigurationManager
.AppSettings["OwnerEmail"]
.Split(';')
.Select(e => new MailAddress(e.Trim()))
.ToList();
}
public EmailService(string host, int port, string username, string password, IEnumerable<string> moderators)
{
this.host = host;
this.port = port;
this.username = username;
this.password = password;
this.from = new MailAddress(username);
this.moderatorEmails = moderators.Select(e => new MailAddress(e.Trim())).ToList();
}
public void SendMail(string recipient, string subject, string body)
{
// execute asynchronously
Task.Factory.StartNew(
() => DoWork(recipient, subject, body),
TaskCreationOptions.LongRunning)
.ContinueWith(
task => ErrorLog.GetDefault(null).Log(new Error(task.Exception)),
TaskContinuationOptions.OnlyOnFaulted);
}
private void DoWork(string recipient, string subject, string body)
{
var mailMessage = new MailMessage
{
Body = body,
Subject = subject,
From = this.from,
IsBodyHtml = true
};
mailMessage.To.Add(new MailAddress(recipient));
// add moderators
moderatorEmails.ForEach(m => mailMessage.Bcc.Add(m));
using (var smtpClient = new SmtpClient
{
Host = host,
Port = port,
UseDefaultCredentials = false
})
{
smtpClient.Credentials = new NetworkCredential { UserName = this.username, Password = this.password };
smtpClient.Send(mailMessage);
}
}
}
}
| using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Configuration;
using System.Net.Mail;
using System.Threading.Tasks;
using System.Web;
using System.Web.Configuration;
using Elmah;
namespace SnittListan.Services
{
public class EmailService : IEmailService
{
private string host;
private int port;
private string username;
private string password;
private MailAddress from;
private List<MailAddress> moderatorEmails;
public EmailService()
{
// fetch settings from web.config
var config = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
var settings = (MailSettingsSectionGroup)config.GetSectionGroup("system.net/mailSettings");
this.host = settings.Smtp.Network.Host;
this.port = settings.Smtp.Network.Port;
this.username = settings.Smtp.Network.UserName;
this.password = settings.Smtp.Network.Password;
this.from = new MailAddress(this.username);
this.moderatorEmails = ConfigurationManager
.AppSettings["OwnerEmail"]
.Split(';')
.Select(e => new MailAddress(e.Trim()))
.ToList();
}
public EmailService(string host, int port, string username, string password, IEnumerable<string> moderators)
{
this.host = host;
this.port = port;
this.username = username;
this.password = password;
this.from = new MailAddress(username);
this.moderatorEmails = moderators.Select(e => new MailAddress(e.Trim())).ToList();
}
public void SendMail(string recipient, string subject, string body)
{
// execute asynchronously
Task.Factory.StartNew(
() => DoWork(recipient, subject, body),
TaskCreationOptions.LongRunning)
.ContinueWith(
task => ErrorLog.GetDefault(null).Log(new Error(task.Exception)),
TaskContinuationOptions.OnlyOnFaulted);
}
private void DoWork(string recipient, string subject, string body)
{
var mailMessage = new MailMessage
{
Body = body,
Subject = subject,
From = this.from
};
mailMessage.To.Add(new MailAddress(recipient));
// add moderators
moderatorEmails.ForEach(m => mailMessage.Bcc.Add(m));
using (var smtpClient = new SmtpClient
{
Host = host,
Port = port,
UseDefaultCredentials = false
})
{
smtpClient.Credentials = new NetworkCredential { UserName = this.username, Password = this.password };
smtpClient.Send(mailMessage);
}
}
}
}
| mit | C# |
fab9ccb49e4f07b162b8ae0ac691598ec0845bf5 | adjust version number | eugenpodaru/resume,eugenpodaru/resume,eugenpodaru/resume | Resume/Properties/AssemblyInfo.cs | Resume/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Resume")]
[assembly: AssemblyDescription("Eugen Podaru's Resume")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Resume")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("2fb77ae9-82dd-42fb-9501-5704907aadcb")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("0.1.*")]
[assembly: AssemblyFileVersion("0.1.0.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Resume")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Resume")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("2fb77ae9-82dd-42fb-9501-5704907aadcb")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit | C# |
2e4e6eb61246607d72120bb060fd32010bde8e37 | Change version number | artemlos/SKGL-Extension-for-dot-NET,SerialKeyManager/SKGL-Extension-for-dot-NET | SKM/Properties/AssemblyInfo.cs | SKM/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("SKM Client API")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Artem Los")]
[assembly: AssemblyProduct("SKM")]
[assembly: AssemblyCopyright("Copyright © 2014-2017 Artem Los, All rights reserved")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("0f5e191b-dbc9-4a6b-8b55-7d9de286c2fd")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("4.0.2.2")]
[assembly: AssemblyFileVersion("4.0.2.2")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("SKM Client API")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Artem Los")]
[assembly: AssemblyProduct("SKM")]
[assembly: AssemblyCopyright("Copyright © 2014-2017 Artem Los, All rights reserved")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("0f5e191b-dbc9-4a6b-8b55-7d9de286c2fd")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("4.0.2.1")]
[assembly: AssemblyFileVersion("4.0.2.1")]
| bsd-3-clause | C# |
4cfd714025665c80a28ba4e96da81dbef4adcae5 | fix namespace | ucdavis/CRP,ucdavis/CRP,ucdavis/CRP | CRP.Mvc/Controllers/ViewModels/Payment/PaymentReceiptViewModel.cs | CRP.Mvc/Controllers/ViewModels/Payment/PaymentReceiptViewModel.cs | using System;
using CRP.Core.Domain;
namespace CRP.Mvc.Controllers.ViewModels.Payment
{
public class PaymentReceiptViewModel
{
public Item Item { get; set; }
public Core.Domain.Transaction Transaction { get; set; }
public string Amount { get; set; }
public string CardNumber { get; set; }
public DateTime? CardExp { get; set; }
public DateTime AuthDateTime { get; set; }
public string AuthCode { get; set; }
}
} | using System;
using CRP.Core.Domain;
namespace CRP.Mvc.Controllers.ViewModels.Payment
{
public class PaymentReceiptViewModel
{
public Item Item { get; set; }
public Transaction Transaction { get; set; }
public string Amount { get; set; }
public string CardNumber { get; set; }
public DateTime? CardExp { get; set; }
public DateTime AuthDateTime { get; set; }
public string AuthCode { get; set; }
}
} | mit | C# |
ee55bd24960242957cdda5437ceb3e6e3756e589 | Sort game rules before running tests (#10484) | space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14 | Content.IntegrationTests/Tests/GameRules/StartEndGameRulesTest.cs | Content.IntegrationTests/Tests/GameRules/StartEndGameRulesTest.cs | using System;
using System.Linq;
using System.Threading.Tasks;
using Content.Server.GameTicking;
using Content.Server.GameTicking.Rules;
using NUnit.Framework;
using Robust.Shared.GameObjects;
using Robust.Shared.Prototypes;
namespace Content.IntegrationTests.Tests.GameRules;
[TestFixture]
public sealed class StartEndGameRulesTest
{
/// <summary>
/// Tests that all game rules can be added/started/ended at the same time without exceptions.
/// </summary>
[Test]
public async Task TestAllConcurrent()
{
await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings()
{
NoClient = true,
Dirty = true,
});
var server = pairTracker.Pair.Server;
await server.WaitIdleAsync();
var protoMan = server.ResolveDependency<IPrototypeManager>();
var gameTicker = server.ResolveDependency<IEntitySystemManager>().GetEntitySystem<GameTicker>();
await server.WaitAssertion(() =>
{
var rules = protoMan.EnumeratePrototypes<GameRulePrototype>().ToList();
rules.Sort((x, y) => string.Compare(x.ID, y.ID, StringComparison.Ordinal));
// Start all rules
foreach (var rule in rules)
{
gameTicker.StartGameRule(rule);
}
Assert.That(gameTicker.AddedGameRules, Has.Count.EqualTo(rules.Count));
});
// Wait three ticks for any random update loops that might happen
await server.WaitRunTicks(3);
await server.WaitAssertion(() =>
{
// End all rules
gameTicker.ClearGameRules();
Assert.That(!gameTicker.AddedGameRules.Any());
});
await pairTracker.CleanReturnAsync();
}
}
| using System.Linq;
using System.Threading.Tasks;
using Content.Server.GameTicking;
using Content.Server.GameTicking.Rules;
using NUnit.Framework;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Prototypes;
namespace Content.IntegrationTests.Tests.GameRules;
/// <summary>
/// Tests that all game rules can be added/started/ended at the same time without exceptions.
/// </summary>
[TestFixture]
public sealed class StartEndGameRulesTest
{
[Test]
public async Task Test()
{
await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings(){Dirty = true});
var server = pairTracker.Pair.Server;
await server.WaitAssertion(() =>
{
var gameTicker = EntitySystem.Get<GameTicker>();
var protoMan = IoCManager.Resolve<IPrototypeManager>();
var rules = protoMan.EnumeratePrototypes<GameRulePrototype>().ToArray();
// Start all rules
foreach (var rule in rules)
{
gameTicker.StartGameRule(rule);
}
Assert.That(gameTicker.AddedGameRules.Count == rules.Length);
});
// Wait three ticks for any random update loops that might happen
await server.WaitRunTicks(3);
await server.WaitAssertion(() =>
{
var gameTicker = EntitySystem.Get<GameTicker>();
// End all rules
gameTicker.ClearGameRules();
Assert.That(!gameTicker.AddedGameRules.Any());
});
await pairTracker.CleanReturnAsync();
}
}
| mit | C# |
16849cbe3be69597af099eb1f2e910afff69ff08 | Update moderation page. | enarod/enarod-web-api,enarod/enarod-web-api,enarod/enarod-web-api | Infopulse.EDemocracy.Web/Areas/Admin/Views/Petitions/Index.cshtml | Infopulse.EDemocracy.Web/Areas/Admin/Views/Petitions/Index.cshtml | @model List<Infopulse.EDemocracy.Model.BusinessEntities.Petition>
@{
ViewBag.Title = "Модерація петицій";
}
<div class="row">
<h2 class="col-md-12">Модерація петицій</h2>
</div>
<table>
<thead>
<tr>
<th>Petition ID</th>
<th>Subject</th>
<th>Creation date</th>
<th>Approved by</th>
<th>Approved date</th>
</tr>
</thead>
<tbody>
@foreach (var petition in Model)
{
<tr>
<td>@petition.ID</td>
<td>@petition.Subject</td>
<td>@petition.CreatedDate</td>
<td>none</td>
<td>none</td>
</tr>
}
</tbody>
</table> | @model List<Infopulse.EDemocracy.Model.BusinessEntities.Petition>
@{
ViewBag.Title = "Модерація петицій";
}
<div class="row">
<h2 class="col-md-12">Модерація петицій</h2>
</div>
<ol>
@foreach (var petition in Model)
{
<li>@petition.Subject</li>
}
</ol> | cc0-1.0 | C# |
94b490b2b4e585abf4857166af9f534546bb5467 | Add test case for gift insertion | kw90/SantasSledge | Santa/Tests/Common/TourTest.cs | Santa/Tests/Common/TourTest.cs | using Common;
using NUnit.Framework;
namespace Tests.Common
{
[TestFixture]
public class TourTest
{
private Tour testee;
[SetUp]
public void Init()
{
testee = new Tour();
testee.AddGift(new Gift(1, 500, 0, 0));
testee.AddGift(new Gift(2, 500, 4, 2));
}
[Test]
public void TestValidTourWeight()
{
Assert.IsTrue(testee.IsValid());
}
[Test]
public void TestInvalidTourWeight()
{
testee.AddGift(new Gift(3, 0.001, 5, 5));
Assert.IsFalse(testee.IsValid());
}
[Test]
public void TestAddGift()
{
int oldCount = testee.Gifts.Count;
testee.AddGift(new Gift(3, 0.001, 5, 5));
Assert.AreEqual(oldCount + 1, testee.Gifts.Count);
}
}
}
| using Common;
using NUnit.Framework;
namespace Tests.Common
{
[TestFixture]
public class TourTest
{
private Tour testee;
[SetUp]
public void Init()
{
testee = new Tour();
testee.AddGift(new Gift(1, 500, 0, 0));
testee.AddGift(new Gift(2, 500, 4, 2));
}
[Test]
public void TestValidTourWeight()
{
Assert.IsTrue(testee.IsValid());
}
[Test]
public void TestInvalidTourWeight()
{
testee.AddGift(new Gift(3, 0.001, 5, 5));
Assert.IsFalse(testee.IsValid());
}
}
}
| mit | C# |
5f87edd25405b75d6f889a0865a73e0217fe1a51 | Fix archiving tests on Linux | gtryus/libpalaso,sillsdev/libpalaso,mccarthyrb/libpalaso,tombogle/libpalaso,ddaspit/libpalaso,ermshiperete/libpalaso,andrew-polk/libpalaso,sillsdev/libpalaso,ermshiperete/libpalaso,sillsdev/libpalaso,gtryus/libpalaso,andrew-polk/libpalaso,ermshiperete/libpalaso,gmartin7/libpalaso,ddaspit/libpalaso,andrew-polk/libpalaso,tombogle/libpalaso,ddaspit/libpalaso,ermshiperete/libpalaso,glasseyes/libpalaso,mccarthyrb/libpalaso,gmartin7/libpalaso,mccarthyrb/libpalaso,gtryus/libpalaso,gtryus/libpalaso,tombogle/libpalaso,glasseyes/libpalaso,gmartin7/libpalaso,mccarthyrb/libpalaso,glasseyes/libpalaso,sillsdev/libpalaso,tombogle/libpalaso,glasseyes/libpalaso,ddaspit/libpalaso,gmartin7/libpalaso,andrew-polk/libpalaso | SIL.Archiving/Generic/ArchivingFileSystem.cs | SIL.Archiving/Generic/ArchivingFileSystem.cs |
using System;
using System.IO;
using SIL.PlatformUtilities;
namespace SIL.Archiving.Generic
{
/// <summary />
public static class ArchivingFileSystem
{
internal const string kAccessProtocolFolderName = "Archiving";
/// <summary />
public static string SilCommonDataFolder
{
get
{
// On Linux we have to use /var/lib (instead of CommonApplicationData which
// translates to /usr/share and isn't writable by default)
string folder = Platform.IsLinux ? "/var/lib" :
Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
return CheckFolder(Path.Combine(folder, "SIL"));
}
}
/// <summary />
public static string SilCommonArchivingDataFolder
{
get { return CheckFolder(Path.Combine(SilCommonDataFolder, kAccessProtocolFolderName)); }
}
/// <summary />
public static string SilCommonIMDIDataFolder
{
get { return CheckFolder(Path.Combine(SilCommonArchivingDataFolder, "IMDI")); }
}
/// <summary />
public static string CheckFolder(string folderName)
{
if (!Directory.Exists(folderName))
{
try
{
Directory.CreateDirectory(folderName);
}
catch (UnauthorizedAccessException)
{
if (Platform.IsLinux)
{
if (folderName.StartsWith("/var/lib/SIL"))
{
// by default /var/lib isn't writable on Linux, so we can't create a new
// directory. Create a folder in the user's home directory instead.
var endFolder = folderName.Substring("/var/lib/SIL".Length).TrimStart('/');
folderName = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"SIL", endFolder);
return CheckFolder(folderName);
}
}
throw;
}
}
return folderName;
}
}
}
|
using System;
using System.IO;
using SIL.PlatformUtilities;
namespace SIL.Archiving.Generic
{
/// <summary />
public static class ArchivingFileSystem
{
internal const string kAccessProtocolFolderName = "Archiving";
/// <summary />
public static string SilCommonDataFolder
{
get
{
// On Linux we have to use /var/lib (instead of CommonApplicationData which
// translates to /usr/share and isn't writable by default)
string folder = Platform.IsLinux ? "/var/lib" :
Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
return CheckFolder(Path.Combine(folder, "SIL"));
}
}
/// <summary />
public static string SilCommonArchivingDataFolder
{
get { return CheckFolder(Path.Combine(SilCommonDataFolder, kAccessProtocolFolderName)); }
}
/// <summary />
public static string SilCommonIMDIDataFolder
{
get { return CheckFolder(Path.Combine(SilCommonArchivingDataFolder, "IMDI")); }
}
/// <summary />
public static string CheckFolder(string folderName)
{
if (!Directory.Exists(folderName))
{
try
{
Directory.CreateDirectory(folderName);
}
catch (UnauthorizedAccessException)
{
if (Platform.IsLinux)
{
if (folderName.StartsWith("/var/lib/SIL/"))
{
// by default /var/lib isn't writable on Linux, so we can't create a new
// directory. Create a folder in the user's home directory instead.
var endFolder = folderName.Substring("/var/lib/SIL/".Length);
folderName = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"SIL", endFolder);
return CheckFolder(folderName);
}
}
throw;
}
}
return folderName;
}
}
}
| mit | C# |
f26274462761a932ff5ce49e889129175204d51f | Make PrincipalType [Flags] | Brightspace/D2L.Security.OAuth2 | D2L.Security.OAuth2/Principal/PrincipalType.cs | D2L.Security.OAuth2/Principal/PrincipalType.cs | using System;
namespace D2L.Security.OAuth2.Principal {
/// <summary>
/// Principal types
/// </summary>
[Flags]
public enum PrincipalType {
/// <summary>
/// Principal represents a user. Applies when the sub claim is set on the principal
/// </summary>
User = 1,
/// <summary>
/// Principal represents a service. Applies when the sub claim is not set on the principal
/// </summary>
Service = 2,
/// <summary>
/// No principal
/// </summary>
Anonymous = 4
}
}
| namespace D2L.Security.OAuth2.Principal {
/// <summary>
/// Principal types
/// </summary>
public enum PrincipalType {
/// <summary>
/// Principal represents a user. Applies when the sub claim is set on the principal
/// </summary>
User,
/// <summary>
/// Principal represents a service. Applies when the sub claim is not set on the principal
/// </summary>
Service,
/// <summary>
/// No principal
/// </summary>
Anonymous
}
}
| apache-2.0 | C# |
e4c591d242823175cc1df1d9d928825d3a417589 | allow internals to be visible for some internal projects | ali-ince/neo4j-dotnet-driver,neo4j/neo4j-dotnet-driver,neo4j/neo4j-dotnet-driver | Neo4j.Driver/Neo4j.Driver/Properties/AssemblyInfo.cs | Neo4j.Driver/Neo4j.Driver/Properties/AssemblyInfo.cs | // Copyright (c) 2002-2017 "Neo Technology,"
// Network Engine for Objects in Lund AB [http://neotechnology.com]
//
// This file is part of Neo4j.
//
// 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.Resources;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Neo4j.Driver")]
[assembly: AssemblyDescription("The official .NET driver for the Neo4j Graph Database over the Bolt protocol.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Neo4j.Driver")]
[assembly: AssemblyCopyright("Copyright © 2002-2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.5.*")]
[assembly: AssemblyVersion("1.5.0.0")]
[assembly: AssemblyFileVersion("1.5.0.0")]
[assembly: InternalsVisibleTo("Neo4j.Driver.Tests"), InternalsVisibleTo("Neo4j.Driver.IntegrationTests"), InternalsVisibleTo("Neo4j.Driver.Tck.Tests"), InternalsVisibleTo("DynamicProxyGenAssembly2"), InternalsVisibleTo("Neo4j.Driver.Benchmark.NBench.Akka")]
| // Copyright (c) 2002-2017 "Neo Technology,"
// Network Engine for Objects in Lund AB [http://neotechnology.com]
//
// This file is part of Neo4j.
//
// 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.Resources;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Neo4j.Driver")]
[assembly: AssemblyDescription("The official .NET driver for the Neo4j Graph Database over the Bolt protocol.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Neo4j.Driver")]
[assembly: AssemblyCopyright("Copyright © 2002-2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.5.*")]
[assembly: AssemblyVersion("1.5.0.0")]
[assembly: AssemblyFileVersion("1.5.0.0")]
[assembly: InternalsVisibleTo("Neo4j.Driver.Tests"), InternalsVisibleTo("Neo4j.Driver.IntegrationTests"), InternalsVisibleTo("Neo4j.Driver.Tck.Tests"), InternalsVisibleTo("DynamicProxyGenAssembly2")]
| apache-2.0 | C# |
8d3d23e371891ccf310f572d9bb0d60f100681df | Change #65 Substitute variables in Debug Log command | RonanPearce/Fungus,FungusGames/Fungus,kdoore/Fungus,tapiralec/Fungus,lealeelu/Fungus,snozbot/fungus,Nilihum/fungus,inarizushi/Fungus | Assets/Fungus/FungusScript/Scripts/Commands/DebugLog.cs | Assets/Fungus/FungusScript/Scripts/Commands/DebugLog.cs | using UnityEngine;
using System.Collections;
namespace Fungus
{
[CommandInfo("Scripting",
"Debug Log",
"Writes a log message to the debug console.")]
public class DebugLog : Command
{
public enum DebugLogType
{
Info,
Warning,
Error
}
public DebugLogType logType;
public StringData logMessage;
public override void OnEnter ()
{
FungusScript fungusScript = GetFungusScript();
string message = fungusScript.SubstituteVariables(logMessage.Value);
switch (logType)
{
case DebugLogType.Info:
Debug.Log(message);
break;
case DebugLogType.Warning:
Debug.LogWarning(message);
break;
case DebugLogType.Error:
Debug.LogError(message);
break;
}
Continue();
}
public override string GetSummary()
{
return logMessage.GetDescription();
}
public override Color GetButtonColor()
{
return new Color32(235, 191, 217, 255);
}
}
} | using UnityEngine;
using System.Collections;
namespace Fungus
{
[CommandInfo("Scripting",
"Debug Log",
"Writes a log message to the debug console.")]
public class DebugLog : Command
{
public enum DebugLogType
{
Info,
Warning,
Error
}
public DebugLogType logType;
public StringData logMessage;
public override void OnEnter ()
{
switch (logType)
{
case DebugLogType.Info:
Debug.Log(logMessage.Value);
break;
case DebugLogType.Warning:
Debug.LogWarning(logMessage.Value);
break;
case DebugLogType.Error:
Debug.LogError(logMessage.Value);
break;
}
Continue();
}
public override string GetSummary()
{
return logMessage.GetDescription();
}
public override Color GetButtonColor()
{
return new Color32(235, 191, 217, 255);
}
}
} | mit | C# |
fb6093eb65d1e300d8f67ceb3682639a9a47f77f | Revert "walk cycle doesn't awkwardly begi" | Barleytree/NitoriWare,NitorInc/NitoriWare,NitorInc/NitoriWare,Barleytree/NitoriWare | Assets/Microgames/KnifeDodge/Scripts/KnifeDodgeReimu.cs | Assets/Microgames/KnifeDodge/Scripts/KnifeDodgeReimu.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class KnifeDodgeReimu : MonoBehaviour {
public float speed = 1; // speed in meters per second
public float animSpeed = 1f;
public float animSpeedStopped = 0.25f;
public float killLaunchSpeed = 15.0f;
public GameObject leftBound;
public GameObject rightBound;
bool bIsKilled;
// Use this for initialization
void Start () {
bIsKilled = false;
}
void Update(){
Vector3 moveDir = Vector3.zero;
if (!bIsKilled) {
moveDir.x = Input.GetAxisRaw ("Horizontal"); // get result of AD keys in X
moveDir.z = Input.GetAxisRaw ("Vertical"); // get result of WS keys in Z
}
if (moveDir == Vector3.zero) {
GetComponent<Animator> ().speed = animSpeedStopped;
GetComponent<Animator> ().Play ("Standing");
} else {
GetComponent<Animator> ().speed = animSpeed;
GetComponent<Animator> ().Play ("Moving");
}
// move this object at frame rate independent speed:
float boundryColliderSize = leftBound.GetComponent<BoxCollider2D>().size.x;
if (moveDir.x > 0
&& transform.position.x < rightBound.GetComponent<Transform> ().position.x) {
transform.position += moveDir * speed * Time.deltaTime;
}
if ((transform.position.x > leftBound.GetComponent<Transform> ().position.x)
&& moveDir.x < 0) {
transform.position += moveDir * speed * Time.deltaTime;
}
}
void OnCollisionEnter2D(Collision2D coll) {
if (coll.gameObject.tag == "KnifeDodgeHazard") {
Kill ();
MicrogameController.instance.setVictory (false, true);
}
}
public void Kill() {
bIsKilled = true;
GetComponent<BoxCollider2D> ().size = new Vector2 (0, 0);
transform.GetComponent<Rigidbody2D> ().velocity = new Vector2 (0, killLaunchSpeed);
transform.GetComponent<Rigidbody2D> ().angularVelocity = 80.0f;
MicrogameController.instance.setVictory (false, true);
// To implement later
// CameraShake.instance.setScreenShake (.15f);
// CameraShake.instance.shakeCoolRate = .5f;
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class KnifeDodgeReimu : MonoBehaviour {
public float speed = 1; // speed in meters per second
public float animSpeed = 1f;
public float animSpeedStopped = 0.25f;
public float killLaunchSpeed = 15.0f;
public GameObject leftBound;
public GameObject rightBound;
bool bIsKilled;
// Use this for initialization
void Start () {
bIsKilled = false;
}
void Update(){
Vector3 moveDir = Vector3.zero;
if (!bIsKilled) {
moveDir.x = Input.GetAxisRaw ("Horizontal"); // get result of AD keys in X
moveDir.z = Input.GetAxisRaw ("Vertical"); // get result of WS keys in Z
}
if (moveDir == Vector3.zero) {
GetComponent<Animator> ().speed = animSpeedStopped;
} else {
GetComponent<Animator> ().speed = animSpeed;
}
// move this object at frame rate independent speed:
float boundryColliderSize = leftBound.GetComponent<BoxCollider2D>().size.x;
if (moveDir.x > 0
&& transform.position.x < rightBound.GetComponent<Transform> ().position.x) {
transform.position += moveDir * speed * Time.deltaTime;
}
if ((transform.position.x > leftBound.GetComponent<Transform> ().position.x)
&& moveDir.x < 0) {
transform.position += moveDir * speed * Time.deltaTime;
}
}
void OnCollisionEnter2D(Collision2D coll) {
if (coll.gameObject.tag == "KnifeDodgeHazard") {
Kill ();
MicrogameController.instance.setVictory (false, true);
}
}
public void Kill() {
bIsKilled = true;
GetComponent<BoxCollider2D> ().size = new Vector2 (0, 0);
transform.GetComponent<Rigidbody2D> ().velocity = new Vector2 (0, killLaunchSpeed);
transform.GetComponent<Rigidbody2D> ().angularVelocity = 80.0f;
MicrogameController.instance.setVictory (false, true);
// To implement later
// CameraShake.instance.setScreenShake (.15f);
// CameraShake.instance.shakeCoolRate = .5f;
}
}
| mit | C# |
4e53274f2f1fc6d8c4c375bd9a76a06537be9e81 | Optimize clipping | protyposis/Aurio,protyposis/Aurio | AudioAlign/AudioAlign.Audio/Streams/VolumeClipStream.cs | AudioAlign/AudioAlign.Audio/Streams/VolumeClipStream.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NAudio.Wave;
namespace AudioAlign.Audio.Streams {
public class VolumeClipStream : AbstractAudioStreamWrapper {
public VolumeClipStream(IAudioStream sourceStream)
: base(sourceStream) {
if (!(sourceStream.Properties.Format == AudioFormat.IEEE && sourceStream.Properties.BitDepth == 32)) {
throw new ArgumentException("unsupported source format: " + sourceStream.Properties);
}
Clip = true;
}
/// <summary>
/// Enables or disables audio sample clipping.
/// </summary>
public bool Clip { get; set; }
public override int Read(byte[] buffer, int offset, int count) {
int bytesRead = sourceStream.Read(buffer, offset, count);
if (Clip && bytesRead > 0) {
unsafe {
fixed (byte* sampleBuffer = &buffer[offset]) {
float* samples = (float*)sampleBuffer;
for (int x = 0; x < bytesRead / 4; x++) {
if (samples[x] > 1.0f) {
samples[x] = 1.0f;
}
else if(samples[x] < -1.0f) {
samples[x] = -1.0f;
}
}
}
}
}
return bytesRead;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NAudio.Wave;
namespace AudioAlign.Audio.Streams {
public class VolumeClipStream : AbstractAudioStreamWrapper {
public VolumeClipStream(IAudioStream sourceStream)
: base(sourceStream) {
if (!(sourceStream.Properties.Format == AudioFormat.IEEE && sourceStream.Properties.BitDepth == 32)) {
throw new ArgumentException("unsupported source format: " + sourceStream.Properties);
}
Clip = true;
}
/// <summary>
/// Enables or disables audio sample clipping.
/// </summary>
public bool Clip { get; set; }
public override int Read(byte[] buffer, int offset, int count) {
int bytesRead = sourceStream.Read(buffer, offset, count);
if (Clip && bytesRead > 0) {
unsafe {
fixed (byte* sampleBuffer = &buffer[offset]) {
float* samples = (float*)sampleBuffer;
for (int x = 0; x < bytesRead / 4; x++) {
if (samples[x] > 0) {
samples[x] = samples[x] > 1 ? 1.0f : samples[x];
}
else {
samples[x] = samples[x] < -1 ? -1.0f : samples[x];
}
}
}
}
}
return bytesRead;
}
}
}
| agpl-3.0 | C# |
ea2792145fb90e2aaa4f3109b52dfc5b67475433 | Rename variable to match type | jcrang/dependency-injection-kata-series,mjac/dependency-injection-kata-series | src/DependencyInjection.Console/PatternGenerators/SquareIndependentPatternGenerator.cs | src/DependencyInjection.Console/PatternGenerators/SquareIndependentPatternGenerator.cs | using DependencyInjection.Console.Entities;
using DependencyInjection.Console.SquarePainters;
namespace DependencyInjection.Console.PatternGenerators
{
internal class SquareIndependentPatternGenerator : IPatternGenerator
{
private readonly ISquarePainter _squarePainter;
public SquareIndependentPatternGenerator()
{
_squarePainter = new CircleSquarePainter();
}
public Pattern Generate(int width, int height)
{
var pattern = new Pattern(width, height);
var squares = pattern.Squares;
for (var i = 0; i < width; ++i)
{
for (var j = 0; j < height; ++j)
{
squares[i, j] = _squarePainter.PaintSquare(width, height, i, j);
}
}
return pattern;
}
}
} | using DependencyInjection.Console.Entities;
using DependencyInjection.Console.SquarePainters;
namespace DependencyInjection.Console.PatternGenerators
{
internal class SquareIndependentPatternGenerator : IPatternGenerator
{
private readonly ISquarePainter _squarePainter;
public SquareIndependentPatternGenerator()
{
_squarePainter = new CircleSquarePainter();
}
public Pattern Generate(int width, int height)
{
var generate = new Pattern(width, height);
var squares = generate.Squares;
for (var i = 0; i < width; ++i)
{
for (var j = 0; j < height; ++j)
{
squares[i, j] = _squarePainter.PaintSquare(width, height, i, j);
}
}
return generate;
}
}
} | mit | C# |
064a245bedbbfb6cfed13d5034ac7b80b5f7af97 | Add documentation for ClockTimeSpan. | eylvisaker/AgateLib | AgateLib/Platform/ClockTimeSpan.cs | AgateLib/Platform/ClockTimeSpan.cs | using System;
namespace AgateLib.Platform
{
/// <summary>
/// Structure which represents a time span on an IStopClock object.
/// </summary>
public struct ClockTimeSpan
{
/// <summary>
/// Constructs a new ClockTimeSpan object representing the amount of seconds.
/// </summary>
/// <param name="timePassedSeconds"></param>
/// <returns></returns>
public static ClockTimeSpan FromSeconds(double timePassedSeconds)
{
return new ClockTimeSpan(timePassedSeconds);
}
/// <summary>
/// Constructs a new ClockTimeSpan object representing the amount of milliseconds.
/// </summary>
/// <param name="timePassedMs"></param>
/// <returns></returns>
public static ClockTimeSpan FromMilliseconds(double timePassedMs)
{
return new ClockTimeSpan(timePassedMs * 0.001);
}
/// <summary>
/// Returns an empty ClockTimeSpan object.
/// </summary>
public static ClockTimeSpan Zero => new ClockTimeSpan();
private double timeSpanSeconds;
private ClockTimeSpan(double timeSpanSeconds)
{
this.timeSpanSeconds = timeSpanSeconds;
}
/// <summary>
/// Gets the total amount of time in milliseconds.
/// </summary>
public double TotalMilliseconds => timeSpanSeconds * 1000;
/// <summary>
/// Gets the total amount of time in seconds.
/// </summary>
public double TotalSeconds => timeSpanSeconds;
/// <summary>
/// Converts a ClockTimeSpan to a TimeSpan object.
/// </summary>
/// <param name="source"></param>
public static explicit operator TimeSpan(ClockTimeSpan source)
{
return TimeSpan.FromMilliseconds(source.TotalMilliseconds);
}
}
} | namespace AgateLib.Platform
{
public struct ClockTimeSpan
{
public static ClockTimeSpan FromSeconds(double timePassedSeconds)
{
return new ClockTimeSpan(timePassedSeconds);
}
public static ClockTimeSpan FromMilliseconds(double timePassedMs)
{
return new ClockTimeSpan(timePassedMs * 0.001);
}
public static ClockTimeSpan Zero => new ClockTimeSpan();
private double timeSpanSeconds;
private ClockTimeSpan(double timeSpanSeconds)
{
this.timeSpanSeconds = timeSpanSeconds;
}
public double TotalMilliseconds => timeSpanSeconds * 1000;
public double TotalSeconds => timeSpanSeconds;
}
} | mit | C# |
fce53d319ade8f4ed920d00c12f358344892d18c | Bump version | Weingartner/ReactiveCompositeCollections | ReactiveCompositeCollections/Properties/AssemblyInfo.cs | ReactiveCompositeCollections/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ReactiveCompositeCollections")]
[assembly: AssemblyDescription("ReactiveCompositeCollections")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Weingartner Maschinenbau GmbH")]
[assembly: AssemblyProduct("ReactiveCompositeCollections")]
[assembly: AssemblyCopyright("Copyright Weingartner Maschinenbau GmbH © HP 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("5b586874-8d3e-4137-9ba8-e982413416d5")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.3.0.0")]
[assembly: AssemblyFileVersion("1.3.0.0")]
[assembly: AssemblyInformationalVersion("1.3.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ReactiveCompositeCollections")]
[assembly: AssemblyDescription("ReactiveCompositeCollections")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Weingartner Maschinenbau GmbH")]
[assembly: AssemblyProduct("ReactiveCompositeCollections")]
[assembly: AssemblyCopyright("Copyright Weingartner Maschinenbau GmbH © HP 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("5b586874-8d3e-4137-9ba8-e982413416d5")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.2.0.0")]
[assembly: AssemblyFileVersion("1.2.0.0")]
[assembly: AssemblyInformationalVersion("1.2.0")]
| mit | C# |
97945d1dde7d021e5cfd7949f55fd727416c36c2 | Update the IKlawrAppDomainManager interface | Algorithman/klawr,lightszero/klawr,enlight/klawr,enlight/klawr,Algorithman/klawr,lightszero/klawr,Algorithman/klawr,lightszero/klawr,enlight/klawr | Engine/Source/ThirdParty/Klawr/ClrHostInterfaces/IKlawrAppDomainManager.cs | Engine/Source/ThirdParty/Klawr/ClrHostInterfaces/IKlawrAppDomainManager.cs | //
// The MIT License (MIT)
//
// Copyright (c) 2014 Vadim Macagon
//
// 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.InteropServices;
namespace Klawr.ClrHost.Interfaces
{
/// <summary>
/// This interface is implemented by the managed side of the CLR host, and is used by the
/// native side of the CLR host to interact with the managed side.
/// </summary>
[ComVisible(true)]
[GuidAttribute("D90BC9C3-F4DC-4103-BEFA-966FA8C4B7EF")]
public interface IKlawrAppDomainManager
{
/// <summary>
/// Create an engine app domain that can be unloaded.
/// This method should only be invoked on the default app domain manager.
/// </summary>
void CreateEngineAppDomain();
/// <summary>
/// Unload the engine app domain.
/// This method should only be invoked on the default app domain manager.
/// </summary>
void DestroyEngineAppDomain();
/// <summary>
/// Store pointers to native functions that wrap methods of a C++ class.
/// This method should only be invoked on the engine app domain manager.
/// </summary>
/// <param name="nativeClassName">Name of C++ class to store function pointers for.</param>
/// <param name="functionPointers">Array of pointers to native functions.</param>
void SetNativeFunctionPointers(string nativeClassName, IntPtr[] functionPointers);
/// <summary>
/// Retrieve pointers to native functions that wrap methods of a C++ class.
/// This method should only be invoked on the default app domain manager.
/// </summary>
/// <param name="nativeClassName">Name of C++ class to retrieve function pointers for.</param>
/// <returns>Array of pointers to native functions.</returns>
IntPtr[] GetNativeFunctionPointers(string nativeClassName);
}
}
| //
// The MIT License (MIT)
//
// Copyright (c) 2014 Vadim Macagon
//
// 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.InteropServices;
namespace Klawr.ClrHost.Interfaces
{
/// <summary>
/// This interface is implemented by the managed side of the CLR host, and is used by the
/// native side of the CLR host to interact with the managed side.
/// </summary>
[ComVisible(true)]
[GuidAttribute("D90BC9C3-F4DC-4103-BEFA-966FA8C4B7EF")]
public interface IKlawrAppDomainManager
{
/// <summary>
/// Store pointers to native functions that wrap methods of a C++ class.
/// </summary>
/// <param name="nativeClassName">Name of C++ class to store function pointers for.</param>
/// <param name="functionPointers">Array of pointers to native functions.</param>
void SetNativeFunctionPointers(string nativeClassName, IntPtr[] functionPointers);
/// <summary>
/// Retrieve pointers to native functions that wrap methods of a C++ class.
/// </summary>
/// <param name="nativeClassName">Name of C++ class to retrieve function pointers for.</param>
/// <returns>Array of pointers to native functions.</returns>
IntPtr[] GetNativeFunctionPointers(string nativeClassName);
}
}
| mit | C# |
8552c05cb1e82d9c749ca83bd7b73bb45ded09b6 | Remove blank line. | heejaechang/roslyn,dotnet/roslyn,physhi/roslyn,OmarTawfik/roslyn,genlu/roslyn,panopticoncentral/roslyn,bartdesmet/roslyn,jmarolf/roslyn,weltkante/roslyn,tmat/roslyn,shyamnamboodiripad/roslyn,dotnet/roslyn,panopticoncentral/roslyn,KirillOsenkov/roslyn,AmadeusW/roslyn,sharwell/roslyn,AlekseyTs/roslyn,physhi/roslyn,bkoelman/roslyn,abock/roslyn,wvdd007/roslyn,jasonmalinowski/roslyn,tannergooding/roslyn,agocke/roslyn,AmadeusW/roslyn,DustinCampbell/roslyn,reaction1989/roslyn,jasonmalinowski/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,bkoelman/roslyn,KevinRansom/roslyn,tmat/roslyn,cston/roslyn,wvdd007/roslyn,dotnet/roslyn,genlu/roslyn,stephentoub/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,VSadov/roslyn,nguerrera/roslyn,VSadov/roslyn,jamesqo/roslyn,davkean/roslyn,jmarolf/roslyn,abock/roslyn,OmarTawfik/roslyn,VSadov/roslyn,diryboy/roslyn,shyamnamboodiripad/roslyn,KirillOsenkov/roslyn,MichalStrehovsky/roslyn,mavasani/roslyn,nguerrera/roslyn,heejaechang/roslyn,bartdesmet/roslyn,CyrusNajmabadi/roslyn,tannergooding/roslyn,tmeschter/roslyn,DustinCampbell/roslyn,swaroop-sridhar/roslyn,jcouv/roslyn,eriawan/roslyn,weltkante/roslyn,cston/roslyn,tmat/roslyn,brettfo/roslyn,AlekseyTs/roslyn,dpoeschl/roslyn,paulvanbrenk/roslyn,davkean/roslyn,aelij/roslyn,physhi/roslyn,reaction1989/roslyn,paulvanbrenk/roslyn,MichalStrehovsky/roslyn,gafter/roslyn,jcouv/roslyn,nguerrera/roslyn,AmadeusW/roslyn,sharwell/roslyn,xasx/roslyn,paulvanbrenk/roslyn,agocke/roslyn,eriawan/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,jasonmalinowski/roslyn,diryboy/roslyn,ErikSchierboom/roslyn,CyrusNajmabadi/roslyn,mgoertz-msft/roslyn,bartdesmet/roslyn,KevinRansom/roslyn,OmarTawfik/roslyn,ErikSchierboom/roslyn,heejaechang/roslyn,mavasani/roslyn,brettfo/roslyn,gafter/roslyn,reaction1989/roslyn,agocke/roslyn,jcouv/roslyn,eriawan/roslyn,dpoeschl/roslyn,stephentoub/roslyn,diryboy/roslyn,swaroop-sridhar/roslyn,KirillOsenkov/roslyn,xasx/roslyn,abock/roslyn,tannergooding/roslyn,MichalStrehovsky/roslyn,swaroop-sridhar/roslyn,stephentoub/roslyn,genlu/roslyn,mavasani/roslyn,cston/roslyn,ErikSchierboom/roslyn,jamesqo/roslyn,jmarolf/roslyn,CyrusNajmabadi/roslyn,DustinCampbell/roslyn,KevinRansom/roslyn,xasx/roslyn,panopticoncentral/roslyn,sharwell/roslyn,mgoertz-msft/roslyn,tmeschter/roslyn,mgoertz-msft/roslyn,aelij/roslyn,brettfo/roslyn,tmeschter/roslyn,weltkante/roslyn,shyamnamboodiripad/roslyn,dpoeschl/roslyn,bkoelman/roslyn,AlekseyTs/roslyn,wvdd007/roslyn,gafter/roslyn,aelij/roslyn,davkean/roslyn,jamesqo/roslyn | src/Workspaces/Core/Portable/EmbeddedLanguages/RegularExpressions/IRegexNodeVisitor.cs | src/Workspaces/Core/Portable/EmbeddedLanguages/RegularExpressions/IRegexNodeVisitor.cs | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace Microsoft.CodeAnalysis.EmbeddedLanguages.RegularExpressions
{
internal interface IRegexNodeVisitor
{
void Visit(RegexCompilationUnit node);
void Visit(RegexSequenceNode node);
void Visit(RegexTextNode node);
void Visit(RegexCharacterClassNode node);
void Visit(RegexNegatedCharacterClassNode node);
void Visit(RegexCharacterClassRangeNode node);
void Visit(RegexCharacterClassSubtractionNode node);
void Visit(RegexPosixPropertyNode node);
void Visit(RegexWildcardNode node);
void Visit(RegexZeroOrMoreQuantifierNode node);
void Visit(RegexOneOrMoreQuantifierNode node);
void Visit(RegexZeroOrOneQuantifierNode node);
void Visit(RegexLazyQuantifierNode node);
void Visit(RegexExactNumericQuantifierNode node);
void Visit(RegexOpenNumericRangeQuantifierNode node);
void Visit(RegexClosedNumericRangeQuantifierNode node);
void Visit(RegexAnchorNode node);
void Visit(RegexAlternationNode node);
void Visit(RegexSimpleGroupingNode node);
void Visit(RegexSimpleOptionsGroupingNode node);
void Visit(RegexNestedOptionsGroupingNode node);
void Visit(RegexNonCapturingGroupingNode node);
void Visit(RegexPositiveLookaheadGroupingNode node);
void Visit(RegexNegativeLookaheadGroupingNode node);
void Visit(RegexPositiveLookbehindGroupingNode node);
void Visit(RegexNegativeLookbehindGroupingNode node);
void Visit(RegexNonBacktrackingGroupingNode node);
void Visit(RegexCaptureGroupingNode node);
void Visit(RegexBalancingGroupingNode node);
void Visit(RegexConditionalCaptureGroupingNode node);
void Visit(RegexConditionalExpressionGroupingNode node);
void Visit(RegexSimpleEscapeNode node);
void Visit(RegexAnchorEscapeNode node);
void Visit(RegexCharacterClassEscapeNode node);
void Visit(RegexControlEscapeNode node);
void Visit(RegexHexEscapeNode node);
void Visit(RegexUnicodeEscapeNode node);
void Visit(RegexCaptureEscapeNode node);
void Visit(RegexKCaptureEscapeNode node);
void Visit(RegexOctalEscapeNode node);
void Visit(RegexBackreferenceEscapeNode node);
void Visit(RegexCategoryEscapeNode node);
}
}
| // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace Microsoft.CodeAnalysis.EmbeddedLanguages.RegularExpressions
{
internal interface IRegexNodeVisitor
{
void Visit(RegexCompilationUnit node);
void Visit(RegexSequenceNode node);
void Visit(RegexTextNode node);
void Visit(RegexCharacterClassNode node);
void Visit(RegexNegatedCharacterClassNode node);
void Visit(RegexCharacterClassRangeNode node);
void Visit(RegexCharacterClassSubtractionNode node);
void Visit(RegexPosixPropertyNode node);
void Visit(RegexWildcardNode node);
void Visit(RegexZeroOrMoreQuantifierNode node);
void Visit(RegexOneOrMoreQuantifierNode node);
void Visit(RegexZeroOrOneQuantifierNode node);
void Visit(RegexLazyQuantifierNode node);
void Visit(RegexExactNumericQuantifierNode node);
void Visit(RegexOpenNumericRangeQuantifierNode node);
void Visit(RegexClosedNumericRangeQuantifierNode node);
void Visit(RegexAnchorNode node);
void Visit(RegexAlternationNode node);
void Visit(RegexSimpleGroupingNode node);
void Visit(RegexSimpleOptionsGroupingNode node);
void Visit(RegexNestedOptionsGroupingNode node);
void Visit(RegexNonCapturingGroupingNode node);
void Visit(RegexPositiveLookaheadGroupingNode node);
void Visit(RegexNegativeLookaheadGroupingNode node);
void Visit(RegexPositiveLookbehindGroupingNode node);
void Visit(RegexNegativeLookbehindGroupingNode node);
void Visit(RegexNonBacktrackingGroupingNode node);
void Visit(RegexCaptureGroupingNode node);
void Visit(RegexBalancingGroupingNode node);
void Visit(RegexConditionalCaptureGroupingNode node);
void Visit(RegexConditionalExpressionGroupingNode node);
void Visit(RegexSimpleEscapeNode node);
void Visit(RegexAnchorEscapeNode node);
void Visit(RegexCharacterClassEscapeNode node);
void Visit(RegexControlEscapeNode node);
void Visit(RegexHexEscapeNode node);
void Visit(RegexUnicodeEscapeNode node);
void Visit(RegexCaptureEscapeNode node);
void Visit(RegexKCaptureEscapeNode node);
void Visit(RegexOctalEscapeNode node);
void Visit(RegexBackreferenceEscapeNode node);
void Visit(RegexCategoryEscapeNode node);
}
}
| mit | C# |
7c596fb5449141f218f996f58afb0a5a2b31e93e | Add comment | ctripcorp/apollo.net | Apollo/IApolloOptions.cs | Apollo/IApolloOptions.cs | using Com.Ctrip.Framework.Apollo.Enums;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Net.Http;
namespace Com.Ctrip.Framework.Apollo
{
public interface IApolloOptions
{
string AppId { get; }
/// <summary>
/// Get the data center info for the current application.
/// </summary>
/// <returns> the current data center, null if there is no such info. </returns>
string? DataCenter { get; }
/// <summary>
/// Get the cluster name for the current application.
/// </summary>
/// <returns> the cluster name, or "default" if not specified </returns>
string Cluster { get; }
/// <summary>
/// Get the current environment.
/// </summary>
/// <returns> the env </returns>
Env Env { get; }
string LocalIp { get; }
string? MetaServer { get; }
string? Secret { get; }
#if NET40
ReadOnlyCollection<string>? ConfigServer { get; }
#else
IReadOnlyCollection<string>? ConfigServer { get; }
#endif
/// <summary>Load config timeout. ms</summary>
int Timeout { get; }
/// <summary>Refresh interval. ms</summary>
int RefreshInterval { get; }
string? LocalCacheDir { get; }
Func<HttpMessageHandler>? HttpMessageHandlerFactory { get; }
ICacheFileProvider CacheFileProvider { get; }
}
}
| using Com.Ctrip.Framework.Apollo.Enums;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Net.Http;
namespace Com.Ctrip.Framework.Apollo
{
public interface IApolloOptions
{
string AppId { get; }
/// <summary>
/// Get the data center info for the current application.
/// </summary>
/// <returns> the current data center, null if there is no such info. </returns>
string? DataCenter { get; }
/// <summary>
/// Get the cluster name for the current application.
/// </summary>
/// <returns> the cluster name, or "default" if not specified </returns>
string Cluster { get; }
/// <summary>
/// Get the current environment.
/// </summary>
/// <returns> the env </returns>
Env Env { get; }
string LocalIp { get; }
string? MetaServer { get; }
string? Secret { get; }
#if NET40
ReadOnlyCollection<string>? ConfigServer { get; }
#else
IReadOnlyCollection<string>? ConfigServer { get; }
#endif
/// <summary>ms</summary>
int Timeout { get; }
/// <summary>ms</summary>
int RefreshInterval { get; }
string? LocalCacheDir { get; }
Func<HttpMessageHandler>? HttpMessageHandlerFactory { get; }
ICacheFileProvider CacheFileProvider { get; }
}
}
| apache-2.0 | C# |
2b06d7e6d178f347060c9ee47897bf3807da3943 | Add comment. | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi.Backend/Controllers/LegacyController.cs | WalletWasabi.Backend/Controllers/LegacyController.cs | using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace WalletWasabi.Backend.Controllers
{
/// <summary>
/// Provides legacy, never changing API for legacy applications.
/// </summary>
[Produces("application/json")]
public class LegacyController : ControllerBase
{
public LegacyController(BlockchainController blockchainController)
{
BlockchainController = blockchainController;
}
public BlockchainController BlockchainController { get; }
[HttpGet("api/v3/btc/Blockchain/all-fees")]
[ResponseCache(Duration = 300, Location = ResponseCacheLocation.Client)]
public async Task<IActionResult> GetAllFeesV3Async([FromQuery, Required] string estimateSmartFeeMode)
=> await BlockchainController.GetAllFeesAsync(estimateSmartFeeMode);
}
}
| using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace WalletWasabi.Backend.Controllers
{
[Produces("application/json")]
public class LegacyController : ControllerBase
{
public LegacyController(BlockchainController blockchainController)
{
BlockchainController = blockchainController;
}
public BlockchainController BlockchainController { get; }
[HttpGet("api/v3/btc/Blockchain/all-fees")]
[ResponseCache(Duration = 300, Location = ResponseCacheLocation.Client)]
public async Task<IActionResult> GetAllFeesV3Async([FromQuery, Required] string estimateSmartFeeMode)
=> await BlockchainController.GetAllFeesAsync(estimateSmartFeeMode);
}
}
| mit | C# |
e84c79d14051ecb220429c38cdb321e53f9a0b24 | Update osu!direct categories sorting with web changes | 2yangk23/osu,NeoAdonis/osu,NeoAdonis/osu,smoogipoo/osu,ppy/osu,peppy/osu,peppy/osu,ppy/osu,peppy/osu-new,UselessToucan/osu,johnneijzen/osu,johnneijzen/osu,EVAST9919/osu,ZLima12/osu,EVAST9919/osu,peppy/osu,smoogipoo/osu,smoogipooo/osu,UselessToucan/osu,ZLima12/osu,ppy/osu,smoogipoo/osu,2yangk23/osu,NeoAdonis/osu,UselessToucan/osu | osu.Game/Online/API/Requests/SearchBeatmapSetsRequest.cs | osu.Game/Online/API/Requests/SearchBeatmapSetsRequest.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.ComponentModel;
using osu.Game.Overlays;
using osu.Game.Overlays.Direct;
using osu.Game.Rulesets;
namespace osu.Game.Online.API.Requests
{
public class SearchBeatmapSetsRequest : APIRequest<SearchBeatmapSetsResponse>
{
private readonly string query;
private readonly RulesetInfo ruleset;
private readonly BeatmapSearchCategory searchCategory;
private readonly DirectSortCriteria sortCriteria;
private readonly SortDirection direction;
private string directionString => direction == SortDirection.Descending ? @"desc" : @"asc";
public SearchBeatmapSetsRequest(string query, RulesetInfo ruleset, BeatmapSearchCategory searchCategory = BeatmapSearchCategory.Any, DirectSortCriteria sortCriteria = DirectSortCriteria.Ranked, SortDirection direction = SortDirection.Descending)
{
this.query = System.Uri.EscapeDataString(query);
this.ruleset = ruleset;
this.searchCategory = searchCategory;
this.sortCriteria = sortCriteria;
this.direction = direction;
}
// ReSharper disable once ImpureMethodCallOnReadonlyValueField
protected override string Target => $@"beatmapsets/search?q={query}&m={ruleset.ID ?? 0}&s={searchCategory.ToString().ToLowerInvariant()}&sort={sortCriteria.ToString().ToLowerInvariant()}_{directionString}";
}
public enum BeatmapSearchCategory
{
Any,
[Description("Has Leaderboard")]
Leaderboard,
Ranked,
Qualified,
Loved,
Favourites,
[Description("Pending & WIP")]
Pending,
Graveyard,
[Description("My Maps")]
Mine,
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.ComponentModel;
using osu.Game.Overlays;
using osu.Game.Overlays.Direct;
using osu.Game.Rulesets;
namespace osu.Game.Online.API.Requests
{
public class SearchBeatmapSetsRequest : APIRequest<SearchBeatmapSetsResponse>
{
private readonly string query;
private readonly RulesetInfo ruleset;
private readonly BeatmapSearchCategory searchCategory;
private readonly DirectSortCriteria sortCriteria;
private readonly SortDirection direction;
private string directionString => direction == SortDirection.Descending ? @"desc" : @"asc";
public SearchBeatmapSetsRequest(string query, RulesetInfo ruleset, BeatmapSearchCategory searchCategory = BeatmapSearchCategory.Any, DirectSortCriteria sortCriteria = DirectSortCriteria.Ranked, SortDirection direction = SortDirection.Descending)
{
this.query = System.Uri.EscapeDataString(query);
this.ruleset = ruleset;
this.searchCategory = searchCategory;
this.sortCriteria = sortCriteria;
this.direction = direction;
}
// ReSharper disable once ImpureMethodCallOnReadonlyValueField
protected override string Target => $@"beatmapsets/search?q={query}&m={ruleset.ID ?? 0}&s={(int)searchCategory}&sort={sortCriteria.ToString().ToLowerInvariant()}_{directionString}";
}
public enum BeatmapSearchCategory
{
Any = 7,
[Description("Ranked & Approved")]
RankedApproved = 0,
Qualified = 3,
Loved = 8,
Favourites = 2,
[Description("Pending & WIP")]
PendingWIP = 4,
Graveyard = 5,
[Description("My Maps")]
MyMaps = 6,
}
}
| mit | C# |
38a4c841636144d2d46405166d0cf7ee0e62a44f | Load SettingsSubsection in load() | peppy/osu,johnneijzen/osu,ZLima12/osu,Frontear/osuKyzer,smoogipoo/osu,UselessToucan/osu,NeoAdonis/osu,peppy/osu-new,EVAST9919/osu,naoey/osu,naoey/osu,Damnae/osu,Nabile-Rahmani/osu,2yangk23/osu,DrabWeb/osu,NeoAdonis/osu,DrabWeb/osu,smoogipoo/osu,johnneijzen/osu,DrabWeb/osu,peppy/osu,Drezi126/osu,ppy/osu,smoogipooo/osu,peppy/osu,UselessToucan/osu,naoey/osu,EVAST9919/osu,NeoAdonis/osu,ppy/osu,smoogipoo/osu,ppy/osu,2yangk23/osu,ZLima12/osu,UselessToucan/osu | osu.Game/Overlays/Settings/SettingsSubsection.cs | osu.Game/Overlays/Settings/SettingsSubsection.cs | // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using OpenTK;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Graphics.Sprites;
using System.Collections.Generic;
using System.Linq;
using osu.Framework.Allocation;
namespace osu.Game.Overlays.Settings
{
public abstract class SettingsSubsection : FillFlowContainer, IHasFilterableChildren
{
protected override Container<Drawable> Content => FlowContent;
protected readonly FillFlowContainer FlowContent;
protected abstract string Header { get; }
public IEnumerable<IFilterable> FilterableChildren => Children.OfType<IFilterable>();
public string[] FilterTerms => new[] { Header };
public bool MatchingFilter
{
set
{
this.FadeTo(value ? 1 : 0);
}
}
protected SettingsSubsection()
{
RelativeSizeAxes = Axes.X;
AutoSizeAxes = Axes.Y;
Direction = FillDirection.Vertical;
FlowContent = new FillFlowContainer
{
Direction = FillDirection.Vertical,
Spacing = new Vector2(0, 5),
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
};
}
[BackgroundDependencyLoader]
private void load()
{
AddRangeInternal(new Drawable[]
{
new OsuSpriteText
{
Text = Header.ToUpper(),
Margin = new MarginPadding { Bottom = 10 },
Font = @"Exo2.0-Black",
},
FlowContent
});
}
}
}
| // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using OpenTK;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Graphics.Sprites;
using System.Collections.Generic;
using System.Linq;
namespace osu.Game.Overlays.Settings
{
public abstract class SettingsSubsection : FillFlowContainer, IHasFilterableChildren
{
protected override Container<Drawable> Content => content;
private readonly Container<Drawable> content;
protected abstract string Header { get; }
public IEnumerable<IFilterable> FilterableChildren => Children.OfType<IFilterable>();
public string[] FilterTerms => new[] { Header };
public bool MatchingFilter
{
set
{
this.FadeTo(value ? 1 : 0);
}
}
protected SettingsSubsection()
{
RelativeSizeAxes = Axes.X;
AutoSizeAxes = Axes.Y;
Direction = FillDirection.Vertical;
AddRangeInternal(new Drawable[]
{
new OsuSpriteText
{
Text = Header.ToUpper(),
Margin = new MarginPadding { Bottom = 10 },
Font = @"Exo2.0-Black",
},
content = new FillFlowContainer
{
Direction = FillDirection.Vertical,
Spacing = new Vector2(0, 5),
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
},
});
}
}
}
| mit | C# |
d27c8a7c0786f77ed489bc3e82702d974ba67942 | Fix assembly file version (#14484) | jackmagic313/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,yugangw-msft/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,yugangw-msft/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,yugangw-msft/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,markcowl/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net | sdk/sqlmanagement/Microsoft.Azure.Management.SqlManagement/src/Properties/AssemblyInfo.cs | sdk/sqlmanagement/Microsoft.Azure.Management.SqlManagement/src/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
using System;
using System.Resources;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Azure .NET SDK")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCopyright("Copyright (c) Microsoft Corporation")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
[assembly: AssemblyTitle("Microsoft Azure SQL Management Library")]
[assembly: AssemblyDescription("Provides management functionality for Microsoft Azure SQL.")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.44.0.0")]
| using System.Reflection;
using System.Runtime.InteropServices;
using System;
using System.Resources;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Azure .NET SDK")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCopyright("Copyright (c) Microsoft Corporation")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
[assembly: AssemblyTitle("Microsoft Azure SQL Management Library")]
[assembly: AssemblyDescription("Provides management functionality for Microsoft Azure SQL.")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.45.0.0")]
| mit | C# |
c7d398e18c8f6a706d9a65ee560edcbfef79fa3a | Use expression body | bkoelman/roslyn,mavasani/roslyn,TyOverby/roslyn,reaction1989/roslyn,jcouv/roslyn,reaction1989/roslyn,DustinCampbell/roslyn,tvand7093/roslyn,gafter/roslyn,dpoeschl/roslyn,physhi/roslyn,tmat/roslyn,AnthonyDGreen/roslyn,srivatsn/roslyn,mattscheffer/roslyn,srivatsn/roslyn,CyrusNajmabadi/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,panopticoncentral/roslyn,mmitche/roslyn,CyrusNajmabadi/roslyn,yeaicc/roslyn,physhi/roslyn,weltkante/roslyn,bkoelman/roslyn,DustinCampbell/roslyn,jamesqo/roslyn,dotnet/roslyn,nguerrera/roslyn,mmitche/roslyn,lorcanmooney/roslyn,tvand7093/roslyn,tannergooding/roslyn,Giftednewt/roslyn,panopticoncentral/roslyn,heejaechang/roslyn,kelltrick/roslyn,swaroop-sridhar/roslyn,swaroop-sridhar/roslyn,yeaicc/roslyn,heejaechang/roslyn,pdelvo/roslyn,eriawan/roslyn,VSadov/roslyn,genlu/roslyn,MattWindsor91/roslyn,KevinRansom/roslyn,panopticoncentral/roslyn,genlu/roslyn,dotnet/roslyn,sharwell/roslyn,cston/roslyn,AlekseyTs/roslyn,Giftednewt/roslyn,dotnet/roslyn,orthoxerox/roslyn,Hosch250/roslyn,paulvanbrenk/roslyn,jasonmalinowski/roslyn,mavasani/roslyn,abock/roslyn,CaptainHayashi/roslyn,jkotas/roslyn,brettfo/roslyn,mgoertz-msft/roslyn,OmarTawfik/roslyn,gafter/roslyn,khyperia/roslyn,mattscheffer/roslyn,ErikSchierboom/roslyn,khyperia/roslyn,stephentoub/roslyn,stephentoub/roslyn,xasx/roslyn,orthoxerox/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,aelij/roslyn,pdelvo/roslyn,xasx/roslyn,mgoertz-msft/roslyn,davkean/roslyn,shyamnamboodiripad/roslyn,brettfo/roslyn,yeaicc/roslyn,nguerrera/roslyn,dpoeschl/roslyn,weltkante/roslyn,tmat/roslyn,jmarolf/roslyn,shyamnamboodiripad/roslyn,tmeschter/roslyn,jasonmalinowski/roslyn,lorcanmooney/roslyn,jmarolf/roslyn,xasx/roslyn,ErikSchierboom/roslyn,jkotas/roslyn,OmarTawfik/roslyn,gafter/roslyn,shyamnamboodiripad/roslyn,aelij/roslyn,mavasani/roslyn,jamesqo/roslyn,AmadeusW/roslyn,kelltrick/roslyn,dpoeschl/roslyn,Hosch250/roslyn,wvdd007/roslyn,paulvanbrenk/roslyn,KirillOsenkov/roslyn,robinsedlaczek/roslyn,robinsedlaczek/roslyn,mgoertz-msft/roslyn,swaroop-sridhar/roslyn,bartdesmet/roslyn,KirillOsenkov/roslyn,mattscheffer/roslyn,diryboy/roslyn,MichalStrehovsky/roslyn,jamesqo/roslyn,jmarolf/roslyn,weltkante/roslyn,KevinRansom/roslyn,agocke/roslyn,MattWindsor91/roslyn,AnthonyDGreen/roslyn,Hosch250/roslyn,davkean/roslyn,sharwell/roslyn,sharwell/roslyn,pdelvo/roslyn,abock/roslyn,paulvanbrenk/roslyn,nguerrera/roslyn,heejaechang/roslyn,AlekseyTs/roslyn,kelltrick/roslyn,jcouv/roslyn,cston/roslyn,stephentoub/roslyn,mmitche/roslyn,AmadeusW/roslyn,genlu/roslyn,VSadov/roslyn,reaction1989/roslyn,agocke/roslyn,tmeschter/roslyn,MattWindsor91/roslyn,MichalStrehovsky/roslyn,brettfo/roslyn,khyperia/roslyn,TyOverby/roslyn,CaptainHayashi/roslyn,DustinCampbell/roslyn,KirillOsenkov/roslyn,jkotas/roslyn,diryboy/roslyn,agocke/roslyn,eriawan/roslyn,bkoelman/roslyn,bartdesmet/roslyn,CyrusNajmabadi/roslyn,abock/roslyn,TyOverby/roslyn,AmadeusW/roslyn,orthoxerox/roslyn,srivatsn/roslyn,lorcanmooney/roslyn,ErikSchierboom/roslyn,AnthonyDGreen/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,diryboy/roslyn,Giftednewt/roslyn,tmeschter/roslyn,OmarTawfik/roslyn,KevinRansom/roslyn,tvand7093/roslyn,AlekseyTs/roslyn,robinsedlaczek/roslyn,davkean/roslyn,physhi/roslyn,bartdesmet/roslyn,MichalStrehovsky/roslyn,tmat/roslyn,wvdd007/roslyn,cston/roslyn,tannergooding/roslyn,VSadov/roslyn,MattWindsor91/roslyn,wvdd007/roslyn,jcouv/roslyn,tannergooding/roslyn,aelij/roslyn,jasonmalinowski/roslyn,eriawan/roslyn,CaptainHayashi/roslyn | src/EditorFeatures/Core/Implementation/Diagnostics/DiagnosticsSuggestionTaggerProvider.cs | src/EditorFeatures/Core/Implementation/Diagnostics/DiagnosticsSuggestionTaggerProvider.cs | // Copyright (c) Microsoft. 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.Collections.Immutable;
using System.ComponentModel.Composition;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.Shared.Options;
using Microsoft.CodeAnalysis.Editor.Shared.Tagging;
using Microsoft.CodeAnalysis.Editor.Tagging;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Options;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Adornments;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.VisualStudio.Text.Tagging;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.Diagnostics
{
[Export(typeof(ITaggerProvider))]
[ContentType(ContentTypeNames.RoslynContentType)]
[ContentType(ContentTypeNames.XamlContentType)]
[TagType(typeof(IErrorTag))]
internal partial class DiagnosticsSuggestionTaggerProvider :
AbstractDiagnosticsAdornmentTaggerProvider<IErrorTag>
{
private static readonly IEnumerable<Option<bool>> s_tagSourceOptions =
ImmutableArray.Create(EditorComponentOnOffOptions.Tagger, InternalFeatureOnOffOptions.Squiggles, ServiceComponentOnOffOptions.DiagnosticProvider);
protected internal override IEnumerable<Option<bool>> Options => s_tagSourceOptions;
[ImportingConstructor]
public DiagnosticsSuggestionTaggerProvider(
IEditorFormatMapService editorFormatMapService,
IDiagnosticService diagnosticService,
IForegroundNotificationService notificationService,
[ImportMany] IEnumerable<Lazy<IAsynchronousOperationListener, FeatureMetadata>> listeners)
: base(diagnosticService, notificationService, listeners)
{
}
protected internal override bool IncludeDiagnostic(DiagnosticData diagnostic)
{
return diagnostic.Severity == DiagnosticSeverity.Info;
}
protected override IErrorTag CreateTag(DiagnosticData diagnostic) =>
new ErrorTag(PredefinedErrorTypeNames.HintedSuggestion, diagnostic.Message);
protected override SnapshotSpan AdjustSnapshotSpan(SnapshotSpan snapshotSpan, int minimumLength)
{
// We always want suggestion tags to be two characters long.
return base.AdjustSnapshotSpan(snapshotSpan, minimumLength: 2, maximumLength: 2);
}
}
} | // Copyright (c) Microsoft. 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.Collections.Immutable;
using System.ComponentModel.Composition;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.Shared.Options;
using Microsoft.CodeAnalysis.Editor.Shared.Tagging;
using Microsoft.CodeAnalysis.Editor.Tagging;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Options;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Adornments;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.VisualStudio.Text.Tagging;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.Diagnostics
{
[Export(typeof(ITaggerProvider))]
[ContentType(ContentTypeNames.RoslynContentType)]
[ContentType(ContentTypeNames.XamlContentType)]
[TagType(typeof(IErrorTag))]
internal partial class DiagnosticsSuggestionTaggerProvider :
AbstractDiagnosticsAdornmentTaggerProvider<IErrorTag>
{
private static readonly IEnumerable<Option<bool>> s_tagSourceOptions =
ImmutableArray.Create(EditorComponentOnOffOptions.Tagger, InternalFeatureOnOffOptions.Squiggles, ServiceComponentOnOffOptions.DiagnosticProvider);
protected internal override IEnumerable<Option<bool>> Options => s_tagSourceOptions;
[ImportingConstructor]
public DiagnosticsSuggestionTaggerProvider(
IEditorFormatMapService editorFormatMapService,
IDiagnosticService diagnosticService,
IForegroundNotificationService notificationService,
[ImportMany] IEnumerable<Lazy<IAsynchronousOperationListener, FeatureMetadata>> listeners)
: base(diagnosticService, notificationService, listeners)
{
}
protected internal override bool IncludeDiagnostic(DiagnosticData diagnostic)
{
return diagnostic.Severity == DiagnosticSeverity.Info;
}
protected override IErrorTag CreateTag(DiagnosticData diagnostic)
{
return new ErrorTag(PredefinedErrorTypeNames.HintedSuggestion, diagnostic.Message);
}
protected override SnapshotSpan AdjustSnapshotSpan(SnapshotSpan snapshotSpan, int minimumLength)
{
// We always want suggestion tags to be two characters long.
return base.AdjustSnapshotSpan(snapshotSpan, minimumLength: 2, maximumLength: 2);
}
}
} | mit | C# |
9f3793bd2db01fd46b48b877536c434a342c03c4 | Use proper path for settings file | naveedaz/azure-powershell,naveedaz/azure-powershell,devigned/azure-powershell,naveedaz/azure-powershell,naveedaz/azure-powershell,devigned/azure-powershell,naveedaz/azure-powershell,devigned/azure-powershell,devigned/azure-powershell,AzureAutomationTeam/azure-powershell,AzureAutomationTeam/azure-powershell,devigned/azure-powershell,ClogenyTechnologies/azure-powershell,AzureAutomationTeam/azure-powershell,AzureAutomationTeam/azure-powershell,AzureAutomationTeam/azure-powershell,ClogenyTechnologies/azure-powershell,naveedaz/azure-powershell,ClogenyTechnologies/azure-powershell,ClogenyTechnologies/azure-powershell,ClogenyTechnologies/azure-powershell,AzureAutomationTeam/azure-powershell,devigned/azure-powershell | src/ResourceManager/DataMigration/Commands.DataMigration.Test/DataMigrationAppSettings.cs | src/ResourceManager/DataMigration/Commands.DataMigration.Test/DataMigrationAppSettings.cs | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="DataMigrationAppSettings.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.IO;
namespace Microsoft.Azure.Commands.DataMigration.Test
{
public class DataMigrationAppSettings
{
private static volatile DataMigrationAppSettings instance;
private string configFileName = "appsettings.json";
private static object lockObj = new Object();
private JObject config;
private DataMigrationAppSettings() { }
public static DataMigrationAppSettings Instance
{
get
{
if (instance == null)
{
lock (lockObj)
{
if (instance == null)
{
instance = new DataMigrationAppSettings();
instance.LoadConfigFile();
}
}
}
return instance;
}
}
private void LoadConfigFile()
{
string fullFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, configFileName);
if (!File.Exists(fullFilePath))
{
instance = null;
throw new FileNotFoundException("appsettings.json File Not Found");
}
config = (JObject)JsonConvert.DeserializeObject(File.ReadAllText(fullFilePath));
}
public string GetValue(string configName)
{
string value = (string) config[configName];
if (string.IsNullOrEmpty(value))
{
string message = "Cannot not find config : " + configName;
throw new ArgumentException(message);
}
return value;
}
}
}
| // --------------------------------------------------------------------------------------------------------------------
// <copyright file="DataMigrationAppSettings.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.IO;
namespace Microsoft.Azure.Commands.DataMigration.Test
{
public class DataMigrationAppSettings
{
private static volatile DataMigrationAppSettings instance;
private string configFileName = "appsettings.json";
private static object lockObj = new Object();
private JObject config;
private DataMigrationAppSettings() { }
public static DataMigrationAppSettings Instance
{
get
{
if (instance == null)
{
lock (lockObj)
{
if (instance == null)
{
instance = new DataMigrationAppSettings();
instance.LoadConfigFile();
}
}
}
return instance;
}
}
private void LoadConfigFile()
{
string path = Directory.GetCurrentDirectory();
string fullFilePath = Path.Combine(path, configFileName);
if (!File.Exists(fullFilePath))
{
// Because of File.Delete doesn't throw any exception in case file not found
throw new FileNotFoundException("appsettings.json File Not Found");
}
config = (JObject)JsonConvert.DeserializeObject(File.ReadAllText(fullFilePath));
}
public string GetValue(string configName)
{
string value = (string) config[configName];
if (string.IsNullOrEmpty(value))
{
string message = "Cannot not find config : " + configName;
throw new ArgumentException(message);
}
return value;
}
}
}
| apache-2.0 | C# |
93fed1a6e60489f5cad9d59e6ed801655bfd1308 | Update IDisjointIntervalSet.cs | marsop/ephemeral | Interfaces/IDisjointIntervalSet.cs | Interfaces/IDisjointIntervalSet.cs | using System;
using System.Collections.Generic;
namespace ephemeral
{
/// <summary>
/// Collection of disjoint IIntervals
/// </summary>
public interface IDisjointIntervalSet : IList<IInterval>
{
/// <summary>
/// True if all the contained intervals are contiguous or if empty
/// </summary>
bool IsContiguous { get; }
/// <summary>
/// Sum of durations of each of the enclosed intervals
/// </summary>
TimeSpan AggregatedDuration { get; }
/// <summary>
/// Start of the first contained Interval
/// </summary>
DateTimeOffset Start { get; }
/// <summary>
/// End of the last contained Interval
/// </summary>
DateTimeOffset End { get; }
bool StartIncluded { get; }
bool EndIncluded { get; }
}
}
| using System;
using System.Collections.Generic;
namespace ephemeral
{
/// <summary>
/// Collection of disjoint IIntervals
/// </summary>
public interface IDisjointIntervalSet : IList<IInterval>
{
/// <summary>
/// True if all the contained intervals are contiguous or if empty
/// </summary>
bool IsContiguous { get; }
/// <summary>
/// Sum of durations of each of the enclosed intervals
/// </summary>
TimeSpan AggregatedDuration { get; }
/// <summary>
/// Start of the first contained Interval
/// </summary>
DateTimeOffset Start { get; }
/// <summary>
/// End of the last contained Interval
/// </summary>
DateTimeOffset End { get; }
}
}
| mit | C# |
a953db45e5a08d0f811c46b25f26727268347484 | fix unbreakable space | laedit/ReadingList,laedit/ReadingList | site/_plugins/DateJustifyFilter.csx | site/_plugins/DateJustifyFilter.csx | public class DateJustifyFilter : IFilter
{
public string Name
{
get { return "DateJustify"; }
}
public static string DateJustify(DateTime input)
{
var day = input.ToString("dd");
var year = input.ToString("yy");
var month = input.ToString("MMM").PadRight(5, ' '); // unbreakable space
return day + " " + month + " " + year;
}
} | public class DateJustifyFilter : IFilter
{
public string Name
{
get { return "DateJustify"; }
}
public static string DateJustify(DateTime input)
{
var day = input.ToString("dd");
var year = input.ToString("yy");
var month = input.ToString("MMM").PadRight(5, ' '); // unbreakable space
return day + " " + month + " " + year;
}
} | apache-2.0 | C# |
ef6d4ab2ab672e67f3e788d0b8ce95d2a3e18710 | Update appCore.cs | dottools/Torque2D,dottools/Torque2D,dottools/Torque2D,dottools/Torque2D,dottools/Torque2D,dottools/Torque2D,dottools/Torque2D,dottools/Torque2D,dottools/Torque2D,dottools/Torque2D | library/AppCore/appCore.cs | library/AppCore/appCore.cs | //-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// 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.
//-----------------------------------------------------------------------------
function AppCore::create( %this )
{
// Load system scripts
exec("./scripts/constants.cs");
exec("./scripts/defaultPreferences.cs");
exec("./gui/guiProfiles.cs");
%this.createGuiProfiles();
exec("./scripts/canvas.cs");
// Initialize the canvas
%module = ModuleDatabase.findModule("AppCore", 1);
%this.initializeCanvas(%module.Project);
// Load other modules
ModuleDatabase.loadGroup("launch");
}
//-----------------------------------------------------------------------------
function AppCore::destroy( %this )
{
}
| //-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// 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.
//-----------------------------------------------------------------------------
function AppCore::create( %this )
{
// Load system scripts
exec("./scripts/constants.cs");
exec("./scripts/defaultPreferences.cs");
exec("./gui/guiProfiles.cs");
%this.createGuiProfiles();
exec("./scripts/canvas.cs");
// Initialize the canvas
%this.initializeCanvas(%this.Project);
// Load other modules
ModuleDatabase.loadGroup("launch");
}
//-----------------------------------------------------------------------------
function AppCore::destroy( %this )
{
}
| mit | C# |
46f10b392dfbb0f0adc1fca88222d43ce09b758e | Fix merge errors | Nabile-Rahmani/osu,ppy/osu,ZLima12/osu,2yangk23/osu,ZLima12/osu,Frontear/osuKyzer,smoogipoo/osu,UselessToucan/osu,NeoAdonis/osu,EVAST9919/osu,smoogipoo/osu,NeoAdonis/osu,NeoAdonis/osu,UselessToucan/osu,UselessToucan/osu,DrabWeb/osu,johnneijzen/osu,peppy/osu,ppy/osu,naoey/osu,2yangk23/osu,EVAST9919/osu,naoey/osu,ppy/osu,peppy/osu,naoey/osu,DrabWeb/osu,smoogipooo/osu,smoogipoo/osu,johnneijzen/osu,peppy/osu-new,peppy/osu,DrabWeb/osu | osu.Game.Tests/Visual/TestCaseEditorCompose.cs | osu.Game.Tests/Visual/TestCaseEditorCompose.cs | // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using System.Collections.Generic;
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Timing;
using osu.Game.Rulesets.Osu;
using osu.Game.Screens.Edit.Screens.Compose;
using osu.Game.Tests.Beatmaps;
namespace osu.Game.Tests.Visual
{
[TestFixture]
public class TestCaseEditorCompose : OsuTestCase
{
public override IReadOnlyList<Type> RequiredTypes => new[] { typeof(Compose) };
private DependencyContainer dependencies;
protected override IReadOnlyDependencyContainer CreateLocalDependencies(IReadOnlyDependencyContainer parent)
=> dependencies = new DependencyContainer(parent);
[BackgroundDependencyLoader]
private void load(OsuGameBase osuGame)
{
osuGame.Beatmap.Value = new TestWorkingBeatmap(new OsuRuleset().RulesetInfo);
var clock = new DecoupleableInterpolatingFramedClock { IsCoupled = false };
dependencies.CacheAs<IAdjustableClock>(clock);
dependencies.CacheAs<IFrameBasedClock>(clock);
var compose = new Compose();
compose.Beatmap.BindTo(osuGame.Beatmap);
Child = compose;
}
}
}
| // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using System.Collections.Generic;
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Timing;
using osu.Game.Rulesets.Osu;
using osu.Game.Screens.Edit.Screens.Compose;
using osu.Game.Tests.Beatmaps;
namespace osu.Game.Tests.Visual
{
[TestFixture]
public class TestCaseEditorCompose : OsuTestCase
{
public override IReadOnlyList<Type> RequiredTypes => new[] { typeof(Compose) };
private DependencyContainer dependencies;
protected override IReadOnlyDependencyContainer CreateLocalDependencies(IReadOnlyDependencyContainer parent)
=> dependencies = new DependencyContainer(parent);
[BackgroundDependencyLoader]
private void load(OsuGameBase osuGame)
{
osuGame.Beatmap.Value = new TestWorkingBeatmap(new OsuRuleset().RulesetInfo);
var clock = new DecoupleableInterpolatingFramedClock { IsCoupled = false };
dependencies.CacheAs<IAdjustableClock>(clock);
dependencies.CacheAs<IFrameBasedClock>(clock);
var compose = new Compose();
compose.Beatmap.BindTo(osuGame.Beatmap);
Child = compose;
}
}
}
| mit | C# |
64fda5c6b4195f21ce7cccce5058a082ab10b2d9 | Add FromString and FromFile | yishn/GTPWrapper | GTPWrapper/Sgf/GameTree.cs | GTPWrapper/Sgf/GameTree.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Drawing;
using System.Diagnostics;
using GTPWrapper.DataTypes;
namespace GTPWrapper.Sgf {
/// <summary>
/// Represents a SGF game tree.
/// </summary>
public class GameTree : ListTree<Node> {
/// <summary>
/// Initializes a new instance of the GameTree class.
/// </summary>
public GameTree() : base() { }
/// <summary>
/// Initializes a new instance of the GameTree class with the given node list.
/// </summary>
/// <param name="list"></param>
public GameTree(List<Node> list) : base(list) { }
/// <summary>
/// Returns a string which represents the object.
/// </summary>
public override string ToString() {
return string.Join("\n", this.Elements) + (this.Elements.Count == 0 || this.SubTrees.Count == 0 ? "" : "\n") +
(this.SubTrees.Count == 0 ? "" : "(" + string.Join(")\n(", this.SubTrees) + ")");
}
/// <summary>
/// Creates a GameTree from the given string.
/// </summary>
/// <param name="input">The input string.</param>
public static GameTree FromString(string input) {
var tokens = SgfParser.Tokenize(input).ToList();
return SgfParser.Parse(tokens);
}
/// <summary>
/// Creates a GameTree from the specified file.
/// </summary>
/// <param name="path">The path of the file.</param>
public static GameTree FromFile(string path) {
string input = File.ReadAllText(path);
return GameTree.FromString(input);
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Drawing;
using System.Diagnostics;
using GTPWrapper.DataTypes;
namespace GTPWrapper.Sgf {
/// <summary>
/// Represents a SGF game tree.
/// </summary>
public class GameTree : ListTree<Node> {
/// <summary>
/// Initializes a new instance of the GameTree class.
/// </summary>
public GameTree() : base() { }
/// <summary>
/// Initializes a new instance of the GameTree class with the given node list.
/// </summary>
/// <param name="list"></param>
public GameTree(List<Node> list) : base(list) { }
/// <summary>
/// Returns a string which represents the object.
/// </summary>
public override string ToString() {
return string.Join("\n", this.Elements) + (this.Elements.Count == 0 || this.SubTrees.Count == 0 ? "" : "\n") +
(this.SubTrees.Count == 0 ? "" : "(" + string.Join(")\n(", this.SubTrees) + ")");
}
}
} | mit | C# |
4bbe58a2f6c94bcb9b1085452d0070f25db36bc7 | add a retry policy around queue and hangfire initialization | lehmamic/columbus,lehmamic/columbus | Diskordia.Columbus.BackgroundWorker/Startup.cs | Diskordia.Columbus.BackgroundWorker/Startup.cs | using System;
using AutoMapper;
using Diskordia.Columbus.BackgroundWorker.Services;
using Diskordia.Columbus.Bots;
using Diskordia.Columbus.Bots.FareDeals;
using Diskordia.Columbus.Common;
using Diskordia.Columbus.Staging;
using Diskordia.Columbus.Staging.FareDeals;
using Hangfire;
using Hangfire.Mongo;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Polly;
using Rebus.Config;
using Rebus.ServiceProvider;
namespace Diskordia.Columbus.BackgroundWorker
{
public class Startup
{
public Startup(IConfiguration configuration)
{
if(configuration == null)
{
throw new ArgumentNullException(nameof(configuration));
}
this.Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddOptions();
services.AddAutoMapper(opt => opt.AddProfiles(
new []
{
typeof(StagingExtensions).Assembly
}));
services.AddFareDealStaging(Configuration);
services.AddFareDealBots(Configuration);
services.AddSingleton<IFareDealScanProxy, FareDealScanProxy>();
services.AutoRegisterHandlersFromAssemblyOf<FareDealBotsHandler>();
services.AutoRegisterHandlersFromAssemblyOf<FareDealScanResultHandler>();
var serviceBusOptions = this.Configuration.GetSection("ServiceBus").Get<ServiceBusOptions>();
services.AddRebus(config => config.Transport(t => t.UseRabbitMq(serviceBusOptions.ConnectionString, serviceBusOptions.QueueName)));
var hangfireOptions = this.Configuration.GetSection("HangFire").Get<MongoDbOptions>();
services.AddHangfire(config =>
{
config.UseMongoStorage(hangfireOptions.ConnectionString, hangfireOptions.Database);
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
var policy = Policy.Handle<Exception>()
.WaitAndRetry(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)));
policy.Execute(() => app.UseRebus());
policy.Execute(() =>
{
app.UseHangfireServer();
app.UseHangfireDashboard(options: new DashboardOptions
{
Authorization = new [] { new DisableHangfireDashboardAuthorizationFilter() }
});
});
var fareDealScanOptions = this.Configuration.GetSection("FareDealScan").Get<FareDealScanOptions>();
var fareDealsBotsProxy = app.ApplicationServices.GetService<IFareDealScanProxy>();
RecurringJob.AddOrUpdate("Trigger-FareDealsScan", () => fareDealsBotsProxy.TriggerFareDealsScan(), fareDealScanOptions.ScheduleCronExpression);
}
}
}
| using System;
using AutoMapper;
using Diskordia.Columbus.BackgroundWorker.Services;
using Diskordia.Columbus.Bots;
using Diskordia.Columbus.Bots.FareDeals;
using Diskordia.Columbus.Common;
using Diskordia.Columbus.Staging;
using Diskordia.Columbus.Staging.FareDeals;
using Hangfire;
using Hangfire.Mongo;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Polly;
using Rebus.Config;
using Rebus.ServiceProvider;
namespace Diskordia.Columbus.BackgroundWorker
{
public class Startup
{
public Startup(IConfiguration configuration)
{
if(configuration == null)
{
throw new ArgumentNullException(nameof(configuration));
}
this.Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddOptions();
services.AddAutoMapper(opt => opt.AddProfiles(
new []
{
typeof(StagingExtensions).Assembly
}));
services.AddFareDealStaging(Configuration);
services.AddFareDealBots(Configuration);
services.AddSingleton<IFareDealScanProxy, FareDealScanProxy>();
services.AutoRegisterHandlersFromAssemblyOf<FareDealBotsHandler>();
services.AutoRegisterHandlersFromAssemblyOf<FareDealScanResultHandler>();
var serviceBusOptions = this.Configuration.GetSection("ServiceBus").Get<ServiceBusOptions>();
services.AddRebus(config => config.Transport(t => t.UseRabbitMq(serviceBusOptions.ConnectionString, serviceBusOptions.QueueName)));
var hangfireOptions = this.Configuration.GetSection("HangFire").Get<MongoDbOptions>();
services.AddHangfire(config =>
{
config.UseMongoStorage(hangfireOptions.ConnectionString, hangfireOptions.Database);
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
var policy = Policy.Handle<Exception>()
.WaitAndRetry(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)));
policy.Execute(() => app.UseRebus());
policy.Execute(() =>
{
app.UseHangfireServer();
app.UseHangfireDashboard(options: new DashboardOptions
{
Authorization = new [] { new DisableHangfireDashboardAuthorizationFilter() }
});
});
var fareDealScanOptions = this.Configuration.GetSection("FareDealScan").Get<FareDealScanOptions>();
var fareDealsBotsProxy = app.ApplicationServices.GetService<IFareDealScanProxy>();
RecurringJob.AddOrUpdate("Trigger-FareDealsScan", () => fareDealsBotsProxy.TriggerFareDealsScan(), fareDealScanOptions.ScheduleCronExpression);
// RecurringJob.Trigger("Trigger-FareDealsScan");
}
}
}
| mit | C# |
6ac93989c448c478ccad30753d0e9960aed12a51 | Update demo | sunkaixuan/SqlSugar | Src/Asp.Net/SqlServerTest/Program.cs | Src/Asp.Net/SqlServerTest/Program.cs | using OrmTest.PerformanceTesting;
using OrmTest.UnitTest;
using System;
namespace OrmTest
{
class Program
{
/// <summary>
/// Set up config.cs file and start directly F5
/// 设置Config.cs文件直接F5启动例子
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
//Demo
Demo0_SqlSugarClient.Init();
Demo1_Queryable.Init();
Demo2_Updateable.Init();
Demo3_Insertable.Init();
Demo4_Deleteable.Init();
Demo5_SqlQueryable.Init();
Demo6_Queue.Init();
Demo7_Ado.Init();
Demo8_Saveable.Init();
Demo9_EntityMain.Init();
DemoA_DbMain.Init();
DemoB_Aop.Init();
DemoC_GobalFilter.Init();
DemoD_DbFirst.Init();;
DemoE_CodeFirst.Init();
DemoF_Utilities.Init();
DemoG_SimpleClient.Init();
//Unit test
//NewUnitTest.Init();
//Rest Data
NewUnitTest.RestData();
Console.WriteLine("all successfully.");
Console.ReadKey();
}
}
}
| using OrmTest.PerformanceTesting;
using OrmTest.UnitTest;
using System;
namespace OrmTest
{
class Program
{
/// <summary>
/// Set up config.cs file and start directly F5
/// 设置Config.cs文件直接F5启动例子
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
//Demo
Demo0_SqlSugarClient.Init();
Demo1_Queryable.Init();
Demo2_Updateable.Init();
Demo3_Insertable.Init();
Demo4_Deleteable.Init();
Demo5_SqlQueryable.Init();
Demo6_Queue.Init();
Demo7_Ado.Init();
Demo8_Saveable.Init();
Demo9_EntityMain.Init();
DemoA_DbMain.Init();
DemoB_Aop.Init();
DemoC_GobalFilter.Init();
DemoD_DbFirst.Init();;
DemoE_CodeFirst.Init();
DemoF_Utilities.Init();
DemoG_SimpleClient.Init();
//Unit test
NewUnitTest.Init();
//Rest Data
NewUnitTest.RestData();
Console.WriteLine("all successfully.");
Console.ReadKey();
}
}
}
| apache-2.0 | C# |
3cdc39ac10d329e674f38b8ac8c5cb53b421ec95 | add filtered metrics implementation | mnadel/Metrics.NET,alhardy/Metrics.NET,Liwoj/Metrics.NET,DeonHeyns/Metrics.NET,huoxudong125/Metrics.NET,alhardy/Metrics.NET,mnadel/Metrics.NET,cvent/Metrics.NET,ntent-ad/Metrics.NET,cvent/Metrics.NET,etishor/Metrics.NET,Recognos/Metrics.NET,Recognos/Metrics.NET,MetaG8/Metrics.NET,MetaG8/Metrics.NET,MetaG8/Metrics.NET,DeonHeyns/Metrics.NET,huoxudong125/Metrics.NET,ntent-ad/Metrics.NET,Liwoj/Metrics.NET,etishor/Metrics.NET | Src/Metrics/MetricsDataProvider.cs | Src/Metrics/MetricsDataProvider.cs |
namespace Metrics
{
/// <summary>
/// A provider capable of returning the current values for a set of metrics
/// </summary>
public interface MetricsDataProvider : Utils.IHideObjectMembers
{
/// <summary>
/// Returns the current metrics data for the context for which this provider has been created.
/// </summary>
MetricsData CurrentMetricsData { get; }
}
public sealed class FilteredMetrics : MetricsDataProvider
{
private readonly MetricsDataProvider provider;
private readonly MetricsFilter filter;
public FilteredMetrics(MetricsDataProvider provider, MetricsFilter filter)
{
this.provider = provider;
this.filter = filter;
}
public MetricsData CurrentMetricsData
{
get
{
return this.provider.CurrentMetricsData.Filter(this.filter);
}
}
}
public static class FilteredMetricsExtensions
{
public static MetricsDataProvider WithFilter(this MetricsDataProvider provider, MetricsFilter filter)
{
return new FilteredMetrics(provider, filter);
}
}
}
|
namespace Metrics
{
/// <summary>
/// A provider capable of returning the current values for a set of metrics
/// </summary>
public interface MetricsDataProvider : Utils.IHideObjectMembers
{
/// <summary>
/// Returns the current metrics data for the context for which this provider has been created.
/// </summary>
MetricsData CurrentMetricsData { get; }
}
}
| apache-2.0 | C# |
fb5fa195ee372cbfe97028e47fe6439374c7fc7f | Mark EndOfStreamException type with the RelocatedType attribute to cater for its currently forked locations in different runtimes (System.IO vs. System.Private.Corelib) | yizhang82/corert,shrah/corert,yizhang82/corert,gregkalapos/corert,tijoytom/corert,tijoytom/corert,sandreenko/corert,sandreenko/corert,yizhang82/corert,shrah/corert,gregkalapos/corert,sandreenko/corert,botaberg/corert,tijoytom/corert,gregkalapos/corert,gregkalapos/corert,botaberg/corert,krytarowski/corert,yizhang82/corert,krytarowski/corert,botaberg/corert,shrah/corert,botaberg/corert,sandreenko/corert,krytarowski/corert,krytarowski/corert,shrah/corert,tijoytom/corert | src/System.Private.CoreLib/src/System/IO/EndOfStreamException.cs | src/System.Private.CoreLib/src/System/IO/EndOfStreamException.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Internal.Runtime.CompilerServices;
using System.Runtime.Serialization;
namespace System.IO
{
[RelocatedType("System.IO")]
[RelocatedType("System.Runtime.Extensions")]
[Serializable]
public class EndOfStreamException : IOException
{
public EndOfStreamException()
: base(SR.Arg_EndOfStreamException)
{
HResult = __HResults.COR_E_ENDOFSTREAM;
}
public EndOfStreamException(string message)
: base(message)
{
HResult = __HResults.COR_E_ENDOFSTREAM;
}
public EndOfStreamException(string message, Exception innerException)
: base(message, innerException)
{
HResult = __HResults.COR_E_ENDOFSTREAM;
}
protected EndOfStreamException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.Serialization;
namespace System.IO
{
[Serializable]
public class EndOfStreamException : IOException
{
public EndOfStreamException()
: base(SR.Arg_EndOfStreamException)
{
HResult = __HResults.COR_E_ENDOFSTREAM;
}
public EndOfStreamException(string message)
: base(message)
{
HResult = __HResults.COR_E_ENDOFSTREAM;
}
public EndOfStreamException(string message, Exception innerException)
: base(message, innerException)
{
HResult = __HResults.COR_E_ENDOFSTREAM;
}
protected EndOfStreamException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}
| mit | C# |
b77bd08925461bcbd8b24129570c8cdae17c6fc0 | Simplify null values handling | NeoAdonis/osu,smoogipoo/osu,ppy/osu,smoogipoo/osu,smoogipooo/osu,NeoAdonis/osu,peppy/osu-new,UselessToucan/osu,peppy/osu,UselessToucan/osu,ppy/osu,UselessToucan/osu,peppy/osu,peppy/osu,NeoAdonis/osu,ppy/osu,smoogipoo/osu | osu.Game/Overlays/Profile/Sections/Historical/UserHistoryGraph.cs | osu.Game/Overlays/Profile/Sections/Historical/UserHistoryGraph.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Linq;
using static osu.Game.Users.User;
namespace osu.Game.Overlays.Profile.Sections.Historical
{
public abstract class UserHistoryGraph : UserGraph<DateTime, long>
{
public UserHistoryCount[] Values
{
set => Data = value?.Select(v => new KeyValuePair<DateTime, long>(v.Date, v.Count)).ToArray();
}
protected override float GetDataPointHeight(long playCount) => playCount;
protected override object GetTooltipContent(DateTime date, long playCount)
{
return new TooltipDisplayContent
{
Count = playCount.ToString("N0"),
Date = date.ToString("MMMM yyyy")
};
}
protected abstract class HistoryGraphTooltip : UserGraphTooltip
{
public override bool SetContent(object content)
{
if (!(content is TooltipDisplayContent info))
return false;
Counter.Text = info.Count;
BottomText.Text = info.Date;
return true;
}
}
private class TooltipDisplayContent
{
public string Count;
public string Date;
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Linq;
using static osu.Game.Users.User;
namespace osu.Game.Overlays.Profile.Sections.Historical
{
public abstract class UserHistoryGraph : UserGraph<DateTime, long>
{
public UserHistoryCount[] Values
{
set
{
if (value == null)
{
Data = null;
return;
}
Data = value.Select(v => new KeyValuePair<DateTime, long>(v.Date, v.Count)).ToArray();
}
}
protected override float GetDataPointHeight(long playCount) => playCount;
protected override object GetTooltipContent(DateTime date, long playCount)
{
return new TooltipDisplayContent
{
Count = playCount.ToString("N0"),
Date = date.ToString("MMMM yyyy")
};
}
protected abstract class HistoryGraphTooltip : UserGraphTooltip
{
public override bool SetContent(object content)
{
if (!(content is TooltipDisplayContent info))
return false;
Counter.Text = info.Count;
BottomText.Text = info.Date;
return true;
}
}
private class TooltipDisplayContent
{
public string Count;
public string Date;
}
}
}
| mit | C# |
905872b84c61363989be97466014a4ce59780420 | fix for broadcast messages | KryptPad/KryptPadWebsite,KryptPad/KryptPadWebsite,KryptPad/KryptPadWebsite | KryptPadWebApp/Controllers/AppAPIController.cs | KryptPadWebApp/Controllers/AppAPIController.cs | using KryptPadWebApp.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace KryptPadWebApp.Controllers
{
[RoutePrefix("api/app")]
public class AppAPIController : ApiController
{
/// <summary>
/// Gets the system broadcast message
/// </summary>
/// <returns></returns>
[HttpGet]
[Route("broadcast-message")]
public HttpResponseMessage GetBroadcastMessage()
{
using (var ctx = new ApplicationDbContext())
{
var appSettings = ctx.AppSettings.FirstOrDefault();
if (appSettings != null)
{
// Get the broadcast message and return it
if (!string.IsNullOrWhiteSpace(appSettings.BroadcastMessage))
{
var resp = new HttpResponseMessage(HttpStatusCode.OK);
resp.Content = new StringContent(appSettings.BroadcastMessage, System.Text.Encoding.UTF8, "text/plain");
return resp;
}
}
}
// Nothing to show here
return new HttpResponseMessage(HttpStatusCode.NoContent);
}
}
}
| using KryptPadWebApp.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace KryptPadWebApp.Controllers
{
[RoutePrefix("api/app")]
public class AppAPIController : ApiController
{
/// <summary>
/// Gets the system broadcast message
/// </summary>
/// <returns></returns>
[HttpGet]
[Route("broadcast-message")]
public IHttpActionResult GetBroadcastMessage()
{
using (var ctx = new ApplicationDbContext())
{
var appSettings = ctx.AppSettings.FirstOrDefault();
if (appSettings != null)
{
// Get the broadcast message and return it
if (!string.IsNullOrWhiteSpace(appSettings.BroadcastMessage))
{
return Ok(appSettings.BroadcastMessage);
}
}
}
// Nothing to show here
return StatusCode(HttpStatusCode.NoContent);
}
}
}
| mit | C# |
577623eed03bc38e4cea522f1a8016aa55356775 | Change BlackHole iteration style | iridinite/shiftdrive | Client/BlackHole.cs | Client/BlackHole.cs | /*
** Project ShiftDrive
** (C) Mika Molenkamp, 2016.
*/
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
namespace ShiftDrive {
/// <summary>
/// A <seealso cref="NamedObject"/> representing a gravitational singularity.
/// </summary>
internal sealed class BlackHole : NamedObject {
public BlackHole(GameState world) : base(world) {
type = ObjectType.BlackHole;
facing = 0f;
spritename = "map/blackhole";
bounding = 0f; // no bounding sphere; Update handles gravity pull
}
public override void Update(float deltaTime) {
base.Update(deltaTime);
// simulate gravitational pull
IEnumerable<uint> keys = world.Objects.Keys.OrderByDescending(k => k);
foreach (uint key in keys) {
GameObject gobj = world.Objects[key];
// black holes don't affect themselves...
if (gobj.type == ObjectType.BlackHole) continue;
// objects closer than 140 units are affected by the grav pull
if (!(Vector2.DistanceSquared(gobj.position, this.position) < 19600)) continue;
// pull this object in closer
Vector2 pulldir = Vector2.Normalize(position - gobj.position);
float pullpower = 1f - Vector2.Distance(gobj.position, this.position) / 140f;
gobj.position += pulldir * pullpower * pullpower * deltaTime * 40f;
gobj.changed = true;
// notify player ship
if (pullpower >= 0.1f && gobj.type == ObjectType.PlayerShip && world.IsServer)
NetServer.PublishAnnouncement(AnnouncementId.BlackHole, null);
// objects that are too close to the center are damaged
if (pullpower >= 0.35f) gobj.TakeDamage(pullpower * pullpower * deltaTime * 10f);
// and stuff at the center is simply destroyed
if (pullpower >= 0.95f) gobj.Destroy();
}
}
public override bool IsTerrain() {
return true;
}
}
} | /*
** Project ShiftDrive
** (C) Mika Molenkamp, 2016.
*/
using Microsoft.Xna.Framework;
namespace ShiftDrive {
/// <summary>
/// A <seealso cref="NamedObject"/> representing a gravitational singularity.
/// </summary>
internal sealed class BlackHole : NamedObject {
public BlackHole(GameState world) : base(world) {
type = ObjectType.BlackHole;
facing = 0f;
spritename = "map/blackhole";
bounding = 0f; // no bounding sphere; Update handles gravity pull
}
public override void Update(float deltaTime) {
base.Update(deltaTime);
// simulate gravitational pull
foreach (GameObject gobj in world.Objects.Values) {
// black holes don't affect themselves...
if (gobj.type == ObjectType.BlackHole) continue;
// objects closer than 140 units are affected by the grav pull
if (!(Vector2.DistanceSquared(gobj.position, this.position) < 19600)) continue;
// pull this object in closer
Vector2 pulldir = Vector2.Normalize(position - gobj.position);
float pullpower = 1f - Vector2.Distance(gobj.position, this.position) / 140f;
gobj.position += pulldir * pullpower * pullpower * deltaTime * 40f;
gobj.changed = true;
// notify player ship
if (pullpower >= 0.1f && gobj.type == ObjectType.PlayerShip && world.IsServer)
NetServer.PublishAnnouncement(AnnouncementId.BlackHole, null);
// objects that are too close to the center are damaged
if (pullpower >= 0.35f) gobj.TakeDamage(pullpower * pullpower * deltaTime * 10f);
// and stuff at the center is simply destroyed
if (pullpower >= 0.95f) gobj.Destroy();
}
}
public override bool IsTerrain() {
return true;
}
}
} | bsd-3-clause | C# |
9b17e1f77cae7e3afbbc68f6102ba0251f22eeaf | Remove bad async description | AzureAD/microsoft-authentication-library-for-dotnet,AzureAD/microsoft-authentication-library-for-dotnet,AzureAD/microsoft-authentication-library-for-dotnet,AzureAD/microsoft-authentication-library-for-dotnet | src/client/Microsoft.Identity.Client/Cache/CacheImpl/InMemoryPartitionedCacheSerializer.cs | src/client/Microsoft.Identity.Client/Cache/CacheImpl/InMemoryPartitionedCacheSerializer.cs | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.;
using System.Collections.Concurrent;
using System.Threading.Tasks;
using Microsoft.Identity.Client.Core;
namespace Microsoft.Identity.Client.Cache.CacheImpl
{
/// <summary>
/// A simple partitioned cache, useful for Confidential Client flows.
/// </summary>
internal class InMemoryPartitionedCacheSerializer
: AbstractPartitionedCacheSerializer
{
internal /* internal for test only */ ConcurrentDictionary<string, byte[]> CachePartition { get; }
private readonly ICoreLogger _logger;
public InMemoryPartitionedCacheSerializer(ICoreLogger logger, ConcurrentDictionary<string, byte[]> dictionary = null)
{
CachePartition = dictionary ?? new ConcurrentDictionary<string, byte[]>();
_logger = logger;
}
protected override byte[] ReadCacheBytes(string cacheKey)
{
if (CachePartition.TryGetValue(cacheKey, out byte[] blob))
{
_logger.Verbose($"[InMemoryPartitionedTokenCache] ReadCacheBytes found cacheKey {cacheKey}");
return blob;
}
_logger.Verbose($"[InMemoryPartitionedTokenCache] ReadCacheBytes did not find cacheKey {cacheKey}");
return null;
}
protected override void RemoveKey(string cacheKey)
{
bool removed = CachePartition.TryRemove(cacheKey, out _);
_logger.Verbose($"[InMemoryPartitionedTokenCache] RemoveKeyAsync cacheKey {cacheKey} success {removed}");
}
protected override void WriteCacheBytes(string cacheKey, byte[] bytes)
{
// As per https://docs.microsoft.com/en-us/dotnet/api/system.collections.concurrent.concurrentdictionary-2?redirectedfrom=MSDN&view=net-5.0#remarks
// the indexer is ok to store a key/value pair unconditionally
if (_logger.IsLoggingEnabled(LogLevel.Verbose))
{
_logger.Verbose($"[InMemoryPartitionedTokenCache] WriteCacheBytes with cacheKey {cacheKey}. Cache partitions: {CachePartition.Count}"); // note: Count is expensive
}
CachePartition[cacheKey] = bytes;
}
}
}
| // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.;
using System.Collections.Concurrent;
using System.Threading.Tasks;
using Microsoft.Identity.Client.Core;
namespace Microsoft.Identity.Client.Cache.CacheImpl
{
/// <summary>
/// A simple partitioned cache, useful for Confidential Client flows.
/// </summary>
internal class InMemoryPartitionedCacheSerializer
: AbstractPartitionedCacheSerializer
{
internal /* internal for test only */ ConcurrentDictionary<string, byte[]> CachePartition { get; }
private readonly ICoreLogger _logger;
public InMemoryPartitionedCacheSerializer(ICoreLogger logger, ConcurrentDictionary<string, byte[]> dictionary = null)
{
CachePartition = dictionary ?? new ConcurrentDictionary<string, byte[]>();
_logger = logger;
}
protected override byte[] ReadCacheBytes(string cacheKey)
{
if (CachePartition.TryGetValue(cacheKey, out byte[] blob))
{
_logger.Verbose($"[InMemoryPartitionedTokenCache] ReadCacheBytes found cacheKey {cacheKey}");
return blob;
}
_logger.Verbose($"[InMemoryPartitionedTokenCache] ReadCacheBytes did not find cacheKey {cacheKey}");
return null;
}
protected override void RemoveKey(string cacheKey)
{
bool removed = CachePartition.TryRemove(cacheKey, out _);
_logger.Verbose($"[InMemoryPartitionedTokenCache] RemoveKeyAsync cacheKey {cacheKey} success {removed}");
}
protected override async void WriteCacheBytes(string cacheKey, byte[] bytes)
{
// As per https://docs.microsoft.com/en-us/dotnet/api/system.collections.concurrent.concurrentdictionary-2?redirectedfrom=MSDN&view=net-5.0#remarks
// the indexer is ok to store a key/value pair unconditionally
if (_logger.IsLoggingEnabled(LogLevel.Verbose))
{
_logger.Verbose($"[InMemoryPartitionedTokenCache] WriteCacheBytes with cacheKey {cacheKey}. Cache partitions: {CachePartition.Count}"); // note: Count is expensive
}
CachePartition[cacheKey] = bytes;
}
}
}
| mit | C# |
33368cb25410d980cf9c6358720081f034e7bdde | Add Default cake target | Redth/Plugin.SocialAuth,Redth/Plugin.SocialAuth | build.cake | build.cake | var NUGET_VERSION = Argument ("nugetversion", "0.0.0.1");
var TARGET = Argument ("target", "nuget");
Task ("libs").Does (() => {
EnsureDirectoryExists ("./artifacts/");
NuGetRestore ("./Plugin.SocialAuth.sln");
MSBuild ("./Plugin.SocialAuth.sln", c => c.Configuration = "Release");
});
Task ("nuget").IsDependentOn("libs").Does (() => {
var nuspecs = GetFiles ("./NuSpec/*.nuspec");
foreach (var ns in nuspecs) {
NuGetPack (ns, new NuGetPackSettings {
Version = NUGET_VERSION,
BasePath = "./NuSpec",
OutputDirectory = "./artifacts/",
});
}
});
Task ("Default").IsDependentOn("nuget");
RunTarget (TARGET); | var NUGET_VERSION = Argument ("nugetversion", "0.0.0.1");
var TARGET = Argument ("target", "nuget");
Task ("libs").Does (() => {
EnsureDirectoryExists ("./artifacts/");
NuGetRestore ("./Plugin.SocialAuth.sln");
MSBuild ("./Plugin.SocialAuth.sln", c => c.Configuration = "Release");
});
Task ("nuget").IsDependentOn("libs").Does (() => {
var nuspecs = GetFiles ("./NuSpec/*.nuspec");
foreach (var ns in nuspecs) {
NuGetPack (ns, new NuGetPackSettings {
Version = NUGET_VERSION,
BasePath = "./NuSpec",
OutputDirectory = "./artifacts/",
});
}
});
RunTarget (TARGET); | mit | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.