コード例 #1
0
ファイル: App.cs プロジェクト: yaling888/ClashSharp
        private void StartClash()
        {
retry:
            try
            {
                clash.Start();
                clash.Exited += Clash_Exited;
            }
            catch (Clash.ServiceMissingException e)
            {
                logger.LogInformation(e, "Clash service not installed.");
                try
                {
                    Clash.InstallClashService();
                }
                catch (Exception ex)
                {
                    logger.LogError(ex, "Install Clash service failed.");
                    ExitApp();
                    return;
                }

                goto retry;
            }
            catch (Exception e)
            {
                logger.LogError(e, "Start Clash failed.");
                MessageBox.Show("Start Clash failed.\n" + e.Message);
                ExitApp();
            }
        }
コード例 #2
0
ファイル: App.cs プロジェクト: yaling888/ClashSharp
        public App(
            ILogger <App> logger,
            Clash clash,
            ClashApi clashApi,
            ConfigManager configManager,
            IOptions <AppOptions> options,
            IHostEnvironment environment
            )
        {
            this.logger = logger;
            this.clash  = clash;
            _api        = clashApi;
            _options    = options.Value;

            var isDev = environment.IsDevelopment();

            notifyIcon = BuildNotifyIcon(isDev);

            logger.LogInformation("App started.");

            if (isDev)
            {
                return;
            }

            Task.Run(configManager.UpdateConfig);
            Task.Run(StartClash);
        }
コード例 #3
0
        public static bool[][] GetInterChainContactBools(IStructure structure)
        {
            // Identify inter-chain contacts and then map all aas in the structure to true/false
            Selection contactAas = Clash.GetContactSelection(structure.ToArray());

            bool[][] contacts = structure.Select(chain => chain.Select(aa => contactAas.Aas.Contains(aa)).ToArray()).ToArray();
            return(contacts);
        }
コード例 #4
0
        public static Selection GetCnInterAsuContacts(IStructure cnAsymmetricUnit, int multiplicity, Vector3 axis)
        {
            AxisPattern <IStructure> pattern = new AxisPattern <IStructure>(axis, multiplicity, cnAsymmetricUnit);

            IStructure[] others    = pattern[1, multiplicity - 1].ToArray(); // CxUtilities.Pattern(cnAsymmetricUnit, axis, multiplicity, new int[] { 0 }, true);
            Selection    selection = Clash.GetContactSelectionInFocusSet(new IStructure[] { cnAsymmetricUnit }, others);

            return(selection);
        }
コード例 #5
0
        public static string Url(string villageTag)
        {
            if (Clash.TryFormatTag(villageTag, out string formattedTag) == false)
            {
                throw new InvalidTagException(villageTag);
            }

            return($"players/{Uri.EscapeDataString(formattedTag)}");
        }
コード例 #6
0
ファイル: FileClashRepository.cs プロジェクト: Morebis-GIT/CI
        public void Add(Clash item)
        {
            var items = new List <Clash>()
            {
                item
            };

            InsertItems(_folder, _type, items, items.ConvertAll(i => i.Uid.ToString()));
        }
コード例 #7
0
        public void Ok(object sender, RoutedEventArgs args)
        {
            error.IsVisible = false;
            DisableControls();

            Uri.TryCreate(url.Text, UriKind.Absolute, out Uri? uri);
            if (uri == null || uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps)
            {
                ShowError("The URL is invalid");
                EnableControls();
                return;
            }

            string filename = Utils.RemoveYamlExt(name.Text ?? "");

            if (filename.Length == 0)
            {
                ShowError("Please specify a profile name.");
                EnableControls();
                return;
            }

            if (filename.IndexOfAny(Path.GetInvalidFileNameChars()) > 0)
            {
                ShowError("The name contains invalid characters.");
                EnableControls();
                return;
            }

            if (ConfigFile.GetClashConfigs().Select(Utils.RemoveYamlExt).Contains(filename))
            {
                ShowError("The profile name has existed. Please specify another name.");
                EnableControls();
                return;
            }

            Task.Run(async delegate {
                try {
                    byte[] data = await Utils.GetProxiedHttpClient().GetByteArrayAsync(uri);

                    string?err = Clash.ValidateConfig(data);
                    if (err != null)
                    {
                        throw new Exception(err);
                    }

                    Dispatcher.UIThread.Post(() => {
                        Close(new Result($"{filename}.yaml", uri.ToString(), data));
                    });
                } catch (Exception e) {
                    Dispatcher.UIThread.Post(() => {
                        ShowError(e.Message);
                        EnableControls();
                    });
                }
            });
        }
コード例 #8
0
        public static List <int> GetInterChainContactIndices(IStructure assembly, int chainIndex)
        {
            IChain a = assembly[chainIndex];

            IChain[]   others   = assembly.Where(chain => chain != a).ToArray();
            List <int> contacts = Clash.GetContactIndices(a, others);

            return(contacts);
        }
コード例 #9
0
        public static string Url(string clanTag)
        {
            if (Clash.TryFormatTag(clanTag, out string?formattedTag) == false)
            {
                throw new InvalidTagException(clanTag);
            }

            return($"clans/{Uri.EscapeDataString(formattedTag)}/currentwar/leaguegroup");
        }
コード例 #10
0
        public static Selection GetCnInterAsuContacts(IStructure cnAsymmetricUnit, int multiplicity, Line axis, Clash.ContactType contactType = Clash.ContactType.Atomic)
        {
            IStructure mirror = cnAsymmetricUnit.GetMirroredElement(true, null);
            AxisPattern <IStructure> pattern = new AxisPattern <IStructure>(axis.Point, axis.Direction, multiplicity, mirror, new int[] { 0 });

            IStructure[] others    = pattern.ToArray();//[1, multiplicity - 1].ToArray(); // CxUtilities.Pattern(cnAsymmetricUnit, axis, multiplicity, new int[] { 0 }, true);
            Selection    selection = Clash.GetContactSelectionInFocusSet(new IStructure[] { cnAsymmetricUnit }, others, contactType);

            return(selection);
        }
コード例 #11
0
ファイル: MiscCommands.cs プロジェクト: Sid-003/RiseBot-1
        public async Task GetNotInClanAsync()
        {
            var guildsMembers = Guild.GuildMembers;
            var clanMembers   = await Clash.GetClanMembersAsync(Guild.ClanTag);

            var notInClan = guildsMembers.Where(guildMember =>
                                                !guildMember.Tags.Any(x => clanMembers.Select(y => y.Tag).Any(z => z == x))).ToArray();

            await SendMessageAsync(string.Join('\n',
                                               notInClan.Select(x => Context.Guild.GetUser(x.Id)?.GetDisplayName()).Where(y => !(y is null))));
        }
コード例 #12
0
        private static bool HasParentClash(
            IReadOnlyDictionary <string, Clash> clashesByExternalRef,
            Clash childClash,
            out Clash parentClash)
        {
            parentClash = null;

            return(childClash.ParentExternalidentifier != null &&
                   clashesByExternalRef.TryGetValue(childClash.ParentExternalidentifier, out parentClash) &&
                   parentClash != null);
        }
コード例 #13
0
ファイル: ClansClientBase.cs プロジェクト: devhl-labs/CocApi
        public async Task <ClanWarLeagueGroup?> GetOrFetchLeagueGroupOrDefaultAsync(string tag, CancellationToken?cancellationToken = default)
        {
            string formattedTag = Clash.FormatTag(tag);

            using var scope = Services.CreateScope();

            CacheContext dbContext = scope.ServiceProvider.GetRequiredService <CacheContext>();

            return((await dbContext.Groups.FirstOrDefaultAsync(g => g.Tag == formattedTag))?.Data
                   ?? await _clansApi.FetchClanWarLeagueGroupOrDefaultAsync(formattedTag, cancellationToken));
        }
コード例 #14
0
        private bool AreClashesFromTheSameStructure(Clash first, Clash second)
        {
            while (true)
            {
                if (first == null || second == null)
                {
                    return(false);
                }

                if (string.IsNullOrWhiteSpace(first.ParentExternalidentifier) &&
                    string.IsNullOrWhiteSpace(second.ParentExternalidentifier))
                {
                    return(false);
                }

                if (first.Externalref.EqualInvariantCultureIgnoreCase(second.ParentExternalidentifier))
                {
                    return(true);
                }

                if (second.Externalref.EqualInvariantCultureIgnoreCase(first.ParentExternalidentifier))
                {
                    return(true);
                }

                if (first.ParentExternalidentifier.EqualInvariantCultureIgnoreCase(second.ParentExternalidentifier))
                {
                    return(true);
                }

                var parentClashFromFirst =
                    _clashRepository.FindByExternal(first.ParentExternalidentifier).FirstOrDefault();

                if (parentClashFromFirst != null &&
                    !string.IsNullOrWhiteSpace(parentClashFromFirst.ParentExternalidentifier) &&
                    parentClashFromFirst.ParentExternalidentifier.EqualInvariantCultureIgnoreCase(second.ParentExternalidentifier))
                {
                    return(true);
                }

                var parentClashFromSecond =
                    _clashRepository.FindByExternal(second.ParentExternalidentifier).FirstOrDefault();

                if (parentClashFromSecond != null &&
                    !string.IsNullOrWhiteSpace(parentClashFromSecond.ParentExternalidentifier) &&
                    parentClashFromSecond.ParentExternalidentifier.EqualInvariantCultureIgnoreCase(first.ParentExternalidentifier))
                {
                    return(true);
                }

                first  = parentClashFromFirst;
                second = parentClashFromSecond;
            }
        }
コード例 #15
0
        public static IEnumerable <FusionDesignInfo> GetSplices(IChain nPeptide, Range nAllowedSpliceRange, IChain cPeptide, Range cAllowedSpliceRange, int topX = DefaultTopX)
        {
            List <FusionDesignInfo> splices = new List <FusionDesignInfo>();
            int   minAlignmentLength        = 8;
            float maxRmsd = 0.25f;

            // Find all alignments and remove those that are not between the desired ranges
            // If this becomes a bottleneck, could specify allowed alignment ranges
            List <SequenceAlignment> alignments = Fusion.GetAlignmentsPreservingFullSsBlocks(nPeptide, cPeptide, SS.Helix, minAlignmentLength, maxRmsd);

            alignments.RemoveAll(a => !(nAllowedSpliceRange.Start <= a.Range1.Start && a.Range1.End <= nAllowedSpliceRange.End));
            alignments.RemoveAll(a => !(cAllowedSpliceRange.Start <= a.Range2.Start && a.Range2.End <= cAllowedSpliceRange.End));

            foreach (SequenceAlignment alignment in alignments)
            {
                Matrix alignmentTransform = Rmsd.GetRmsdTransformForResidues(nPeptide, alignment.Range1.Start, alignment.Range1.End, cPeptide, alignment.Range2.Start, alignment.Range2.End);
                IChain copy1 = new Chain(nPeptide);
                IChain copy2 = new Chain(cPeptide);
                copy1.Transform(alignmentTransform);
                IChain[] clashCheckPeptides = new IChain[] { copy1, copy2 };
                if (Clash.GetInterSetBackboneClashes(clashCheckPeptides, new int[] { 0, alignment.Range2.End + 1 }, new int[] { alignment.Range1.Start - 1, copy2.Count - 1 }))
                {
                    continue;
                }

                // Create the spliced peptide
                IChain splicedPeptide = Fusion.GetChain(
                    new IChain[] { copy1, copy2 },
                    new SequenceAlignment[] { alignment },
                    new IEnumerable <int>[] { new int[] { }, new int[] { } });

                // Save it
                FusionDesignInfo spliceInfo     = new FusionDesignInfo();
                Range[]          originalRanges = null;
                Range[]          finalRanges    = null;
                Fusion.GetIdentityRanges(clashCheckPeptides, new SequenceAlignment[] { alignment }, out originalRanges, out finalRanges);
                spliceInfo.Peptide            = splicedPeptide;
                spliceInfo.OriginalChains     = new IChain[] { nPeptide, cPeptide };
                spliceInfo.PdbOutputChains    = new IChain[] { splicedPeptide, copy1, copy2 };
                spliceInfo.ImmutablePositions = new int[] { };
                spliceInfo.IdentityRanges     = finalRanges;
                spliceInfo.OriginalRanges     = originalRanges;

                splices.Add(spliceInfo);
                splices.Sort((a, b) => b.Score.CompareTo(a.Score));
                if (splices.Count > topX)
                {
                    splices.RemoveAt(topX);
                }
            }

            return(splices);
        }
コード例 #16
0
        public static List <int> GetCnInterAsuContactIndices(IStructure cnAsymmetricUnit, int chainIndex, int multiplicity, Vector3 axis)
        {
            Trace.Assert(0 <= chainIndex && chainIndex < cnAsymmetricUnit.Count);

            AxisPattern <IStructure> pattern = new AxisPattern <IStructure>(axis, multiplicity, cnAsymmetricUnit);

            IStructure[] others = pattern[1, multiplicity - 1].ToArray();// CxUtilities.Pattern(cnAsymmetricUnit, axis, multiplicity, new int[] { 0 }, true);

            List <int> interAsuContacts = Clash.GetContactIndices(cnAsymmetricUnit[chainIndex], others.SelectMany(str => str).ToArray());

            return(interAsuContacts);
        }
コード例 #17
0
ファイル: MiscCommands.cs プロジェクト: Sid-003/RiseBot-1
        public async Task GetBandMatchAsync()
        {
            var currentWar = await Clash.GetCurrentWarAsync(Guild.ClanTag);

            if (currentWar is null || currentWar.State != WarState.Preparation)
            {
                await SendMessageAsync("Either not in war or the API hasn't updated yet");

                return;
            }

            await SendMessageAsync($"!match {currentWar.Opponent.Tag}");
        }
コード例 #18
0
        public async Task <CachedPlayer> GetCachedPlayerAsync(string tag, CancellationToken?cancellationToken = default)
        {
            string formattedTag = Clash.FormatTag(tag);

            using var scope = Services.CreateScope();

            CacheContext dbContext = scope.ServiceProvider.GetRequiredService <CacheContext>();

            return(await dbContext.Players
                   .Where(i => i.Tag == formattedTag)
                   .FirstAsync(cancellationToken.GetValueOrDefault())
                   .ConfigureAwait(false));
        }
コード例 #19
0
        public static List <int> GetCnInterAsuContactIndices(IChain monomer, int multiplicity, Vector3 axis)
        {
            IChain[] oligomer = new IChain[multiplicity - 1];
            for (int i = 0; i < multiplicity - 1; i++)
            {
                oligomer[i] = new Chain(monomer);
                oligomer[i].RotateRadians(Vector3.Zero, Vector3.UnitZ, (float)((i + 1) * 2 * Math.PI / multiplicity));
            }

            List <int> contacts = Clash.GetContactIndices(monomer, oligomer);

            return(contacts);
        }
コード例 #20
0
        private (bool Success, string Message) ValidateClashAndDelete(Clash clash)
        {
            var validationResult = ValidateClashBeforeDelete(clash);

            if (validationResult)
            {
                _clashRepository.Delete(clash.Uid);
                _clashRepository.SaveChanges();
                return(Success());
            }

            return(Failure("Clash cannot be deleted – in use"));
        }
コード例 #21
0
ファイル: ClansClientBase.cs プロジェクト: devhl-labs/CocApi
        public async Task <List <CachedWar> > GetClanWarsAsync(string tag, CancellationToken?cancellationToken = default)
        {
            string formattedTag = Clash.FormatTag(tag);

            using var scope = Services.CreateScope();

            CacheContext dbContext = scope.ServiceProvider.GetRequiredService <CacheContext>();

            return(await dbContext.Wars
                   .AsNoTracking()
                   .Where(i => i.ClanTag == formattedTag || i.OpponentTag == formattedTag)
                   .ToListAsync(cancellationToken.GetValueOrDefault(_stopRequestedTokenSource.Token))
                   .ConfigureAwait(false));
        }
コード例 #22
0
ファイル: MiscCommands.cs プロジェクト: Sid-003/RiseBot-1
        public async Task DiscordCheck()
        {
            var clanMembers = await Clash.GetClanMembersAsync(Guild.ClanTag);

            var discordMembers = Guild.GuildMembers;

            var missingMembers = clanMembers.Where(clanMember => !discordMembers.Any(x =>
                                                                                     x.Tags.Any(y => string.Equals(y, clanMember.Tag, StringComparison.InvariantCultureIgnoreCase))))
                                 .ToArray();

            var missingList = string.Join('\n', missingMembers.Select(x => $"{x.Name}{x.Tag}"));

            await SendMessageAsync(missingList);
        }
コード例 #23
0
        private double ExposureClashScore(
            Spot spot,
            Clash clash,
            int productClashCount,
            double weight
            )
        {
            double effectiveExposureCount = _effectiveClashExposureCount.Calculate(
                clash.Differences,
                (clash.DefaultPeakExposureCount, clash.DefaultOffPeakExposureCount),
                (spot.StartDateTime, spot.SalesArea));

            return(1 / effectiveExposureCount * productClashCount * weight);
        }
コード例 #24
0
    void ExplosionDebris(Collision2D col)
    {
        Clash clash = col.gameObject.GetComponent <Clash>();

        for (int i = 0; i < CountDebris1; i++)
        {
            Instantiate(clash.Debris1, new Vector3(col.contacts[0].point.x, col.contacts[0].point.y, -599), transform.rotation);
        }

        for (int i = 0; i < CountDebris2; i++)
        {
            Instantiate(clash.Debris2, new Vector3(col.contacts[0].point.x, col.contacts[0].point.y, -599), transform.rotation);
        }
    }
コード例 #25
0
        private Clash UpdateClash(Clash clash, UpdateClashModel model, bool applyGlobally)
        {
            clash.Description = model.Description;
            clash.ParentExternalidentifier    = model.ParentExternalidentifier;
            clash.DefaultPeakExposureCount    = model.DefaultPeakExposureCount;
            clash.DefaultOffPeakExposureCount = model.DefaultOffPeakExposureCount;

            if (!applyGlobally)
            {
                clash.Differences = model.Differences;
            }

            return(clash);
        }
コード例 #26
0
        public static bool[][] GetCnInterAsuContactBools(IStructure asu, int multiplicity, Vector3 axis)
        {
            asu = (IStructure)asu.DeepCopy();
            IStructure mirror = asu.GetMirroredElement(true, null);
            AxisPattern <IStructure> pattern = new AxisPattern <IStructure>(axis, multiplicity, mirror, new int[] { 0 });

            IStructure[] neighbors = pattern.ToArray();

            //IStructure[] neighbors = CxUtilities.Pattern(asu, axis, multiplicity, new int[] { 0 }, true);

            Selection contactAas = Clash.GetContactSelectionInFocusSet(new IStructure[] { asu }, neighbors, Clash.ContactType.Atomic);

            bool[][] contacts = asu.Select(chain => chain.Select(aa => contactAas.Aas.Contains(aa)).ToArray()).ToArray();
            return(contacts);
        }
コード例 #27
0
ファイル: ClansClientBase.cs プロジェクト: devhl-labs/CocApi
        public async Task AddAsync(string tag, bool downloadWars = true, bool downloadCwl = true, bool downloadMembers = false)
        {
            string formattedTag = Clash.FormatTag(tag);

            using var scope = Services.CreateScope();

            CacheContext dbContext = scope.ServiceProvider.GetRequiredService <CacheContext>();

            CachedClan cachedClan = await dbContext.Clans.Where(c => c.Tag == formattedTag).FirstOrDefaultAsync().ConfigureAwait(false);

            cachedClan ??= await PrepareNewCachedClanAsync(formattedTag, downloadWars, downloadCwl, downloadMembers, dbContext).ConfigureAwait(false);

            await dbContext.SaveChangesAsync().ConfigureAwait(false);

            return;
        }
コード例 #28
0
 private ClashModel LoadClashModel(Clash clash, Clash parentClash)
 {
     return(new ClashModel
     {
         ParentExternalidentifier = clash.ParentExternalidentifier,
         Description = clash.Description,
         DefaultPeakExposureCount = clash.DefaultPeakExposureCount,
         DefaultOffPeakExposureCount = clash.DefaultOffPeakExposureCount,
         Externalref = clash.Externalref,
         ParentClashDescription = parentClash?.Description,
         ParentPeakExposureCount = parentClash?.DefaultPeakExposureCount,
         ParentOffPeakExposureCount = parentClash?.DefaultOffPeakExposureCount,
         Differences = clash.Differences ?? new List <ClashDifference>(),
         Uid = clash.Uid
     });
 }
コード例 #29
0
ファイル: ClansClientBase.cs プロジェクト: devhl-labs/CocApi
        public async Task <CachedWar?> GetLeagueWarOrDefaultAsync(string warTag, DateTime season, CancellationToken?cancellationToken = default)
        {
            string formattedTag = Clash.FormatTag(warTag);

            using var scope = Services.CreateScope();

            CacheContext dbContext = scope.ServiceProvider.GetRequiredService <CacheContext>();

            CachedWar?war = await dbContext.Wars
                            .AsNoTracking()
                            .FirstOrDefaultAsync(w => w.WarTag == formattedTag && w.Season == season, cancellationToken.GetValueOrDefault())
                            .ConfigureAwait(false);

            war?.Data?.Initialize(war.ServerExpiration, formattedTag);

            return(war);
        }
コード例 #30
0
ファイル: ClansClientBase.cs プロジェクト: devhl-labs/CocApi
        public async Task <List <CachedClan> > GetCachedClansAsync(IEnumerable <string> tags, CancellationToken?cancellationToken = default)
        {
            List <string> formattedTags = new List <string>();

            foreach (string tag in tags)
            {
                formattedTags.Add(Clash.FormatTag(tag));
            }

            using var scope = Services.CreateScope();

            CacheContext dbContext = scope.ServiceProvider.GetRequiredService <CacheContext>();

            return(await dbContext.Clans
                   .AsNoTracking()
                   .Where(i => formattedTags.Contains(i.Tag))
                   .ToListAsync(cancellationToken.GetValueOrDefault())
                   .ConfigureAwait(false));
        }