Dataset Viewer
Auto-converted to Parquet Duplicate
repo_id
string
size
int64
file_path
string
content
string
shard_id
int64
quality_score
float32
quality_prediction
int8
quality_confidence
float32
topic_primary
string
topic_group
string
topic_score
float32
topic_all
string
quality2_score
float32
quality2_prediction
int8
quality2_confidence
float32
Mentra-Community/SmartGlassesManager
3,804
SGM_android/SmartGlassesManager/src/main/java/com/teamopensmartglasses/smartglassesmanager/speechrecognition/vad/VadGateSpeechPolicy.java
package com.teamopensmartglasses.smartglassesmanager.speechrecognition.vad; import android.content.Context; import android.util.Log; import com.konovalov.vad.Vad; import com.konovalov.vad.VadListener; import com.konovalov.vad.config.FrameSize; import com.konovalov.vad.config.Mode; import com.konovalov.vad.config.Model; import com.konovalov.vad.config.SampleRate; import com.konovalov.vad.models.VadModel; import com.teamopensmartglasses.smartglassesmanager.speechrecognition.google.asr.SpeechDetectionPolicy; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.Arrays; /** A speech detector that always reports hearing speech. */ public class VadGateSpeechPolicy implements SpeechDetectionPolicy { public final String TAG = "WearLLM_VadGateService"; private Context mContext; private Vad vad; private VadModel vadModel; private boolean isCurrentlySpeech; public VadGateSpeechPolicy(Context context){ mContext = context; isCurrentlySpeech = false; } //custom - divide by 3, gives us best of both worlds - vosk runs best at ~0.2 second buffer, this runs best at 512-1024 size frame, so we run at 0.192second buffer and divide by 3 public void startVad(int blockSizeSamples){ vad = Vad.builder(); blockSizeSamples = blockSizeSamples / 3; Log.d(TAG, "VAD looking for block size samples: " + blockSizeSamples); //find the proper frame size FrameSize fsToUse = null; for (FrameSize fs : FrameSize.values()){ if (fs.getValue() == blockSizeSamples){ fsToUse = fs; break; } } if (fsToUse == null){ Log.e(TAG, "Frame size not supported by VAD, exiting."); return; } vadModel = vad.setModel(Model.SILERO_DNN) .setSampleRate(SampleRate.SAMPLE_RATE_16K) .setFrameSize(fsToUse) // .setMode(Mode.VERY_AGGRESSIVE) .setMode(Mode.AGGRESSIVE) .setSilenceDurationMs(1350) .setSpeechDurationMs(50) .setContext(mContext) .build(); Log.d(TAG, "VAD init'ed."); } @Override public boolean shouldPassAudioToRecognizer() { return isCurrentlySpeech; } @Override public void init(int blockSizeSamples) { startVad(blockSizeSamples); } @Override public void reset() {} public short [] bytesToShort(byte[] bytes) { short[] shorts = new short[bytes.length/2]; // to turn bytes to shorts as either big endian or little endian. ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().get(shorts); return shorts; } @Override public void processAudioBytes(byte[] bytes, int offset, int length) { short [] audioBytesFull = bytesToShort(bytes); int windowLen = audioBytesFull.length / 3; for (int i = 0; i < 3; i++) { int moffset = i * windowLen; short [] audioBytesPartial = Arrays.copyOfRange(audioBytesFull, moffset, moffset + windowLen); vadModel.setContinuousSpeechListener(audioBytesPartial, new VadListener() { @Override public void onSpeechDetected() { //speech detected! // Log.d(TAG, "Speech detected."); isCurrentlySpeech = true; } @Override public void onNoiseDetected() { //noise detected! // Log.d(TAG, "Noise detected!"); isCurrentlySpeech = false; } }); } } @Override public void stop() { vadModel.close(); } }
35
0.82448
1
0.82448
audio-video-media
MEDIA
0.681147
audio-video-media
0.827818
1
0.827818
aaru-dps/Aaru
2,654
Aaru.Images/T98/Unsupported.cs
// /*************************************************************************** // Aaru Data Preservation Suite // ---------------------------------------------------------------------------- // // Filename : Unsupported.cs // Author(s) : Natalia Portillo <[email protected]> // // Component : Disk image plugins. // // --[ Description ] ---------------------------------------------------------- // // Contains features unsupported by T98 disk images. // // --[ License ] -------------------------------------------------------------- // // This library is free software; you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as // published by the Free Software Foundation; either version 2.1 of the // License, or (at your option) any later version. // // This library 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 library; if not, see <http://www.gnu.org/licenses/>. // // ---------------------------------------------------------------------------- // Copyright © 2011-2025 Natalia Portillo // ****************************************************************************/ using System.Diagnostics.CodeAnalysis; using Aaru.CommonTypes.Enums; namespace Aaru.Images; [SuppressMessage("ReSharper", "UnusedType.Global")] public sealed partial class T98 { #region IWritableImage Members /// <inheritdoc /> public ErrorNumber ReadMediaTag(MediaTagType tag, out byte[] buffer) { buffer = null; return ErrorNumber.NotSupported; } /// <inheritdoc /> public ErrorNumber ReadSectorTag(ulong sectorAddress, SectorTagType tag, out byte[] buffer) { buffer = null; return ErrorNumber.NotSupported; } /// <inheritdoc /> public ErrorNumber ReadSectorsTag(ulong sectorAddress, uint length, SectorTagType tag, out byte[] buffer) { buffer = null; return ErrorNumber.NotSupported; } /// <inheritdoc /> public ErrorNumber ReadSectorLong(ulong sectorAddress, out byte[] buffer) { buffer = null; return ErrorNumber.NotSupported; } /// <inheritdoc /> public ErrorNumber ReadSectorsLong(ulong sectorAddress, uint length, out byte[] buffer) { buffer = null; return ErrorNumber.NotSupported; } #endregion }
35
0.835835
1
0.835835
graphics-rendering
MEDIA
0.420001
graphics-rendering
0.683621
1
0.683621
structr/structr
2,001
structr-base/src/main/java/org/structr/core/function/search/FindLtFunction.java
/* * Copyright (C) 2010-2025 Structr GmbH * * This file is part of Structr <http://structr.org>. * * Structr is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * Structr 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Structr. If not, see <http://www.gnu.org/licenses/>. */ package org.structr.core.function.search; import org.structr.common.error.FrameworkException; import org.structr.core.function.AdvancedScriptingFunction; import org.structr.schema.action.ActionContext; public class FindLtFunction extends AdvancedScriptingFunction { public static final String ERROR_MESSAGE_LT = "Usage: ${lt(other)}. Example: ${find(\"User\", \"age\", lt(\"42\"))}"; @Override public String getName() { return "find.lt"; } @Override public String getSignature() { return null; } @Override public Object apply(final ActionContext ctx, final Object caller, final Object[] sources) throws FrameworkException { try { if (sources == null || sources.length > 1) { throw new IllegalArgumentException(); } return new RangePredicate(null, sources[0], false, false); } catch (final IllegalArgumentException e) { logParameterError(caller, sources, ctx.isJavaScriptContext()); return usage(ctx.isJavaScriptContext()); } } @Override public String usage(boolean inJavaScriptContext) { return ERROR_MESSAGE_LT; } @Override public String shortDescription() { return "Returns an lt predicate that can be used in find() function calls"; } @Override public boolean isHidden() { return true; } }
35
0.929441
1
0.929441
compilers-parsers
SYSTEMS
0.316413
compilers-parsers
0.925385
1
0.925385
exercism/website
24,905
app/views/mailers/mailshots_mailer/launch_trophies.html.erb
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional //EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <!--[if IE]><html xmlns="http://www.w3.org/1999/xhtml" class="ie"><![endif]--> <!--[if !IE]><!--><html style="margin: 0;padding: 0;" xmlns="http://www.w3.org/1999/xhtml"><!--<![endif]--> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title></title> <!--[if !mso]><!--><meta http-equiv="X-UA-Compatible" content="IE=edge"/><!--<![endif]--> <meta name="viewport" content="width=device-width"/> <style type="text/css"> p a { text-decoration: underline; font-weight:600; color:#2E57E8; } </style> <style type="text/css"> @media only screen and (min-width: 620px){.wrapper{min-width:600px !important}.wrapper h1{}.wrapper h1{font-size:22px !important;line-height:31px !important}.wrapper h2{}.wrapper h3{}.column{}.wrapper .size-8{font-size:8px !important;line-height:16px !important}.wrapper .size-9{font-size:9px !important;line-height:16px !important}.wrapper .size-10{font-size:10px !important;line-height:18px !important}.wrapper .size-11{font-size:11px !important;line-height:19px !important}.wrapper .size-12{font-size:12px !important;line-height:19px !important}.wrapper .size-13{font-size:13px !important;line-height:21px !important}.wrapper .size-14{font-size:16px !important;line-height:21px !important}.wrapper .size-15{font-size:16px !important;line-height:23px !important}.wrapper .size-16{font-size:16px !important;line-height:24px !important}.wrapper .size-17{font-size:17px !important;line-height:26px !important}.wrapper .size-18{font-size:18px !important;line-height:26px !important}.wrapper .size-20{font-size:20px !important;line-height:28px !important}.wrapper .size-22{font-size:22px !important;line-height:31px !important}.wrapper .size-24{font-size:24px !important;line-height:32px !important}.wrapper .size-26{font-size:26px !important;line-height:34px !important}.wrapper .size-28{font-size:28px !important;line-height:36px !important}.wrapper .size-30{font-size:30px !important;line-height:38px !important}.wrapper .size-32{font-size:32px !important;line-height:40px !important}.wrapper .size-34{font-size:34px !important;line-height:43px !important}.wrapper .size-36{font-size:36px !important;line-height:43px !important}.wrapper .size-40{font-size:40px !important;line-height:47px !important}.wrapper .size-44{font-size:44px !important;line-height:50px !important}.wrapper .size-48{font-size:48px !important;line-height:54px !important}.wrapper .size-56{font-size:56px !important;line-height:60px !important}.wrapper .size-64{font-size:64px !important;line-height:63px !important}} </style> <meta name="x-apple-disable-message-reformatting"/> <style type="text/css"> .main, .mso { margin: 0; padding: 0; } table { border-collapse: collapse; table-layout: fixed; } * { line-height: inherit; } [x-apple-data-detectors] { color: inherit !important; text-decoration: none !important; } .wrapper .footer__share-button a:hover, .wrapper .footer__share-button a:focus { color: #ffffff !important; } .wrapper .footer__share-button a.icon-white:hover, .wrapper .footer__share-button a.icon-white:focus { color: #ffffff !important; } .wrapper .footer__share-button a.icon-black:hover, .wrapper .footer__share-button a.icon-black:focus { color: #000000 !important; } .btn a:hover, .btn a:focus, .footer__share-button a:hover, .footer__share-button a:focus, .email-footer__links a:hover, .email-footer__links a:focus { opacity: 0.8; } .preheader, .header, .layout, .column { transition: width 0.25s ease-in-out, max-width 0.25s ease-in-out; } .preheader td { padding-bottom: 8px; } .layout, div.header { max-width: 400px !important; -fallback-width: 95% !important; width: calc(100% - 20px) !important; } div.preheader { max-width: 360px !important; -fallback-width: 90% !important; width: calc(100% - 60px) !important; } .snippet, .webversion { Float: none !important; } .stack .column { max-width: 400px !important; width: 100% !important; } .fixed-width.has-border { max-width: 402px !important; } .fixed-width.has-border .layout__inner { box-sizing: border-box; } .snippet, .webversion { width: 50% !important; } .ie .btn { width: 100%; } .ie .stack .column, .ie .stack .gutter { display: table-cell; float: none !important; } .ie div.preheader, .ie .email-footer { max-width: 560px !important; width: 560px !important; } .ie .snippet, .ie .webversion { width: 280px !important; } .ie div.header, .ie .layout { max-width: 600px !important; width: 600px !important; } .ie .two-col .column { max-width: 300px !important; width: 300px !important; } .ie .three-col .column, .ie .narrow { max-width: 200px !important; width: 200px !important; } .ie .wide { width: 400px !important; } .ie .stack.fixed-width.has-border, .ie .stack.has-gutter.has-border { max-width: 602px !important; width: 602px !important; } .ie .stack.two-col.has-gutter .column { max-width: 290px !important; width: 290px !important; } .ie .stack.three-col.has-gutter .column, .ie .stack.has-gutter .narrow { max-width: 188px !important; width: 188px !important; } .ie .stack.has-gutter .wide { max-width: 394px !important; width: 394px !important; } .ie .stack.two-col.has-gutter.has-border .column { max-width: 292px !important; width: 292px !important; } .ie .stack.three-col.has-gutter.has-border .column, .ie .stack.has-gutter.has-border .narrow { max-width: 190px !important; width: 190px !important; } .ie .stack.has-gutter.has-border .wide { max-width: 396px !important; width: 396px !important; } .ie .fixed-width .layout__inner { border-left: 0 none white !important; border-right: 0 none white !important; } .ie .layout__edges { display: none; } .mso .layout__edges { font-size: 0; } .layout-fixed-width, .mso .layout-full-width { background-color: #ffffff; } @media only screen and (min-width: 620px) { .column, .gutter { display: table-cell; Float: none !important; vertical-align: top; } div.preheader, .email-footer { max-width: 560px !important; width: 560px !important; } .snippet, .webversion { width: 280px !important; } div.header, .layout, .one-col .column { max-width: 600px !important; width: 600px !important; } .fixed-width.has-border, .fixed-width.x_has-border, .has-gutter.has-border, .has-gutter.x_has-border { max-width: 602px !important; width: 602px !important; } .two-col .column { max-width: 300px !important; width: 300px !important; } .three-col .column, .column.narrow, .column.x_narrow { max-width: 200px !important; width: 200px !important; } .column.wide, .column.x_wide { width: 400px !important; } .two-col.has-gutter .column, .two-col.x_has-gutter .column { max-width: 290px !important; width: 290px !important; } .three-col.has-gutter .column, .three-col.x_has-gutter .column, .has-gutter .narrow { max-width: 188px !important; width: 188px !important; } .has-gutter .wide { max-width: 394px !important; width: 394px !important; } .two-col.has-gutter.has-border .column, .two-col.x_has-gutter.x_has-border .column { max-width: 292px !important; width: 292px !important; } .three-col.has-gutter.has-border .column, .three-col.x_has-gutter.x_has-border .column, .has-gutter.has-border .narrow, .has-gutter.x_has-border .narrow { max-width: 190px !important; width: 190px !important; } .has-gutter.has-border .wide, .has-gutter.x_has-border .wide { max-width: 396px !important; width: 396px !important; } } @supports (display: flex) { @media only screen and (min-width: 620px) { .fixed-width.has-border .layout__inner { display: flex !important; } } } /*** * Mobile Styles * * 1. Overriding inline styles */ @media(max-width: 619px) { .email-flexible-footer .left-aligned-footer .column, .email-flexible-footer .center-aligned-footer, .email-flexible-footer .right-aligned-footer .column { max-width: 100% !important; /* [1] */ text-align: center !important; /* [1] */ width: 100% !important; /* [1] */ } .flexible-footer-logo { margin-left: 0px !important; /* [1] */ margin-right: 0px !important; /* [1] */ } .email-flexible-footer .left-aligned-footer .flexible-footer__share-button__container, .email-flexible-footer .center-aligned-footer .flexible-footer__share-button__container, .email-flexible-footer .right-aligned-footer .flexible-footer__share-button__container { display: inline-block; margin-left: 5px !important; /* [1] */ margin-right: 5px !important; /* [1] */ } .email-flexible-footer__additionalinfo--center { text-align: center !important; /* [1] */ } .email-flexible-footer .left-aligned-footer table, .email-flexible-footer .center-aligned-footer table, .email-flexible-footer .right-aligned-footer table { display: table !important; /* [1] */ width: 100% !important; /* [1] */ } .email-flexible-footer .footer__share-button, .email-flexible-footer .email-footer__additional-info { margin-left: 20px; margin-right: 20px; } } @media (max-width: 321px) { .fixed-width.has-border .layout__inner { border-width: 1px 0 !important; } .layout, .stack .column { min-width: 320px !important; width: 320px !important; } .border { display: none; } .has-gutter .border { display: table-cell; } } .mso div { border: 0 none white !important; } .mso .w560 .divider { margin-left: 260px !important; margin-right: 260px !important; } .mso .w360 .divider { margin-left: 160px !important; margin-right: 160px !important; } .mso .w260 .divider { margin-left: 110px !important; margin-right: 110px !important; } .mso .w160 .divider { margin-left: 60px !important; margin-right: 60px !important; } .mso .w354 .divider { margin-left: 157px !important; margin-right: 157px !important; } .mso .w250 .divider { margin-left: 105px !important; margin-right: 105px !important; } .mso .w148 .divider { margin-left: 54px !important; margin-right: 54px !important; } .mso .size-8, .ie .size-8 { font-size: 8px !important; line-height: 16px !important; } .mso .size-9, .ie .size-9 { font-size: 9px !important; line-height: 16px !important; } .mso .size-10, .ie .size-10 { font-size: 10px !important; line-height: 18px !important; } .mso .size-11, .ie .size-11 { font-size: 11px !important; line-height: 19px !important; } .mso .size-12, .ie .size-12 { font-size: 12px !important; line-height: 19px !important; } .mso .size-13, .ie .size-13 { font-size: 13px !important; line-height: 21px !important; } .mso .size-14, .ie .size-14 { font-size: 16px !important; line-height: 21px !important; } .mso .size-15, .ie .size-15 { font-size: 16px !important; line-height: 23px !important; } .mso .size-16, .ie .size-16 { font-size: 16px !important; line-height: 24px !important; } .mso .size-17, .ie .size-17 { font-size: 17px !important; line-height: 26px !important; } .mso .size-18, .ie .size-18 { font-size: 18px !important; line-height: 26px !important; } .mso .size-20, .ie .size-20 { font-size: 20px !important; line-height: 28px !important; } .mso .size-22, .ie .size-22 { font-size: 22px !important; line-height: 31px !important; } .mso .size-24, .ie .size-24 { font-size: 24px !important; line-height: 32px !important; } .mso .size-26, .ie .size-26 { font-size: 26px !important; line-height: 34px !important; } .mso .size-28, .ie .size-28 { font-size: 28px !important; line-height: 36px !important; } .mso .size-30, .ie .size-30 { font-size: 30px !important; line-height: 38px !important; } .mso .size-32, .ie .size-32 { font-size: 32px !important; line-height: 40px !important; } .mso .size-34, .ie .size-34 { font-size: 34px !important; line-height: 43px !important; } .mso .size-36, .ie .size-36 { font-size: 36px !important; line-height: 43px !important; } .mso .size-40, .ie .size-40 { font-size: 40px !important; line-height: 47px !important; } .mso .size-44, .ie .size-44 { font-size: 44px !important; line-height: 50px !important; } .mso .size-48, .ie .size-48 { font-size: 48px !important; line-height: 54px !important; } .mso .size-56, .ie .size-56 { font-size: 56px !important; line-height: 60px !important; } .mso .size-64, .ie .size-64 { font-size: 64px !important; line-height: 63px !important; } </style> <!--[if !mso]><!--> <style type="text/css"> @import url(https://fonts.googleapis.com/css?family=Poppins:400,500,600,700,400italic,700italic); </style> <link href="https://fonts.googleapis.com/css?family=Poppins:400,500,600,700,400italic,700italic" rel="stylesheet" type="text/css"/> <!--<![endif]--> <style type="text/css"> .main,.mso{background-color:#fff}.logo a:hover,.logo a:focus{color:#0d1012 !important}.footer-logo a:hover,.footer-logo a:focus{color:#372d1b !important}.mso .layout-has-border{border-top:1px solid #bdbdcb;border-bottom:1px solid #bdbdcb}.mso .layout-has-bottom-border{border-bottom:1px solid #bdbdcb}.mso .border,.ie .border{background-color:#bdbdcb}.mso h1,.ie h1{}.mso h1,.ie h1{font-size:22px !important;line-height:31px !important}.mso h2,.ie h2{}.mso h3,.ie h3{}.mso .layout__inner,.ie .layout__inner{}.mso .footer__share-button p{}.mso .footer__share-button p{font-family:Ubuntu,sans-serif} </style> <meta name="robots" content="noindex,nofollow"/> <meta name="og:title" content="Take the #12in23 Challenge"/> </head> <!--[if mso]> <body class="mso"> <![endif]--> <!--[if !mso]><!--> <body class="main full-padding" style="margin: 0;padding: 0;-webkit-text-size-adjust: 100%;"> <!--<![endif]--> <table class="wrapper" style="border-collapse: collapse;table-layout: fixed;min-width: 320px;width: 100%;background-color: #fff;" cellpadding="0" cellspacing="0" role="presentation"><tbody><tr><td> <div role="banner"> <div class="header" style="margin: 0 auto;max-width: 600px;min-width: 320px; width: 320px;width: calc(28000% - 167400px);" id="emb-email-header-container"> <!--[if (mso)|(IE)]><table align="center" class="header" cellpadding="0" cellspacing="0" role="presentation"><tr><td style="width: 600px"><![endif]--> <div class="logo emb-logo-margin-box" style="font-size: 26px;line-height: 32px;margin-top: 20px;margin-bottom: 20px;color: #38434d;font-family: Avenir,sans-serif;margin-left: 20px;margin-right: 20px;" align="center"> <div class="logo-center" align="center" id="emb-email-header"><a style="text-decoration: none;transition: opacity 0.1s ease-in;color: #38434d;" href="https://exercism.org"><img style="display: block;height: auto;width: 100%;border: 0;max-width: 76px;" src="https://exercism-static.s3.eu-west-1.amazonaws.com/static/email-logo.png" alt="" width="76"/></a></div> </div> <!--[if (mso)|(IE)]></td></tr></table><![endif]--> </div> </div> <div> <div class="layout one-col fixed-width stack" style="margin: 0 auto;max-width: 600px;min-width: 320px; width: 320px;width: calc(28000% - 167400px);overflow-wrap: break-word;word-wrap: break-word;word-break: break-word;"> <div class="layout__inner" style="border-collapse: collapse;display: table;width: 100%;background-color: #ffffff;"> <!--[if (mso)|(IE)]><table align="center" cellpadding="0" cellspacing="0" role="presentation"><tr class="layout-fixed-width" style="background-color: #ffffff;"><td style="width: 600px" class="w560"><![endif]--> <div class="column" style="text-align: left;color: #130B43;font-size: 16px;line-height: 25px;font-family: Poppins,Arial,'Helvetica Neue',Helvetica,sans-serif;"> <div style="margin-left: 20px;margin-right: 20px;"> <div style="mso-line-height-rule: exactly;mso-text-raise: 11px;vertical-align: middle;"> <p style="margin-top: 16px;margin-bottom: 0;">Hi <%= @user.handle %>,</p> <p style="margin-top: 16px;margin-bottom: 0;">Last week we rolled out Track Trophies for Exercism's language tracks, a new way of marking and celebrating your progress 🏆 <p style="margin-top: 16px;margin-bottom: 0;">Based on your past achievements, we've already <% if @num_trophies == 1 %> <strong style="font-weight:600"> <%= link_to "awarded you a trophy in #{@trophy_tracks.first.title}", @trophy_tracks.first %>. </strong> You can reveal it in the new Trophy cabinet. <% elsif @trophy_tracks.size == 1 %> <strong style="font-weight:600"> <%= link_to "awarded you #{@num_trophies.humanize} trophies in #{@trophy_tracks.first.title}", @trophy_tracks.first %>. </strong> You can reveal them in the new Trophy cabinet. <% else %> <strong style="font-weight:600"> awarded you <%= @num_trophies %> trophies across <%= to_sentence(@trophy_tracks.map {|track| link_to(track.title, track)}) %>. </strong> You can reveal them in the new Trophy cabinet on each Track page. <% end %> </p> <p style="margin-top: 16px;margin-bottom: 0;"> Trophies are all about giving you that extra motivational nudge and making the learning journey a bit more fun. Hit milestones, achieve learning goals, and the trophy is yours. We also have language-specific trophies in the works. You'll be able to earn them for mastering recursion in Elixir, getting cozy with prototypes in JavaScript, or becoming a metaprogramming maestro in Ruby. </p> <p style="margin-top: 16px;margin-bottom: 0;"> Take some time to check out the new Trophies feature and I hope you enjoy the learning adventure! 🚀 </p> <p style="margin-top: 8px;margin-bottom: 20px;"> Jeremy Walker<br/> Exercism Co-founder</p> </p> </div> </div> <div style="margin-left: 20px;margin-right: 20px;"> <div class="btn btn--shadow btn--large" style="margin-bottom: 20px;"> <![if !mso]><a style="border-radius: 4px;display: inline-block;font-size: 16px;font-weight: bold;line-height: 24px;padding: 12px 24px 13px 24px;text-align: center;text-decoration: none !important;transition: opacity 0.1s ease-in;color: #ffffff !important;box-shadow: inset 0 -2px 0 0 rgba(0, 0, 0, 0.2);background-color: #2e57e8;font-family: Poppins, Trebuchet MS, Avenir, Segoe UI, sans-serif;" href="https://exercism.org"> Visit Exercism <span style="font-size:20px;margin-left:5px">➡</span> </a><![endif]> </div> </div> <!--[if (mso)|(IE)]></td></tr></table><![endif]--> </div> </div> <div style="mso-line-height-rule: exactly;line-height: 20px;font-size: 20px;">&nbsp;</div> <div class="layout one-col has-gutter stack" style="margin-bottom: 20px;max-width: 600px;min-width: 320px; width: 320px;width: calc(28000% - 167400px);overflow-wrap: break-word;word-wrap: break-word;word-break: break-word;"> <div class="layout__inner" style="border-collapse: collapse;display: table;width: 100%;"> <!--[if (mso)|(IE)]><table align="center" cellpadding="0" cellspacing="0" role="presentation"><tr><td style="width: 290px" valign="top" class="w250"><![endif]--> <div class="layout one-col has-gutter stack" style="margin: 0 auto;max-width: 600px;min-width: 320px; width: 320px;width: calc(28000% - 167400px);overflow-wrap: break-word;word-wrap: break-word;word-break: break-word;"> <div class="layout__inner" style="border-collapse: collapse;display: table;width: 100%;"> <!--[if (mso)|(IE)]><table align="center" cellpadding="0" cellspacing="0" role="presentation"><tr><td style="width: 290px" valign="top" class="w250"><![endif]--> <div class="column" style="text-align: left;color: #130B43;font-size: 16px;line-height: 25px;font-family: Poppins,Arial,'Helvetica Neue',Helvetica,sans-serif;"> <div style="margin-left: 20px;margin-right: 20px;margin-bottom:24px;border-top:1px solid #ccc"></div> <table class="column__background" style="border-collapse: collapse;table-layout: fixed;background-color: #ffffff;" cellpadding="0" cellspacing="0" width="100%" role="presentation"> <tbody><tr> <td style="text-align: left;text-align: left;color: #130B43;font-size: 16px;line-height: 25px;font-family: Poppins,Arial,'Helvetica Neue',Helvetica,sans-serif"> <div style="margin-left: 20px;margin-right: 20px"> <div style="mso-line-height-rule: exactly;mso-text-raise: 11px;vertical-align: middle;"> <h2 style="margin-top: 0;margin-bottom: 16px;font-style: normal;font-weight: normal;text-align: left;color: #130B43;font-size: 16px;line-height: 25px;font-family: Poppins,Arial,'Helvetica Neue',Helvetica,sans-serif;font-weight:600">Why am I receiving this?</h2> </div> </div> <div style="margin-left: 20px;margin-right: 20px;margin-bottom: 24px;"> <div style="mso-line-height-rule: exactly;mso-text-raise: 11px;vertical-align: middle;"> <p style="margin-top: 0;margin-bottom: 20px;">You're receiving this because you've previously signed up to <%= link_to "Exercism", root_url, style: "color: #2E57E8; font-weight:500" %> (the <strong style="font-weight:500">free, not-for-profit programming education platform</strong>) and are subscribed to our update emails, where we let you know about new things on the site.</p> <p style="margin-top: 0;margin-bottom: 20px;"> You can <%= link_to "unsubscribe from this email", unsubscribe_url(token: @user.communication_preferences.token, key: @email_communication_preferences_key), style: "color: #2E57E8; font-weight:500" %> or <%= link_to "change your notification settings", unsubscribe_url(token: @user.communication_preferences.token), style: "color: #2E57E8; font-weight:500" %> to opt out of some or all emails. </p> </div> </div> </td> </tr></tbody> </table> </div> <!--[if (mso)|(IE)]></td></tr></table><![endif]--> </div> </div> <div style="mso-line-height-rule: exactly;line-height: 20px;font-size: 20px;">&nbsp;</div> </div> <!--[if (mso)|(IE)]></table></td><![endif]--> <!--[if (mso)|(IE)]></td></tr></table><![endif]--> </div> </div> </div> </td></tr></tbody></table> <style type="text/css"> @media (max-width:619px){.email-flexible-footer .left-aligned-footer .column,.email-flexible-footer .center-aligned-footer,.email-flexible-footer .right-aligned-footer .column{max-width:101% !important;text-align:center !important;width:100% !important}.flexible-footer-logo{margin-left:0px !important;margin-right:0px !important}.email-flexible-footer .left-aligned-footer .flexible-footer__share-button__container,.email-flexible-footer .center-aligned-footer .flexible-footer__share-button__container,.email-flexible-footer .right-aligned-footer .flexible-footer__share-button__container{display:inline-block;margin-left:5px !important;margin-right:5px !important}.email-flexible-footer__additionalinfo--center{text-align:center !important}.email-flexible-footer .left-aligned-footer table,.email-flexible-footer .center-aligned-footer table,.email-flexible-footer .right-aligned-footer table{display:table !important;width:100% !important}.email-flexible-footer .footer__share-button,.email-flexible-footer .email-footer__additional-info{margin-left:20px;margin-right:20px}} </style> </body> </html>
35
0.741917
1
0.741917
web-frontend
APP_WEB
0.999009
web-frontend
0.088686
0
0.911314
dotnet/roslyn-tools
1,542
src/NuGetRepack/CLI/NuGetRepack.csproj
<?xml version="1.0" encoding="utf-8"?> <!-- 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.txt file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>$(NetFrameworkToolCurrent)</TargetFramework> <!-- Using an explicit nuspec file since NuGet Pack target currently doesn't support including dependencies in tools packages --> <IsPackable>true</IsPackable> <NuspecFile>NuGetRepack.nuspec</NuspecFile> <NuspecBasePath>$(OutputPath)</NuspecBasePath> <PackageId>RoslynTools.NuGetRepack</PackageId> <PackageDescription>Tool for updating version of NuGet packages.</PackageDescription> <PackageTags>Roslyn Build Tool NuGet version</PackageTags> <DevelopmentDependency>true</DevelopmentDependency> </PropertyGroup> <ItemGroup> <Compile Include="..\Common\NuGetVersionUpdater.cs" Link="NuGetVersionUpdater.cs" /> <Compile Include="..\Common\NuGetUtils.cs" Link="NuGetUtils.cs" /> </ItemGroup> <ItemGroup> <PackageReference Include="NuGet.Versioning" Version="$(NuGetVersioningVersion)" /> <PackageReference Include="System.IO.Packaging" Version="$(SystemIOPackagingVersion)" /> <PackageReference Include="System.ValueTuple" Version="$(SystemValueTupleVersion)" /> </ItemGroup> <ItemGroup> <InternalsVisibleTo Include="RoslynTools.NuGetRepack.Tests" /> </ItemGroup> </Project>
35
0.867895
1
0.867895
web-backend
APP_WEB
0.365459
web-backend
0.000052
0
0.999948
erwincoumans/motion_imitation
13,529
third_party/unitree_legged_sdk/pybind11/docs/advanced/exceptions.rst
Exceptions ########## Built-in C++ to Python exception translation ============================================ When Python calls C++ code through pybind11, pybind11 provides a C++ exception handler that will trap C++ exceptions, translate them to the corresponding Python exception, and raise them so that Python code can handle them. pybind11 defines translations for ``std::exception`` and its standard subclasses, and several special exception classes that translate to specific Python exceptions. Note that these are not actually Python exceptions, so they cannot be examined using the Python C API. Instead, they are pure C++ objects that pybind11 will translate the corresponding Python exception when they arrive at its exception handler. .. tabularcolumns:: |p{0.5\textwidth}|p{0.45\textwidth}| +--------------------------------------+--------------------------------------+ | Exception thrown by C++ | Translated to Python exception type | +======================================+======================================+ | :class:`std::exception` | ``RuntimeError`` | +--------------------------------------+--------------------------------------+ | :class:`std::bad_alloc` | ``MemoryError`` | +--------------------------------------+--------------------------------------+ | :class:`std::domain_error` | ``ValueError`` | +--------------------------------------+--------------------------------------+ | :class:`std::invalid_argument` | ``ValueError`` | +--------------------------------------+--------------------------------------+ | :class:`std::length_error` | ``ValueError`` | +--------------------------------------+--------------------------------------+ | :class:`std::out_of_range` | ``IndexError`` | +--------------------------------------+--------------------------------------+ | :class:`std::range_error` | ``ValueError`` | +--------------------------------------+--------------------------------------+ | :class:`std::overflow_error` | ``OverflowError`` | +--------------------------------------+--------------------------------------+ | :class:`pybind11::stop_iteration` | ``StopIteration`` (used to implement | | | custom iterators) | +--------------------------------------+--------------------------------------+ | :class:`pybind11::index_error` | ``IndexError`` (used to indicate out | | | of bounds access in ``__getitem__``, | | | ``__setitem__``, etc.) | +--------------------------------------+--------------------------------------+ | :class:`pybind11::value_error` | ``ValueError`` (used to indicate | | | wrong value passed in | | | ``container.remove(...)``) | +--------------------------------------+--------------------------------------+ | :class:`pybind11::key_error` | ``KeyError`` (used to indicate out | | | of bounds access in ``__getitem__``, | | | ``__setitem__`` in dict-like | | | objects, etc.) | +--------------------------------------+--------------------------------------+ Exception translation is not bidirectional. That is, *catching* the C++ exceptions defined above above will not trap exceptions that originate from Python. For that, catch :class:`pybind11::error_already_set`. See :ref:`below <handling_python_exceptions_cpp>` for further details. There is also a special exception :class:`cast_error` that is thrown by :func:`handle::call` when the input arguments cannot be converted to Python objects. Registering custom translators ============================== If the default exception conversion policy described above is insufficient, pybind11 also provides support for registering custom exception translators. To register a simple exception conversion that translates a C++ exception into a new Python exception using the C++ exception's ``what()`` method, a helper function is available: .. code-block:: cpp py::register_exception<CppExp>(module, "PyExp"); This call creates a Python exception class with the name ``PyExp`` in the given module and automatically converts any encountered exceptions of type ``CppExp`` into Python exceptions of type ``PyExp``. It is possible to specify base class for the exception using the third parameter, a `handle`: .. code-block:: cpp py::register_exception<CppExp>(module, "PyExp", PyExc_RuntimeError); Then `PyExp` can be caught both as `PyExp` and `RuntimeError`. The class objects of the built-in Python exceptions are listed in the Python documentation on `Standard Exceptions <https://docs.python.org/3/c-api/exceptions.html#standard-exceptions>`_. The default base class is `PyExc_Exception`. When more advanced exception translation is needed, the function ``py::register_exception_translator(translator)`` can be used to register functions that can translate arbitrary exception types (and which may include additional logic to do so). The function takes a stateless callable (e.g. a function pointer or a lambda function without captured variables) with the call signature ``void(std::exception_ptr)``. When a C++ exception is thrown, the registered exception translators are tried in reverse order of registration (i.e. the last registered translator gets the first shot at handling the exception). Inside the translator, ``std::rethrow_exception`` should be used within a try block to re-throw the exception. One or more catch clauses to catch the appropriate exceptions should then be used with each clause using ``PyErr_SetString`` to set a Python exception or ``ex(string)`` to set the python exception to a custom exception type (see below). To declare a custom Python exception type, declare a ``py::exception`` variable and use this in the associated exception translator (note: it is often useful to make this a static declaration when using it inside a lambda expression without requiring capturing). The following example demonstrates this for a hypothetical exception classes ``MyCustomException`` and ``OtherException``: the first is translated to a custom python exception ``MyCustomError``, while the second is translated to a standard python RuntimeError: .. code-block:: cpp static py::exception<MyCustomException> exc(m, "MyCustomError"); py::register_exception_translator([](std::exception_ptr p) { try { if (p) std::rethrow_exception(p); } catch (const MyCustomException &e) { exc(e.what()); } catch (const OtherException &e) { PyErr_SetString(PyExc_RuntimeError, e.what()); } }); Multiple exceptions can be handled by a single translator, as shown in the example above. If the exception is not caught by the current translator, the previously registered one gets a chance. If none of the registered exception translators is able to handle the exception, it is handled by the default converter as described in the previous section. .. seealso:: The file :file:`tests/test_exceptions.cpp` contains examples of various custom exception translators and custom exception types. .. note:: Call either ``PyErr_SetString`` or a custom exception's call operator (``exc(string)``) for every exception caught in a custom exception translator. Failure to do so will cause Python to crash with ``SystemError: error return without exception set``. Exceptions that you do not plan to handle should simply not be caught, or may be explicitly (re-)thrown to delegate it to the other, previously-declared existing exception translators. .. _handling_python_exceptions_cpp: Handling exceptions from Python in C++ ====================================== When C++ calls Python functions, such as in a callback function or when manipulating Python objects, and Python raises an ``Exception``, pybind11 converts the Python exception into a C++ exception of type :class:`pybind11::error_already_set` whose payload contains a C++ string textual summary and the actual Python exception. ``error_already_set`` is used to propagate Python exception back to Python (or possibly, handle them in C++). .. tabularcolumns:: |p{0.5\textwidth}|p{0.45\textwidth}| +--------------------------------------+--------------------------------------+ | Exception raised in Python | Thrown as C++ exception type | +======================================+======================================+ | Any Python ``Exception`` | :class:`pybind11::error_already_set` | +--------------------------------------+--------------------------------------+ For example: .. code-block:: cpp try { // open("missing.txt", "r") auto file = py::module_::import("io").attr("open")("missing.txt", "r"); auto text = file.attr("read")(); file.attr("close")(); } catch (py::error_already_set &e) { if (e.matches(PyExc_FileNotFoundError)) { py::print("missing.txt not found"); } else if (e.match(PyExc_PermissionError)) { py::print("missing.txt found but not accessible"); } else { throw; } } Note that C++ to Python exception translation does not apply here, since that is a method for translating C++ exceptions to Python, not vice versa. The error raised from Python is always ``error_already_set``. This example illustrates this behavior: .. code-block:: cpp try { py::eval("raise ValueError('The Ring')"); } catch (py::value_error &boromir) { // Boromir never gets the ring assert(false); } catch (py::error_already_set &frodo) { // Frodo gets the ring py::print("I will take the ring"); } try { // py::value_error is a request for pybind11 to raise a Python exception throw py::value_error("The ball"); } catch (py::error_already_set &cat) { // cat won't catch the ball since // py::value_error is not a Python exception assert(false); } catch (py::value_error &dog) { // dog will catch the ball py::print("Run Spot run"); throw; // Throw it again (pybind11 will raise ValueError) } Handling errors from the Python C API ===================================== Where possible, use :ref:`pybind11 wrappers <wrappers>` instead of calling the Python C API directly. When calling the Python C API directly, in addition to manually managing reference counts, one must follow the pybind11 error protocol, which is outlined here. After calling the Python C API, if Python returns an error, ``throw py::error_already_set();``, which allows pybind11 to deal with the exception and pass it back to the Python interpreter. This includes calls to the error setting functions such as ``PyErr_SetString``. .. code-block:: cpp PyErr_SetString(PyExc_TypeError, "C API type error demo"); throw py::error_already_set(); // But it would be easier to simply... throw py::type_error("pybind11 wrapper type error"); Alternately, to ignore the error, call `PyErr_Clear <https://docs.python.org/3/c-api/exceptions.html#c.PyErr_Clear>`_. Any Python error must be thrown or cleared, or Python/pybind11 will be left in an invalid state. .. _unraisable_exceptions: Handling unraisable exceptions ============================== If a Python function invoked from a C++ destructor or any function marked ``noexcept(true)`` (collectively, "noexcept functions") throws an exception, there is no way to propagate the exception, as such functions may not throw. Should they throw or fail to catch any exceptions in their call graph, the C++ runtime calls ``std::terminate()`` to abort immediately. Similarly, Python exceptions raised in a class's ``__del__`` method do not propagate, but are logged by Python as an unraisable error. In Python 3.8+, a `system hook is triggered <https://docs.python.org/3/library/sys.html#sys.unraisablehook>`_ and an auditing event is logged. Any noexcept function should have a try-catch block that traps class:`error_already_set` (or any other exception that can occur). Note that pybind11 wrappers around Python exceptions such as :class:`pybind11::value_error` are *not* Python exceptions; they are C++ exceptions that pybind11 catches and converts to Python exceptions. Noexcept functions cannot propagate these exceptions either. A useful approach is to convert them to Python exceptions and then ``discard_as_unraisable`` as shown below. .. code-block:: cpp void nonthrowing_func() noexcept(true) { try { // ... } catch (py::error_already_set &eas) { // Discard the Python error using Python APIs, using the C++ magic // variable __func__. Python already knows the type and value and of the // exception object. eas.discard_as_unraisable(__func__); } catch (const std::exception &e) { // Log and discard C++ exceptions. third_party::log(e); } } .. versionadded:: 2.6
35
0.848966
1
0.848966
cli-devtools
APP_WEB
0.450407
cli-devtools
0.499928
0
0.500072
perplexityai/perplexity-py
3,580
CONTRIBUTING.md
## Setting up the environment ### With Rye We use [Rye](https://rye.astral.sh/) to manage dependencies because it will automatically provision a Python environment with the expected Python version. To set it up, run: ```sh $ ./scripts/bootstrap ``` Or [install Rye manually](https://rye.astral.sh/guide/installation/) and run: ```sh $ rye sync --all-features ``` You can then run scripts using `rye run python script.py` or by activating the virtual environment: ```sh # Activate the virtual environment - https://docs.python.org/3/library/venv.html#how-venvs-work $ source .venv/bin/activate # now you can omit the `rye run` prefix $ python script.py ``` ### Without Rye Alternatively if you don't want to install `Rye`, you can stick with the standard `pip` setup by ensuring you have the Python version specified in `.python-version`, create a virtual environment however you desire and then install dependencies using this command: ```sh $ pip install -r requirements-dev.lock ``` ## Modifying/Adding code Most of the SDK is generated code. Modifications to code will be persisted between generations, but may result in merge conflicts between manual patches and changes from the generator. The generator will never modify the contents of the `src/perplexity/lib/` and `examples/` directories. ## Adding and running examples All files in the `examples/` directory are not modified by the generator and can be freely edited or added to. ```py # add an example to examples/<your-example>.py #!/usr/bin/env -S rye run python … ``` ```sh $ chmod +x examples/<your-example>.py # run the example against your api $ ./examples/<your-example>.py ``` ## Using the repository from source If you’d like to use the repository from source, you can either install from git or link to a cloned repository: To install via git: ```sh $ pip install git+ssh://[email protected]/perplexityai/perplexity-py.git ``` Alternatively, you can build from source and install the wheel file: Building this package will create two files in the `dist/` directory, a `.tar.gz` containing the source files and a `.whl` that can be used to install the package efficiently. To create a distributable version of the library, all you have to do is run this command: ```sh $ rye build # or $ python -m build ``` Then to install: ```sh $ pip install ./path-to-wheel-file.whl ``` ## Running tests Most tests require you to [set up a mock server](https://github.com/stoplightio/prism) against the OpenAPI spec to run the tests. ```sh # you will need npm installed $ npx prism mock path/to/your/openapi.yml ``` ```sh $ ./scripts/test ``` ## Linting and formatting This repository uses [ruff](https://github.com/astral-sh/ruff) and [black](https://github.com/psf/black) to format the code in the repository. To lint: ```sh $ ./scripts/lint ``` To format and fix all ruff issues automatically: ```sh $ ./scripts/format ``` ## Publishing and releases Changes made to this repository via the automated release PR pipeline should publish to PyPI automatically. If the changes aren't made through the automated pipeline, you may want to make releases manually. ### Publish with a GitHub workflow You can release to package managers by using [the `Publish PyPI` GitHub action](https://www.github.com/perplexityai/perplexity-py/actions/workflows/publish-pypi.yml). This requires a setup organization or repository secret to be set up. ### Publish manually If you need to manually release a package, you can run the `bin/publish-pypi` script with a `PYPI_TOKEN` set on the environment.
35
0.800022
1
0.800022
devops-infra
OPS
0.425592
devops-infra
0.000009
0
0.999991
FluxpointDev/MultiRPC
15,595
MultiRPC/RPC.cs
using System; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading.Tasks; using System.Timers; using System.Windows; using DiscordRPC; using DiscordRPC.Message; using MultiRPC.GUI; using MultiRPC.GUI.Pages; using MultiRPC.GUI.Views; using MultiRPC.JsonClasses; namespace MultiRPC { public static class RPC { public enum RPCType { MultiRPC, Custom } public const ulong MultiRPCID = 450894077165043722; public static RPCType Type; public static RichPresence Presence { get; private set; } = new RichPresence(); private static RichPresence BackupPresence; private static DateTime _startTime; private static Timer _uptime; public static ulong IDToUse; private static DiscordRpcClient RPCClient; private static string _pageUserWasOnWhenStarted; public static event EventHandler RPCShutdown; /// <summary> /// Has rpc failed /// </summary> private static bool _failed; /// <summary> /// Is afk rpc status on /// </summary> public static bool AFK; public static bool IsRPCRunning { get; private set; } private static async Task<bool> CheckPresence(string text) { if (!string.IsNullOrWhiteSpace(text) && !App.Config.InviteWarn && text.ToLower().Contains("discord.gg")) { var result = await CustomMessageBox.Show(App.Text.AdvertisingWarning, App.Text.Warning, MessageBoxButton.OKCancel, MessageBoxImage.Warning); if (result == MessageBoxResult.OK) { App.Config.InviteWarn = true; await App.Config.Save(); App.Logging.Application(App.Text.AdvertisingWarningDisabled); return true; } if (result == MessageBoxResult.Cancel) { return false; } } return true; } public static bool Equals(this RichPresence richPresence, CustomProfile profile) { if (richPresence.Details != profile.Text1) { return false; } if (richPresence.State != profile.Text2) { return false; } if (richPresence.Timestamps == null && profile.ShowTime || richPresence.Timestamps != null && !profile.ShowTime) { return false; } var assets = !string.IsNullOrWhiteSpace(profile.LargeKey) || !string.IsNullOrWhiteSpace(profile.SmallKey) ? new Assets { LargeImageKey = profile.LargeKey, LargeImageText = profile.LargeText, SmallImageKey = profile.SmallKey, SmallImageText = profile.SmallText } : null; return richPresence.Assets == assets; } public static Task UpdateType(RPCType type) { if (!IsRPCRunning) { Type = type; } return Task.CompletedTask; } public static async Task Start() { //Check that the presence isn't ban worthy if (!await CheckPresence(Presence.Details) || !await CheckPresence(Presence.State)) { return; } App.Logging.Application(App.Text.StartingRpc); _failed = true; var pipeCount = 0; var discordClientName = "Discord"; var foundClient = false; //Get the client to connect to if (App.Config.ClientToUse != 0) { var pipes = Directory.GetFiles(@"\\.\pipe\"); for (var i = 0; i < pipes.Length; i++) { var pipe = pipes[i].Split('\\').Last(); switch (pipe) { case "discord-sock": if (App.Config.ClientToUse == 1) { discordClientName = "Discord"; foundClient = true; } break; case "discordptb-sock": if (App.Config.ClientToUse == 2) { discordClientName = "Discord PTB"; foundClient = true; } break; case "discordcanary-sock": if (App.Config.ClientToUse == 3) { discordClientName = "Discord Canary"; foundClient = true; } break; } if (foundClient) { break; } if (pipe.StartsWith("discord")) { pipeCount++; } } } //Log the client we are going to connect to App.Logging.Application($"Discord {App.Text.Client}: {discordClientName} ({pipeCount})"); RPCClient = new DiscordRpcClient(IDToUse.ToString(), pipeCount, App.Logging, true); //Set up events RPCClient.OnConnectionEstablished += Client_OnConnectionEstablished; RPCClient.OnConnectionFailed += Client_OnConnectionFailed; RPCClient.OnPresenceUpdate += Client_OnPresenceUpdate; RPCClient.OnReady += Client_OnReady; if (!AFK) { await MainPage._MainPage.Dispatcher.InvokeAsync(() => MainPage._MainPage.btnUpdate.IsEnabled = true); } //Show that we are going to load things™ await MainPage._MainPage.frmRPCPreview.Dispatcher.InvokeAsync(async () => { await ((RPCPreview)MainPage._MainPage.frmRPCPreview.Content).UpdateUIViewType(RPCPreview.ViewType .Loading); MainPage._MainPage.rCon.Text = App.Text.Loading; MainPage._MainPage.btnStart.Style = (Style)MainPage._MainPage.Resources["ButtonRed"]; _pageUserWasOnWhenStarted = MainPage._MainPage.btnStart.Content.ToString(); MainPage._MainPage.btnStart.Content = App.Text.Shutdown; }); //Connect RPCClient.Initialize(); //Set up the time that will show (if user wants it) _startTime = DateTime.UtcNow; if (Presence.Timestamps != null) { Presence.Timestamps.Start = _startTime; } //Send the presence RPCClient.SetPresence(Presence); if (MasterCustomPage._MasterCustomPage != null) { MasterCustomPage._MasterCustomPage.Dispatcher.InvokeAsync(() => { //Disable buttons unless it's the same ClientID (still not allowed to mess with the Client ID tho) var profileClientID = !AFK && MasterCustomPage.CurrentButton != null && MainPage._MainPage.frmContent.Content is MasterCustomPage ? MasterCustomPage.Profiles[MasterCustomPage.CurrentButton.Content.ToString()].ClientID : "0"; for (var i = 0; i < MasterCustomPage.ProfileButtons.Count; i++) { if (profileClientID == "0" || MasterCustomPage.Profiles[MasterCustomPage.ProfileButtons[i].Content.ToString()] .ClientID != profileClientID) { MasterCustomPage.ProfileButtons[i].IsEnabled = false; } } MasterCustomPage._MasterCustomPage.imgProfileAdd.IsEnabled = false; MasterCustomPage._MasterCustomPage.imgProfileDelete.IsEnabled = false; }); CustomPage._CustomPage.Dispatcher.InvokeAsync(() => CustomPage._CustomPage.tbClientID.IsEnabled = false); } IsRPCRunning = true; } public static void SetPresence(string text1, string text2, string largeKey, string largeText, string smallKey, string smallText, bool showTime, bool fromTrigger = false) { if (AFK) { return; } if (fromTrigger) { BackupPresence ??= Presence; } else if (BackupPresence != null) { Presence = BackupPresence; BackupPresence = null; return; } Presence.Details = text1; Presence.State = text2; Presence.Assets = !string.IsNullOrWhiteSpace(largeKey) || !string.IsNullOrWhiteSpace(smallKey) ? new Assets { LargeImageKey = largeKey, LargeImageText = largeText, SmallImageKey = smallKey, SmallImageText = smallText } : null; Presence.Timestamps = showTime ? new Timestamps() : null; } public static void SetPresence(CustomProfile profile, bool fromTrigger = false) => SetPresence(profile?.Text1, profile?.Text2, profile?.LargeKey, profile?.LargeText, profile?.SmallKey, profile?.SmallText, profile?.ShowTime ?? false, fromTrigger); public static async void Update() { if (IsRPCRunning) { if (Presence.Timestamps != null) { Presence.Timestamps.Start = _startTime; } RPCClient.SetPresence(Presence); } else { await Start(); } } private static async void Client_OnReady(object sender, ReadyMessage args) { var user = $"{args.User.Username}#{args.User.Discriminator:0000}"; if (App.Config.LastUser != user) { App.Config.LastUser = user; await App.Config.Save(); } App.Logging.LogEvent(App.Text.Client, $"{App.Text.Hi} {user} 👋"); //Make update timer to update time in GUI _uptime = new Timer(new TimeSpan(0, 0, 1).TotalMilliseconds); if (Presence.Timestamps != null) { _uptime.Start(); } _uptime.Elapsed += Uptime_Elapsed; MainPage._MainPage.Dispatcher.Invoke(() => { MainPage._MainPage.rUsername.Text = user; MainPage._MainPage.rCon.Text = App.Text.Connected; }); } private static void Uptime_Elapsed(object sender, ElapsedEventArgs e) { var ts = TimeSpan.FromTicks(DateTime.UtcNow.Ticks - _startTime.Ticks); MainPage._MainPage.frmRPCPreview.Dispatcher.Invoke(async () => { await ((RPCPreview) MainPage._MainPage.frmRPCPreview.Content).UpdateTime(ts); }); } private static void Client_OnPresenceUpdate(object sender, PresenceMessage args) { MainPage._MainPage.frmRPCPreview.Dispatcher.Invoke(() => { MainPage._MainPage.frmRPCPreview.Content = new RPCPreview(args); if (Presence.Timestamps != null) { _uptime.Start(); } else { _uptime.Stop(); } MainPage._MainPage.rCon.Text = App.Text.Connected; }); } private static void Client_OnConnectionFailed(object sender, ConnectionFailedMessage args) { if (!_failed) { _failed = true; MainPage._MainPage.frmRPCPreview.Dispatcher.Invoke(async () => { await ((RPCPreview) MainPage._MainPage.frmRPCPreview.Content).UpdateUIViewType( RPCPreview.ViewType.Error, App.Text.AttemptingToReconnect); MainPage._MainPage.rCon.Text = App.Text.Loading; }); } } private static void Client_OnConnectionEstablished(object sender, ConnectionEstablishedMessage args) { _failed = false; } public static void Shutdown() { App.Logging.LogEvent(App.Text.Client, App.Text.ShuttingDown); _uptime?.Stop(); _uptime?.Dispose(); RPCClient?.Dispose(); MainPage._MainPage.frmRPCPreview.Dispatcher.Invoke(async () => { await ((RPCPreview) MainPage._MainPage.frmRPCPreview.Content).UpdateUIViewType(RPCPreview.ViewType .Default); MainPage._MainPage.btnStart.SetResourceReference(FrameworkElement.StyleProperty, "ButtonGreen"); switch (MainPage._MainPage.frmContent.Content) { case MultiRPCPage multiRpcPage: MainPage._MainPage.btnStart.Content = App.Text.Start + " MultiRPC"; multiRpcPage.CanRunRPC(); break; case MasterCustomPage _CustomPage: MainPage._MainPage.btnStart.Content = App.Text.StartCustom; _CustomPage.CustomPage.CanRunRPC(); break; default: MainPage._MainPage.btnStart.Content = _pageUserWasOnWhenStarted.Contains("MultiRPC") ? App.Text.Start + " MultiRPC" : App.Text.StartCustom; break; } MainPage._MainPage.btnUpdate.IsEnabled = false; MainPage._MainPage.rCon.Text = App.Text.Disconnected; }); AFK = false; if (MasterCustomPage._MasterCustomPage != null) { MasterCustomPage._MasterCustomPage.Dispatcher.Invoke(() => { if (MasterCustomPage._MasterCustomPage != null) { for (var i = 0; i < MasterCustomPage.ProfileButtons.Count; i++) { MasterCustomPage.ProfileButtons[i].IsEnabled = true; } MasterCustomPage._MasterCustomPage.imgProfileAdd.IsEnabled = true; MasterCustomPage._MasterCustomPage.imgProfileDelete.IsEnabled = true; } }); CustomPage._CustomPage.Dispatcher.Invoke(() => CustomPage._CustomPage.tbClientID.IsEnabled = true); } IsRPCRunning = false; RPCShutdown?.Invoke(null, EventArgs.Empty); } } }
35
0.957781
1
0.957781
desktop-app
APP_WEB
0.598976
desktop-app
0.979409
1
0.979409
pulumi/pulumi-aws
11,559
sdk/java/src/main/java/com/pulumi/aws/cloudformation/inputs/StackSetInstanceOperationPreferencesArgs.java
// *** WARNING: this file was generated by pulumi-language-java. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** package com.pulumi.aws.cloudformation.inputs; import com.pulumi.core.Output; import com.pulumi.core.annotations.Import; import java.lang.Integer; import java.lang.String; import java.util.List; import java.util.Objects; import java.util.Optional; import javax.annotation.Nullable; public final class StackSetInstanceOperationPreferencesArgs extends com.pulumi.resources.ResourceArgs { public static final StackSetInstanceOperationPreferencesArgs Empty = new StackSetInstanceOperationPreferencesArgs(); /** * Specifies how the concurrency level behaves during the operation execution. Valid values are `STRICT_FAILURE_TOLERANCE` and `SOFT_FAILURE_TOLERANCE`. * */ @Import(name="concurrencyMode") private @Nullable Output<String> concurrencyMode; /** * @return Specifies how the concurrency level behaves during the operation execution. Valid values are `STRICT_FAILURE_TOLERANCE` and `SOFT_FAILURE_TOLERANCE`. * */ public Optional<Output<String>> concurrencyMode() { return Optional.ofNullable(this.concurrencyMode); } /** * Number of accounts, per Region, for which this operation can fail before AWS CloudFormation stops the operation in that Region. * */ @Import(name="failureToleranceCount") private @Nullable Output<Integer> failureToleranceCount; /** * @return Number of accounts, per Region, for which this operation can fail before AWS CloudFormation stops the operation in that Region. * */ public Optional<Output<Integer>> failureToleranceCount() { return Optional.ofNullable(this.failureToleranceCount); } /** * Percentage of accounts, per Region, for which this stack operation can fail before AWS CloudFormation stops the operation in that Region. * */ @Import(name="failureTolerancePercentage") private @Nullable Output<Integer> failureTolerancePercentage; /** * @return Percentage of accounts, per Region, for which this stack operation can fail before AWS CloudFormation stops the operation in that Region. * */ public Optional<Output<Integer>> failureTolerancePercentage() { return Optional.ofNullable(this.failureTolerancePercentage); } /** * Maximum number of accounts in which to perform this operation at one time. * */ @Import(name="maxConcurrentCount") private @Nullable Output<Integer> maxConcurrentCount; /** * @return Maximum number of accounts in which to perform this operation at one time. * */ public Optional<Output<Integer>> maxConcurrentCount() { return Optional.ofNullable(this.maxConcurrentCount); } /** * Maximum percentage of accounts in which to perform this operation at one time. * */ @Import(name="maxConcurrentPercentage") private @Nullable Output<Integer> maxConcurrentPercentage; /** * @return Maximum percentage of accounts in which to perform this operation at one time. * */ public Optional<Output<Integer>> maxConcurrentPercentage() { return Optional.ofNullable(this.maxConcurrentPercentage); } /** * Concurrency type of deploying StackSets operations in Regions, could be in parallel or one Region at a time. Valid values are `SEQUENTIAL` and `PARALLEL`. * */ @Import(name="regionConcurrencyType") private @Nullable Output<String> regionConcurrencyType; /** * @return Concurrency type of deploying StackSets operations in Regions, could be in parallel or one Region at a time. Valid values are `SEQUENTIAL` and `PARALLEL`. * */ public Optional<Output<String>> regionConcurrencyType() { return Optional.ofNullable(this.regionConcurrencyType); } /** * Order of the Regions in where you want to perform the stack operation. * */ @Import(name="regionOrders") private @Nullable Output<List<String>> regionOrders; /** * @return Order of the Regions in where you want to perform the stack operation. * */ public Optional<Output<List<String>>> regionOrders() { return Optional.ofNullable(this.regionOrders); } private StackSetInstanceOperationPreferencesArgs() {} private StackSetInstanceOperationPreferencesArgs(StackSetInstanceOperationPreferencesArgs $) { this.concurrencyMode = $.concurrencyMode; this.failureToleranceCount = $.failureToleranceCount; this.failureTolerancePercentage = $.failureTolerancePercentage; this.maxConcurrentCount = $.maxConcurrentCount; this.maxConcurrentPercentage = $.maxConcurrentPercentage; this.regionConcurrencyType = $.regionConcurrencyType; this.regionOrders = $.regionOrders; } public static Builder builder() { return new Builder(); } public static Builder builder(StackSetInstanceOperationPreferencesArgs defaults) { return new Builder(defaults); } public static final class Builder { private StackSetInstanceOperationPreferencesArgs $; public Builder() { $ = new StackSetInstanceOperationPreferencesArgs(); } public Builder(StackSetInstanceOperationPreferencesArgs defaults) { $ = new StackSetInstanceOperationPreferencesArgs(Objects.requireNonNull(defaults)); } /** * @param concurrencyMode Specifies how the concurrency level behaves during the operation execution. Valid values are `STRICT_FAILURE_TOLERANCE` and `SOFT_FAILURE_TOLERANCE`. * * @return builder * */ public Builder concurrencyMode(@Nullable Output<String> concurrencyMode) { $.concurrencyMode = concurrencyMode; return this; } /** * @param concurrencyMode Specifies how the concurrency level behaves during the operation execution. Valid values are `STRICT_FAILURE_TOLERANCE` and `SOFT_FAILURE_TOLERANCE`. * * @return builder * */ public Builder concurrencyMode(String concurrencyMode) { return concurrencyMode(Output.of(concurrencyMode)); } /** * @param failureToleranceCount Number of accounts, per Region, for which this operation can fail before AWS CloudFormation stops the operation in that Region. * * @return builder * */ public Builder failureToleranceCount(@Nullable Output<Integer> failureToleranceCount) { $.failureToleranceCount = failureToleranceCount; return this; } /** * @param failureToleranceCount Number of accounts, per Region, for which this operation can fail before AWS CloudFormation stops the operation in that Region. * * @return builder * */ public Builder failureToleranceCount(Integer failureToleranceCount) { return failureToleranceCount(Output.of(failureToleranceCount)); } /** * @param failureTolerancePercentage Percentage of accounts, per Region, for which this stack operation can fail before AWS CloudFormation stops the operation in that Region. * * @return builder * */ public Builder failureTolerancePercentage(@Nullable Output<Integer> failureTolerancePercentage) { $.failureTolerancePercentage = failureTolerancePercentage; return this; } /** * @param failureTolerancePercentage Percentage of accounts, per Region, for which this stack operation can fail before AWS CloudFormation stops the operation in that Region. * * @return builder * */ public Builder failureTolerancePercentage(Integer failureTolerancePercentage) { return failureTolerancePercentage(Output.of(failureTolerancePercentage)); } /** * @param maxConcurrentCount Maximum number of accounts in which to perform this operation at one time. * * @return builder * */ public Builder maxConcurrentCount(@Nullable Output<Integer> maxConcurrentCount) { $.maxConcurrentCount = maxConcurrentCount; return this; } /** * @param maxConcurrentCount Maximum number of accounts in which to perform this operation at one time. * * @return builder * */ public Builder maxConcurrentCount(Integer maxConcurrentCount) { return maxConcurrentCount(Output.of(maxConcurrentCount)); } /** * @param maxConcurrentPercentage Maximum percentage of accounts in which to perform this operation at one time. * * @return builder * */ public Builder maxConcurrentPercentage(@Nullable Output<Integer> maxConcurrentPercentage) { $.maxConcurrentPercentage = maxConcurrentPercentage; return this; } /** * @param maxConcurrentPercentage Maximum percentage of accounts in which to perform this operation at one time. * * @return builder * */ public Builder maxConcurrentPercentage(Integer maxConcurrentPercentage) { return maxConcurrentPercentage(Output.of(maxConcurrentPercentage)); } /** * @param regionConcurrencyType Concurrency type of deploying StackSets operations in Regions, could be in parallel or one Region at a time. Valid values are `SEQUENTIAL` and `PARALLEL`. * * @return builder * */ public Builder regionConcurrencyType(@Nullable Output<String> regionConcurrencyType) { $.regionConcurrencyType = regionConcurrencyType; return this; } /** * @param regionConcurrencyType Concurrency type of deploying StackSets operations in Regions, could be in parallel or one Region at a time. Valid values are `SEQUENTIAL` and `PARALLEL`. * * @return builder * */ public Builder regionConcurrencyType(String regionConcurrencyType) { return regionConcurrencyType(Output.of(regionConcurrencyType)); } /** * @param regionOrders Order of the Regions in where you want to perform the stack operation. * * @return builder * */ public Builder regionOrders(@Nullable Output<List<String>> regionOrders) { $.regionOrders = regionOrders; return this; } /** * @param regionOrders Order of the Regions in where you want to perform the stack operation. * * @return builder * */ public Builder regionOrders(List<String> regionOrders) { return regionOrders(Output.of(regionOrders)); } /** * @param regionOrders Order of the Regions in where you want to perform the stack operation. * * @return builder * */ public Builder regionOrders(String... regionOrders) { return regionOrders(List.of(regionOrders)); } public StackSetInstanceOperationPreferencesArgs build() { return $; } } }
35
0.848827
1
0.848827
devops-infra
OPS
0.511287
devops-infra
0.862252
1
0.862252
KhronosGroup/SPIRV-LLVM
8,443
test/Transforms/ObjCARC/rv.ll
; RUN: opt -objc-arc -S < %s | FileCheck %s target datalayout = "e-p:64:64:64" declare i8* @objc_retain(i8*) declare i8* @objc_retainAutoreleasedReturnValue(i8*) declare void @objc_release(i8*) declare i8* @objc_autorelease(i8*) declare i8* @objc_autoreleaseReturnValue(i8*) declare i8* @objc_retainAutoreleaseReturnValue(i8*) declare void @objc_autoreleasePoolPop(i8*) declare void @objc_autoreleasePoolPush() declare i8* @objc_retainBlock(i8*) declare i8* @objc_retainedObject(i8*) declare i8* @objc_unretainedObject(i8*) declare i8* @objc_unretainedPointer(i8*) declare void @use_pointer(i8*) declare void @callee() declare void @callee_fnptr(void ()*) declare void @invokee() declare i8* @returner() ; Test that retain+release elimination is suppressed when the ; retain is an objc_retainAutoreleasedReturnValue, since it's ; better to do the RV optimization. ; CHECK-LABEL: define void @test0( ; CHECK-NEXT: entry: ; CHECK-NEXT: %x = call i8* @returner ; CHECK-NEXT: %0 = tail call i8* @objc_retainAutoreleasedReturnValue(i8* %x) [[NUW:#[0-9]+]] ; CHECK: t: ; CHECK-NOT: @objc_ ; CHECK: return: ; CHECK-NEXT: call void @objc_release(i8* %x) ; CHECK-NEXT: ret void ; CHECK-NEXT: } define void @test0(i1 %p) nounwind { entry: %x = call i8* @returner() %0 = call i8* @objc_retainAutoreleasedReturnValue(i8* %x) br i1 %p, label %t, label %return t: call void @use_pointer(i8* %x) store i8 0, i8* %x br label %return return: call void @objc_release(i8* %x) nounwind ret void } ; Delete no-ops. ; CHECK-LABEL: define void @test2( ; CHECK-NOT: @objc_ ; CHECK: } define void @test2() { call i8* @objc_retainAutoreleasedReturnValue(i8* null) call i8* @objc_autoreleaseReturnValue(i8* null) ; call i8* @objc_retainAutoreleaseReturnValue(i8* null) ; TODO ret void } ; Delete a redundant retainRV,autoreleaseRV when forwaring a call result ; directly to a return value. ; CHECK-LABEL: define i8* @test3( ; CHECK: call i8* @returner() ; CHECK-NEXT: ret i8* %call define i8* @test3() { entry: %call = call i8* @returner() %0 = call i8* @objc_retainAutoreleasedReturnValue(i8* %call) nounwind %1 = call i8* @objc_autoreleaseReturnValue(i8* %0) nounwind ret i8* %1 } ; Delete a redundant retain,autoreleaseRV when forwaring a call result ; directly to a return value. ; CHECK-LABEL: define i8* @test4( ; CHECK: call i8* @returner() ; CHECK-NEXT: ret i8* %call define i8* @test4() { entry: %call = call i8* @returner() %0 = call i8* @objc_retain(i8* %call) nounwind %1 = call i8* @objc_autoreleaseReturnValue(i8* %0) nounwind ret i8* %1 } ; Delete a redundant fused retain+autoreleaseRV when forwaring a call result ; directly to a return value. ; TODO ; HECK: define i8* @test5 ; HECK: call i8* @returner() ; HECK-NEXT: ret i8* %call ;define i8* @test5() { ;entry: ; %call = call i8* @returner() ; %0 = call i8* @objc_retainAutoreleaseReturnValue(i8* %call) nounwind ; ret i8* %0 ;} ; Don't eliminate objc_retainAutoreleasedReturnValue by merging it into ; an objc_autorelease. ; TODO? Merge objc_retainAutoreleasedReturnValue and objc_autorelease into ; objc_retainAutoreleasedReturnValueAutorelease and merge ; objc_retainAutoreleasedReturnValue and objc_autoreleaseReturnValue ; into objc_retainAutoreleasedReturnValueAutoreleaseReturnValue? ; Those entrypoints don't exist yet though. ; CHECK-LABEL: define i8* @test7( ; CHECK: call i8* @objc_retainAutoreleasedReturnValue(i8* %p) ; CHECK: %t = tail call i8* @objc_autoreleaseReturnValue(i8* %p) define i8* @test7() { %p = call i8* @returner() call i8* @objc_retainAutoreleasedReturnValue(i8* %p) %t = call i8* @objc_autoreleaseReturnValue(i8* %p) call void @use_pointer(i8* %p) ret i8* %t } ; CHECK-LABEL: define i8* @test7b( ; CHECK: call i8* @objc_retain(i8* %p) ; CHECK: %t = tail call i8* @objc_autoreleaseReturnValue(i8* %p) define i8* @test7b() { %p = call i8* @returner() call void @use_pointer(i8* %p) call i8* @objc_retainAutoreleasedReturnValue(i8* %p) %t = call i8* @objc_autoreleaseReturnValue(i8* %p) ret i8* %p } ; Don't apply the RV optimization to autorelease if there's no retain. ; CHECK: define i8* @test9(i8* %p) ; CHECK: call i8* @objc_autorelease(i8* %p) define i8* @test9(i8* %p) { call i8* @objc_autorelease(i8* %p) ret i8* %p } ; Do not apply the RV optimization. ; CHECK: define i8* @test10(i8* %p) ; CHECK: tail call i8* @objc_retain(i8* %p) [[NUW]] ; CHECK: call i8* @objc_autorelease(i8* %p) [[NUW]] ; CHECK-NEXT: ret i8* %p define i8* @test10(i8* %p) { %1 = call i8* @objc_retain(i8* %p) %2 = call i8* @objc_autorelease(i8* %p) ret i8* %p } ; Don't do the autoreleaseRV optimization because @use_pointer ; could undo the retain. ; CHECK: define i8* @test11(i8* %p) ; CHECK: tail call i8* @objc_retain(i8* %p) ; CHECK-NEXT: call void @use_pointer(i8* %p) ; CHECK: call i8* @objc_autorelease(i8* %p) ; CHECK-NEXT: ret i8* %p define i8* @test11(i8* %p) { %1 = call i8* @objc_retain(i8* %p) call void @use_pointer(i8* %p) %2 = call i8* @objc_autorelease(i8* %p) ret i8* %p } ; Don't spoil the RV optimization. ; CHECK: define i8* @test12(i8* %p) ; CHECK: tail call i8* @objc_retain(i8* %p) ; CHECK: call void @use_pointer(i8* %p) ; CHECK: tail call i8* @objc_autoreleaseReturnValue(i8* %p) ; CHECK: ret i8* %p define i8* @test12(i8* %p) { %1 = call i8* @objc_retain(i8* %p) call void @use_pointer(i8* %p) %2 = call i8* @objc_autoreleaseReturnValue(i8* %p) ret i8* %p } ; Don't zap the objc_retainAutoreleasedReturnValue. ; CHECK-LABEL: define i8* @test13( ; CHECK: tail call i8* @objc_retainAutoreleasedReturnValue(i8* %p) ; CHECK: call i8* @objc_autorelease(i8* %p) ; CHECK: ret i8* %p define i8* @test13() { %p = call i8* @returner() %1 = call i8* @objc_retainAutoreleasedReturnValue(i8* %p) call void @callee() %2 = call i8* @objc_autorelease(i8* %p) ret i8* %p } ; Convert objc_retainAutoreleasedReturnValue to objc_retain if its ; argument is not a return value. ; CHECK-LABEL: define void @test14( ; CHECK-NEXT: tail call i8* @objc_retain(i8* %p) [[NUW]] ; CHECK-NEXT: ret void define void @test14(i8* %p) { call i8* @objc_retainAutoreleasedReturnValue(i8* %p) ret void } ; Don't convert objc_retainAutoreleasedReturnValue to objc_retain if its ; argument is a return value. ; CHECK-LABEL: define void @test15( ; CHECK-NEXT: %y = call i8* @returner() ; CHECK-NEXT: tail call i8* @objc_retainAutoreleasedReturnValue(i8* %y) [[NUW]] ; CHECK-NEXT: ret void define void @test15() { %y = call i8* @returner() call i8* @objc_retainAutoreleasedReturnValue(i8* %y) ret void } ; Delete autoreleaseRV+retainRV pairs. ; CHECK: define i8* @test19(i8* %p) { ; CHECK-NEXT: ret i8* %p define i8* @test19(i8* %p) { call i8* @objc_autoreleaseReturnValue(i8* %p) call i8* @objc_retainAutoreleasedReturnValue(i8* %p) ret i8* %p } ; Like test19 but with plain autorelease. ; CHECK: define i8* @test20(i8* %p) { ; CHECK-NEXT: call i8* @objc_autorelease(i8* %p) ; CHECK-NEXT: call i8* @objc_retain(i8* %p) ; CHECK-NEXT: ret i8* %p define i8* @test20(i8* %p) { call i8* @objc_autorelease(i8* %p) call i8* @objc_retainAutoreleasedReturnValue(i8* %p) ret i8* %p } ; Like test19 but with plain retain. ; CHECK: define i8* @test21(i8* %p) { ; CHECK-NEXT: call i8* @objc_autoreleaseReturnValue(i8* %p) ; CHECK-NEXT: call i8* @objc_retain(i8* %p) ; CHECK-NEXT: ret i8* %p define i8* @test21(i8* %p) { call i8* @objc_autoreleaseReturnValue(i8* %p) call i8* @objc_retain(i8* %p) ret i8* %p } ; Like test19 but with plain retain and autorelease. ; CHECK: define i8* @test22(i8* %p) { ; CHECK-NEXT: call i8* @objc_autorelease(i8* %p) ; CHECK-NEXT: call i8* @objc_retain(i8* %p) ; CHECK-NEXT: ret i8* %p define i8* @test22(i8* %p) { call i8* @objc_autorelease(i8* %p) call i8* @objc_retain(i8* %p) ret i8* %p } ; Convert autoreleaseRV to autorelease. ; CHECK-LABEL: define void @test23( ; CHECK: call i8* @objc_autorelease(i8* %p) [[NUW]] define void @test23(i8* %p) { store i8 0, i8* %p call i8* @objc_autoreleaseReturnValue(i8* %p) ret void } ; Don't convert autoreleaseRV to autorelease if the result is returned, ; even through a bitcast. ; CHECK-LABEL: define {}* @test24( ; CHECK: tail call i8* @objc_autoreleaseReturnValue(i8* %p) define {}* @test24(i8* %p) { %t = call i8* @objc_autoreleaseReturnValue(i8* %p) %s = bitcast i8* %p to {}* ret {}* %s } ; CHECK: attributes [[NUW]] = { nounwind }
35
0.580193
1
0.580193
testing-qa
OPS
0.721131
testing-qa,compilers-parsers
0.353667
0
0.646333
absences/Unity_HybridCLR_YooAsset_Luban-protobuf3-
10,863
HybridCLR_UNITY/Packages/com.focus-creative-games.hybridclr_unity/Editor/BuildProcessors/AddLil2cppSourceCodeToXcodeproj2020Or2021.cs
using System; using HybridCLR.Editor.Installer; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using UnityEditor; using System.Reflection; using HybridCLR.Editor.Settings; #if (UNITY_2020 || UNITY_2021) && UNITY_IOS using UnityEditor.Build; using UnityEditor.Callbacks; using UnityEditor.iOS.Xcode; using UnityEngine; namespace HybridCLR.Editor.BuildProcessors { public static class AddLil2cppSourceCodeToXcodeproj2020Or2021 { //[MenuItem("Test/GenProj")] //public static void Modify() //{ // OnPostProcessBuild(BuildTarget.iOS, $"{SettingsUtil.ProjectDir}/Build-iOS"); //} //[MenuItem("Test/CreateLumps")] //public static void CreateLumpsCmd() //{ // CreateLumps($"{SettingsUtil.LocalIl2CppDir}/libil2cpp", $"{SettingsUtil.HybridCLRDataDir}/lumps"); //} [PostProcessBuild] public static void OnPostProcessBuild(BuildTarget target, string pathToBuiltProject) { if (target != BuildTarget.iOS || !HybridCLRSettings.Instance.enable) return; /* * 1. 生成lump,并且添加到工程 3. 将libil2cpp目录复制到 Library/. 删除旧的. search paths里修改 libil2cpp/include为libil2cpp 3. Libraries/bdwgc/include -> Libraries/external/bdwgc/include 4. 将external目录复制到 Library/external。删除旧目录 5. 将Library/external/baselib/Platforms/OSX改名为 IOS 全大写 6. 将 external/zlib下c 文件添加到工程 7. 移除libil2cpp.a 8. Include path add libil2cpp/os/ClassLibraryPAL/brotli/include 9. add external/xxHash */ string pbxprojFile = $"{pathToBuiltProject}/Unity-iPhone.xcodeproj/project.pbxproj"; string srcLibil2cppDir = $"{SettingsUtil.LocalIl2CppDir}/libil2cpp"; string dstLibil2cppDir = $"{pathToBuiltProject}/Libraries/libil2cpp"; string lumpDir = $"{pathToBuiltProject}/Libraries/lumps"; string srcExternalDir = $"{SettingsUtil.LocalIl2CppDir}/external"; string dstExternalDir = $"{pathToBuiltProject}/Libraries/external"; //RemoveExternalLibil2cppOption(srcExternalDir, dstExternalDir); CopyLibil2cppToXcodeProj(srcLibil2cppDir, dstLibil2cppDir); CopyExternalToXcodeProj(srcExternalDir, dstExternalDir); var lumpFiles = CreateLumps(dstLibil2cppDir, lumpDir); var extraSources = GetExtraSourceFiles(dstExternalDir, dstLibil2cppDir); var cflags = new List<string>() { "-DIL2CPP_MONO_DEBUGGER_DISABLED", }; ModifyPBXProject(pathToBuiltProject, pbxprojFile, lumpFiles, extraSources, cflags); } private static string GetRelativePathFromProj(string path) { return path.Substring(path.IndexOf("Libraries", StringComparison.Ordinal)).Replace('\\', '/'); } private static void ModifyPBXProject(string pathToBuiltProject, string pbxprojFile, List<LumpFile> lumpFiles, List<string> extraFiles, List<string> cflags) { var proj = new PBXProject(); proj.ReadFromFile(pbxprojFile); string targetGUID = proj.GetUnityFrameworkTargetGuid(); // 移除旧的libil2cpp.a var libil2cppGUID = proj.FindFileGuidByProjectPath("Libraries/libil2cpp.a"); if (!string.IsNullOrEmpty(libil2cppGUID)) { proj.RemoveFileFromBuild(targetGUID, libil2cppGUID); proj.RemoveFile(libil2cppGUID); File.Delete(Path.Combine(pathToBuiltProject, "Libraries", "libil2cpp.a")); } //var lumpGroupGuid = proj.AddFile("Lumps", $"Classes/Lumps", PBXSourceTree.Group); foreach (var lumpFile in lumpFiles) { string lumpFileName = Path.GetFileName(lumpFile.lumpFile); string projPathOfFile = $"Classes/Lumps/{lumpFileName}"; string relativePathOfFile = GetRelativePathFromProj(lumpFile.lumpFile); string lumpGuid = proj.FindFileGuidByProjectPath(projPathOfFile); if (!string.IsNullOrEmpty(lumpGuid)) { proj.RemoveFileFromBuild(targetGUID, lumpGuid); proj.RemoveFile(lumpGuid); } lumpGuid = proj.AddFile(relativePathOfFile, projPathOfFile, PBXSourceTree.Source); proj.AddFileToBuild(targetGUID, lumpGuid); } foreach (var extraFile in extraFiles) { string projPathOfFile = $"Classes/Extrals/{Path.GetFileName(extraFile)}"; string extraFileGuid = proj.FindFileGuidByProjectPath(projPathOfFile); if (!string.IsNullOrEmpty(extraFileGuid)) { proj.RemoveFileFromBuild(targetGUID, extraFileGuid); proj.RemoveFile(extraFileGuid); //Debug.LogWarning($"remove exist extra file:{projPathOfFile} guid:{extraFileGuid}"); } var lumpGuid = proj.AddFile(GetRelativePathFromProj(extraFile), projPathOfFile, PBXSourceTree.Source); proj.AddFileToBuild(targetGUID, lumpGuid); } foreach(var configName in proj.BuildConfigNames()) { //Debug.Log($"build config:{bcn}"); string configGuid = proj.BuildConfigByName(targetGUID, configName); string headerSearchPaths = "HEADER_SEARCH_PATHS"; string hspProp = proj.GetBuildPropertyForConfig(configGuid, headerSearchPaths); //Debug.Log($"config guid:{configGuid} prop:{hspProp}"); string newPro = hspProp.Replace("libil2cpp/include", "libil2cpp") .Replace("Libraries/bdwgc", "Libraries/external/bdwgc"); if (!newPro.Contains("Libraries/libil2cpp/os/ClassLibraryPAL/brotli/include")) { newPro += " $(SRCROOT)/Libraries/libil2cpp/os/ClassLibraryPAL/brotli/include"; } if (!newPro.Contains("Libraries/external/xxHash")) { newPro += " $(SRCROOT)/Libraries/external/xxHash"; } //Debug.Log($"config:{bcn} new prop:{newPro}"); proj.SetBuildPropertyForConfig(configGuid, headerSearchPaths, newPro); string cflagKey = "OTHER_CFLAGS"; string cfProp = proj.GetBuildPropertyForConfig(configGuid, cflagKey); foreach (var flag in cflags) { if (!cfProp.Contains(flag)) { cfProp += " " + flag; } } if (configName.Contains("Debug") && !cfProp.Contains("-DIL2CPP_DEBUG=")) { cfProp += " -DIL2CPP_DEBUG=1 -DDEBUG=1"; } proj.SetBuildPropertyForConfig(configGuid, cflagKey, cfProp); } proj.WriteToFile(pbxprojFile); } private static void CopyLibil2cppToXcodeProj(string srcLibil2cppDir, string dstLibil2cppDir) { BashUtil.RemoveDir(dstLibil2cppDir); BashUtil.CopyDir(srcLibil2cppDir, dstLibil2cppDir, true); } private static void CopyExternalToXcodeProj(string srcExternalDir, string dstExternalDir) { BashUtil.RemoveDir(dstExternalDir); BashUtil.CopyDir(srcExternalDir, dstExternalDir, true); string baselibPlatfromsDir = $"{dstExternalDir}/baselib/Platforms"; BashUtil.RemoveDir($"{baselibPlatfromsDir}/IOS"); BashUtil.CopyDir($"{baselibPlatfromsDir}/OSX", $"{baselibPlatfromsDir}/IOS", true); } class LumpFile { public List<string> cppFiles = new List<string>(); public readonly string lumpFile; public readonly string il2cppConfigFile; public LumpFile(string lumpFile, string il2cppConfigFile) { this.lumpFile = lumpFile; this.il2cppConfigFile = il2cppConfigFile; this.cppFiles.Add(il2cppConfigFile); } public void SaveFile() { var lumpFileContent = new List<string>(); foreach (var file in cppFiles) { lumpFileContent.Add($"#include \"{GetRelativePathFromProj(file)}\""); } File.WriteAllLines(lumpFile, lumpFileContent, Encoding.UTF8); Debug.Log($"create lump file:{lumpFile}"); } } private static List<LumpFile> CreateLumps(string libil2cppDir, string outputDir) { BashUtil.RecreateDir(outputDir); string il2cppConfigFile = $"{libil2cppDir}/il2cpp-config.h"; var lumpFiles = new List<LumpFile>(); int lumpFileIndex = 0; foreach (var cppDir in Directory.GetDirectories(libil2cppDir, "*", SearchOption.AllDirectories).Concat(new string[] {libil2cppDir})) { var lumpFile = new LumpFile($"{outputDir}/lump_{Path.GetFileName(cppDir)}_{lumpFileIndex}.cpp", il2cppConfigFile); foreach (var file in Directory.GetFiles(cppDir, "*.cpp", SearchOption.TopDirectoryOnly)) { lumpFile.cppFiles.Add(file); } lumpFile.SaveFile(); lumpFiles.Add(lumpFile); ++lumpFileIndex; } var mmFiles = Directory.GetFiles(libil2cppDir, "*.mm", SearchOption.AllDirectories); if (mmFiles.Length > 0) { var lumpFile = new LumpFile($"{outputDir}/lump_mm.mm", il2cppConfigFile); foreach (var file in mmFiles) { lumpFile.cppFiles.Add(file); } lumpFile.SaveFile(); lumpFiles.Add(lumpFile); } return lumpFiles; } private static List<string> GetExtraSourceFiles(string externalDir, string libil2cppDir) { var files = new List<string>(); foreach (string extraDir in new string[] { $"{externalDir}/zlib", $"{externalDir}/xxHash", $"{libil2cppDir}/os/ClassLibraryPAL/brotli", }) { if (!Directory.Exists(extraDir)) { continue; } files.AddRange(Directory.GetFiles(extraDir, "*.c", SearchOption.AllDirectories)); } return files; } } } #endif
35
0.840377
1
0.840377
desktop-app
APP_WEB
0.306621
desktop-app
0.677597
1
0.677597
great-expectations/great_expectations
2,967
docs/docusaurus/docs/core/connect_to_data/sql_data/_create_a_batch_definition/create_a_batch_definition.py
""" To run this test locally, run: 1. Activate docker. 2. From the repo root dir, activate the postgresql database docker container: pytest --postgresql --docs-tests -k "create_a_batch_definition_postgres" tests/integration/test_script_runner.py """ # The following import and setup method sets up the data and environment used to test this example. # It can be disregarded by anyone using referencing this script as an example of a # GX workflow. from docs.docusaurus.docs.components._testing.utility_scripts.postgres_preconfigured_data_asset import ( setup, ) setup() # <snippet name="docs/docusaurus/docs/core/connect_to_data/sql_data/_create_a_batch_definition/_create_a_batch_definition.md full example"> import great_expectations as gx context = gx.get_context() # <snippet name="docs/docusaurus/docs/core/connect_to_data/sql_data/_create_a_data_asset/create_a_data_asset.py retrieve a Data Asset"> # Retrieve a Data Source datasource_name = "my_datasource" data_source = context.data_sources.get(datasource_name) # Get the Data Asset from the Data Source asset_name = "MY_TABLE_ASSET" data_asset = data_source.get_asset(asset_name) # </snippet> # Example of a full table Batch Definition # highlight-start # <snippet name="docs/docusaurus/docs/core/connect_to_data/sql_data/_create_a_batch_definition/_create_a_batch_definition.md full table batch definition"> full_table_batch_definition = data_asset.add_batch_definition_whole_table( name="FULL_TABLE" ) # </snippet> # highlight-end # Verify that the Batch Definition is valid # <snippet name="docs/docusaurus/docs/core/connect_to_data/sql_data/_create_a_batch_definition/_create_a_batch_definition.md verify full table"> full_table_batch = full_table_batch_definition.get_batch() full_table_batch.head() # </snippet> # Examples of partitioned Batch Definitions # highlight-start # <snippet name="docs/docusaurus/docs/core/connect_to_data/sql_data/_create_a_batch_definition/_create_a_batch_definition.md daily batch definition"> date_column = "pickup_datetime" daily_batch_definition = data_asset.add_batch_definition_daily( name="DAILY", column=date_column ) monthly_batch_definition = data_asset.add_batch_definition_monthly( name="MONTHLY", column=date_column ) yearly_batch_definition = data_asset.add_batch_definition_yearly( name="YEARLY", column=date_column ) # </snippet> # highlight-end # Verify that the partitioned Batch Definitions are valid # <snippet name="docs/docusaurus/docs/core/connect_to_data/sql_data/_create_a_batch_definition/_create_a_batch_definition.md verify daily"> daily_batch = daily_batch_definition.get_batch( batch_parameters={"year": 2020, "month": 1, "day": 14} ) daily_batch.head() monthly_batch = monthly_batch_definition.get_batch( batch_parameters={"year": 2020, "month": 1} ) monthly_batch.head() yearly_batch = yearly_batch_definition.get_batch(batch_parameters={"year": 2020}) yearly_batch.head() # </snippet> # </snippet>
35
0.7286
1
0.7286
data-engineering
AI_DATA
0.773971
data-engineering
0.113445
0
0.886555
epicweb-dev/data-modeling
2,622
exercises/09.optimize/02.problem.multi-column-index/epicshop/pre-set-playground.js
import os from 'node:os' import path from 'node:path' import * as esbuild from 'esbuild' import fsExtra from 'fs-extra' const { EPICSHOP_PLAYGROUND_TIMESTAMP, EPICSHOP_PLAYGROUND_SRC_DIR, EPICSHOP_PLAYGROUND_DEST_DIR, } = process.env const tempDir = path.join( os.tmpdir(), 'epicshop', 'playground-storage', EPICSHOP_PLAYGROUND_TIMESTAMP, ) const destDirSchema = path.join( EPICSHOP_PLAYGROUND_DEST_DIR, 'prisma', 'schema.prisma', ) const srcDirSchema = path.join( EPICSHOP_PLAYGROUND_SRC_DIR, 'prisma', 'schema.prisma', ) let schemaIsSame = false if ((await isFile(destDirSchema)) && (await isFile(srcDirSchema))) { schemaIsSame = await isSameFile(destDirSchema, srcDirSchema) if (schemaIsSame) { await fsExtra.ensureDir(tempDir) await fsExtra.copy( path.join(EPICSHOP_PLAYGROUND_DEST_DIR, 'node_modules/.prisma'), path.join(tempDir, 'node_modules/.prisma'), ) } } let seedIsSame = false const destSeed = path.join(EPICSHOP_PLAYGROUND_DEST_DIR, 'prisma', 'seed.ts') const srcSeed = path.join(EPICSHOP_PLAYGROUND_SRC_DIR, 'prisma', 'seed.ts') if ((await isFile(destSeed)) && (await isFile(srcSeed))) { seedIsSame = await isSameFile(destSeed, srcSeed) } if (seedIsSame && schemaIsSame) { // save the database in a temp directory by the timestamp so it can be // restored in the post script. await fsExtra.ensureDir(tempDir) await fsExtra.copy( path.join(EPICSHOP_PLAYGROUND_DEST_DIR, 'prisma', 'data.db'), path.join(tempDir, 'data.db'), ) } async function isSameFile(file1, file2) { const f1IsFile = await isFile(file1) const f2IsFile = await isFile(file2) if (!f1IsFile && !f2IsFile) return true if (f1IsFile !== f2IsFile) return false if (/.(ts|js|tsx|jsx)$/.test(file1)) { try { // doing this comparison of the bundled/minified code accounts for code // comments and whitespace changes that should not affect the outcome of // the code. const bundle1 = await getBundle(file1) const bundle2 = await getBundle(file2) return bundle1 === bundle2 } catch { return false } } else { const [content1, content2] = await Promise.all([ fsExtra.readFile(file1), fsExtra.readFile(file2), ]) return content1.equals(content2) } } async function isFile(p) { try { const stat = await fsExtra.stat(p) return stat.isFile() } catch (error) { return false } } async function getBundle(filepath) { const { outputFiles: [{ text }], } = await esbuild.build({ entryPoints: [filepath], bundle: true, platform: 'node', format: 'esm', write: false, packages: 'external', external: ['*.png'], minify: true, }) return text }
35
0.880408
1
0.880408
build-systems
OPS
0.248057
build-systems
0.912467
1
0.912467
CYRUS-STUDIO/LLVM
2,124
llvm/test/MC/AArch64/SME2/usdot-diagnostics.s
// RUN: not llvm-mc -triple=aarch64 -show-encoding -mattr=+sme2 2>&1 < %s | FileCheck %s // --------------------------------------------------------------------------// // Invalid select register usdot za.s[w7, 0, vgx2], {z0.b-z1.b}, z0.b[0] // CHECK: [[@LINE-1]]:{{[0-9]+}}: error: operand must be a register in range [w8, w11] // CHECK-NEXT: usdot za.s[w7, 0, vgx2], {z0.b-z1.b}, z0.b[0] // CHECK-NOT: [[@LINE-1]]:{{[0-9]+}}: usdot za.s[w12, 0, vgx4], {z0.b-z3.b}, z0.b[0] // CHECK: [[@LINE-1]]:{{[0-9]+}}: error: operand must be a register in range [w8, w11] // CHECK-NEXT: usdot za.s[w12, 0, vgx4], {z0.b-z3.b}, z0.b[0] // CHECK-NOT: [[@LINE-1]]:{{[0-9]+}}: // --------------------------------------------------------------------------// // Invalid select offset usdot za.s[w8, 16], {z0.b-z1.b}, z0.b[0] // CHECK: [[@LINE-1]]:{{[0-9]+}}: error: immediate must be an integer in range [0, 7]. // CHECK-NEXT: usdot za.s[w8, 16], {z0.b-z1.b}, z0.b[0] // CHECK-NOT: [[@LINE-1]]:{{[0-9]+}}: // --------------------------------------------------------------------------// // Out of range element index usdot za.s[w8, 0], {z0.b-z1.b}, z0.b[4] // CHECK: [[@LINE-1]]:{{[0-9]+}}: error: vector lane must be an integer in range [0, 3]. // CHECK-NEXT: usdot za.s[w8, 0], {z0.b-z1.b}, z0.b[4] // CHECK-NOT: [[@LINE-1]]:{{[0-9]+}}: usdot za.s[w8, 0], {z0.b-z3.b}, z0.b[4] // CHECK: [[@LINE-1]]:{{[0-9]+}}: error: vector lane must be an integer in range [0, 3]. // CHECK-NEXT: usdot za.s[w8, 0], {z0.b-z3.b}, z0.b[4] // CHECK-NOT: [[@LINE-1]]:{{[0-9]+}}: // --------------------------------------------------------------------------// // ZPR range constraint usdot za.s[w8, 5], {z0.b-z1.b}, z16.b[0] // CHECK: [[@LINE-1]]:{{[0-9]+}}: error: Invalid restricted vector register, expected z0.b..z15.b // CHECK-NEXT: usdot za.s[w8, 5], {z0.b-z1.b}, z16.b[0] // CHECK-NOT: [[@LINE-1]]:{{[0-9]+}}: usdot za.s[w8, 5], {z0.b-z3.b}, z16.b[0] // CHECK: [[@LINE-1]]:{{[0-9]+}}: error: Invalid restricted vector register, expected z0.b..z15.b // CHECK-NEXT: usdot za.s[w8, 5], {z0.b-z3.b}, z16.b[0] // CHECK-NOT: [[@LINE-1]]:{{[0-9]+}}:
35
0.562632
1
0.562632
compilers-parsers
SYSTEMS
0.997526
compilers-parsers,testing-qa
0.244053
0
0.755947
ETDA/ThaiD-PHP-RP
4,810
system/HTTP/Header.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <[email protected]> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\HTTP; use Stringable; /** * Class Header * * Represents a single HTTP header. * * @see \CodeIgniter\HTTP\HeaderTest */ class Header implements Stringable { /** * The name of the header. * * @var string */ protected $name; /** * The value of the header. May have more than one * value. If so, will be an array of strings. * E.g., * [ * 'foo', * [ * 'bar' => 'fizz', * ], * 'baz' => 'buzz', * ] * * @var array<int|string, array<string, string>|string>|string */ protected $value; /** * Header constructor. name is mandatory, if a value is provided, it will be set. * * @param array<int|string, array<string, string>|string>|string|null $value */ public function __construct(string $name, $value = null) { $this->name = $name; $this->setValue($value); } /** * Returns the name of the header, in the same case it was set. */ public function getName(): string { return $this->name; } /** * Gets the raw value of the header. This may return either a string * or an array, depending on whether the header has multiple values or not. * * @return array<int|string, array<string, string>|string>|string */ public function getValue() { return $this->value; } /** * Sets the name of the header, overwriting any previous value. * * @return $this */ public function setName(string $name) { $this->name = $name; return $this; } /** * Sets the value of the header, overwriting any previous value(s). * * @param array<int|string, array<string, string>|string>|string|null $value * * @return $this */ public function setValue($value = null) { $this->value = is_array($value) ? $value : (string) $value; return $this; } /** * Appends a value to the list of values for this header. If the * header is a single value string, it will be converted to an array. * * @param array<string, string>|string|null $value * * @return $this */ public function appendValue($value = null) { if ($value === null) { return $this; } if (! is_array($this->value)) { $this->value = [$this->value]; } if (! in_array($value, $this->value, true)) { $this->value[] = is_array($value) ? $value : (string) $value; } return $this; } /** * Prepends a value to the list of values for this header. If the * header is a single value string, it will be converted to an array. * * @param array<string, string>|string|null $value * * @return $this */ public function prependValue($value = null) { if ($value === null) { return $this; } if (! is_array($this->value)) { $this->value = [$this->value]; } array_unshift($this->value, $value); return $this; } /** * Retrieves a comma-separated string of the values for a single header. * * NOTE: Not all header values may be appropriately represented using * comma concatenation. For such headers, use getHeader() instead * and supply your own delimiter when concatenating. * * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2 */ public function getValueLine(): string { if (is_string($this->value)) { return $this->value; } if (! is_array($this->value)) { return ''; } $options = []; foreach ($this->value as $key => $value) { if (is_string($key) && ! is_array($value)) { $options[] = $key . '=' . $value; } elseif (is_array($value)) { $key = key($value); $options[] = $key . '=' . $value[$key]; } elseif (is_numeric($key)) { $options[] = $value; } } return implode(', ', $options); } /** * Returns a representation of the entire header string, including * the header name and all values converted to the proper format. */ public function __toString(): string { return $this->name . ': ' . $this->getValueLine(); } }
35
0.847817
1
0.847817
web-backend
APP_WEB
0.856792
web-backend
0.678994
1
0.678994
arfc/moltres
9,713
doc/content/bib/theses.bib
@mastersthesis{park_advancement_2020, address = {Urbana, IL}, title = {Advancement and {Verification} of {Moltres} for {Molten} {Salt} {Reactor} {Safety} {Analysis}}, copyright = {Copyright 2020 Sun Myung Park}, url = {https://www.ideals.illinois.edu/handle/2142/108542}, language = {English}, school = {University of Illinois at Urbana-Champaign}, author = {Park, Sun Myung}, month = aug, year = {2020}, file = {Park - 2020 - Advancement and Verification of Moltres for Molten.pdf:C\:\\Users\\Sun Myung\\Zotero\\storage\\JYYYTBJ7\\Park - 2020 - Advancement and Verification of Moltres for Molten.pdf:application/pdf}, } @mastersthesis{fairhurst-agosta_multi-physics_2020, address = {Urbana, IL}, title = {Multi-{Physics} and {Technical} {Analysis} of {High}-{Temperature} {Gas}-{Cooled} {Reactors} for {Hydrogen} {Production}}, copyright = {Copyright 2020 Roberto Fairhurst Agosta}, abstract = {The future energy needs require the development of clean energy sources to ease the increasing environmental concerns. High-Temperature Gas-cooled Reactors have several desirable features that make them ideal candidates for the near-future large-scale deployment. Some of these features are a high temperature and high thermal cycle efficiency, which enable a wide range of process heat applications, such as hydrogen production. Implementing hydrogen economies can decarbonize the transport and power sectors, offering an alternative to ease climate change. This work uses Moltres as the primary simulation tool. Although Moltres original development targeted Molten Salt Reactors, this work studies Moltres applicability to multi-physics simulations of prismatic High-Temperature Gas-cooled Reactors. Multi-physics simulations are necessary for assessing reactor safety characteristics. Ensuring Moltres’ multi-physics modeling capabilities requires assessing the independent modeling capabilities of the different physical phenomena. Therefore, this thesis breaks down the analysis into three parts: stand-alone neutronics, stand-alone thermal-fluids, and coupled neutronics/thermal-fluids. Regarding stand-alone neutronics, several analyses compare the results calculated by Moltres and Serpent on an MHTGR-350 model. The first analysis studies the energy group structure effects on the simulation of a fuel column. The results of the study suggest using a 15-energy group structure for attaining a desirable accuracy. The following analysis focuses on the full-core problem and compares different aspects of the simulations, concluding that Moltres obtains reasonably accurate results. The final study on stand-alone neutronics describes Moltres results of Phase I Exercise 1 of the OECD/NEA MHTGR-350 Benchmark. The benchmark exercise proved to be a modeling challenge, requiring the implementation of several approximations. For the most part, this thesis demonstrates Moltres’ capability to simulate stand-alone neutronics of prismatic High-Temperature Gas-cooled Reactors. Regarding stand-alone thermal-fluids, several studies compare Moltres results to previously published results. These studies focus on local models such as the unit cell and the fuel column problems, for which Moltres temperature results differ by less than 2\% from the published results. Further studies analyze the possibility of extending the thermal-fluids model implemented in the previous problems to a full-core simulation, finding a high memory requirement imposed by the simulations. The full-core simulations focus on Phase I Exercise 2 of the benchmark, for which the implementation of a two-level approach in Moltres was necessary. The study’s temperatures were within an 11.3\% difference to the published results, concluding that further analysis is required. Regarding coupled neutronics/thermal-fluids, the analysis describes Phase I Exercise 3 of the benchmark. The exercise uses a simplified model that helps visualize some of the essential aspects of multi-physics simulations in Moltres. This exercise finds some areas of improvement in Moltres’ model and sets a basis for future work. This thesis aligns with the University of Illinois’ goals to reduce carbon emissions from its campus’s electricity generation and transportation sectors. This work focuses on two main analysis by introducing a nuclear reactor coupled to a hydrogen plant as a solution. The first analysis evaluates the conversion of the university fleet and the mass transit transport system in Urbana-Champaign to Fuel Cell Electric Vehicles. The second analysis investigates the duck curve phenomenon in the university’s grid and introduces a mitigation strategy that may reduce the reliance on dispatchable sources. These studies emphasize how nuclear energy and hydrogen production can potentially mitigate climate change.}, language = {English (US)}, school = {University of Illinois at Urbana-Champaign}, author = {Fairhurst-Agosta, Roberto}, month = dec, year = {2020}, file = {Fairhurst-Agosta - Multi-Physics and Technical Analysis of High-Tempe.pdf:C\:\\Users\\Sun Myung\\Zotero\\storage\\PTK9576U\\Fairhurst-Agosta - Multi-Physics and Technical Analysis of High-Tempe.pdf:application/pdf}, } @mastersthesis{lee_neutronics_2020, address = {Urbana, IL}, title = {Neutronics and {Thermal}-{Hydraulics} {Analysis} of {TransAtomic} {Power} {Molten} {Salt} {Reactor} ({TAP} {MSR}) {Core} {Under} {Load} {Following} {Operations}}, shorttitle = {Neutronics and thermal-hydraulics analysis of transatomic power molten salt reactor ({TAP} {MSR}) core under load following operations}, url = {https://www.ideals.illinois.edu/bitstream/handle/2142/109415/LEE-THESIS-2020.pdf?sequence=1&isAllowed=y}, abstract = {This work analyzed the neutronics and thermal-hydraulics behavior of the Transatomic Power Molten Salt Reactor (TAP MSR) core under load-following operations using a Monte Carlo code, Serpent 2, as well as a UIUC-developed MOOSE-based code, Moltres. A simulation method was developed to determine the operational bounds of the TAP MSR core and its transient behavior under rapid power ramps using both fresh fuel salt and fuel salt with equilibrium 135Xe. The thermal-hydraulics investigation studied the potential of exceeding material temperature constraints under simple advection flow versus a flow simulated with Incompressible Navier-Stokes physics. Finally, the effects of gas entrainment on the reactor core behavior were investigated. This study concludes that the TAP MSR core is able to perform rapid load following operations without exceeding its thermal safety constraints. The findings in this work were derived from research performed under the DOE ARPA-E MEITNER project, DE-AR0000983.}, school = {University of Illinois at Urbana-Champaign}, author = {Lee, Alvin J. H.}, month = dec, year = {2020}, file = {Lee - 2020 - Neutronics and Thermal-Hydraulics Analysis of Tran.pdf:C\:\\Users\\Sun Myung\\Zotero\\storage\\73JPRPQ3\\Lee - 2020 - Neutronics and Thermal-Hydraulics Analysis of Tran.pdf:application/pdf}, } @mastersthesis{pater_multiphysics_2019, title = {Multiphysics simulations of {Molten} {Salt} {Reactors} using the {Moltres} code}, copyright = {http://creativecommons.org/licenses/by-nc-sa/3.0/es/}, url = {https://upcommons.upc.edu/handle/2117/173747}, language = {cat}, urldate = {2022-05-04}, school = {Universitat Politècnica de Catalunya}, author = {Pater, Mateusz}, month = nov, year = {2019}, note = {Accepted: 2019-12-11T11:03:14Z Publisher: Universitat Politècnica de Catalunya}, keywords = {Àrees temàtiques de la UPC::Física, Nuclear engineering--Safety measures, Reactors nuclears -- Mesures de seguretat -- Simulació per ordinador}, file = {Full Text PDF:C\:\\Users\\Sun Myung\\Zotero\\storage\\NWWJN9XA\\Pater - 2019 - Multiphysics simulations of Molten Salt Reactors u.pdf:application/pdf;Snapshot:C\:\\Users\\Sun Myung\\Zotero\\storage\\QZJV3C6Z\\173747.html:text/html}, } @phdthesis{chee_fluoride-salt-cooled_2022, address = {Urbana, IL}, type = {Dissertation}, title = {Fluoride-{Salt}-{Cooled} {High} {Temperature} {Reactor} {Design} {Optimization} with {Evolutionary} {Algorithms}}, copyright = {Copyright 2021 Gwendolyn Jin Yi Chee}, url = {https://github.com/arfc/2022-chee-dissertation}, abstract = {Additive manufacturing of reactor core components removes the geometric constraints required by conventional manufacturing, such as slabs as fuel planks and cylinders as fuel rods. Due to the expansion of the potential design space facilitated through additive manufacturing, reactor designers need to find methods, such as generative design, to explore the design space efficiently. In this defense, I will show that I successfully applied evolutionary algorithms to conduct generative reactor design optimization for a fluoride-salt-cooled high-temperature reactor (FHR). I achieved this through three distinct research efforts: 1) furthering our understanding of the FHR design’s complexities through neutronics and temperature modeling, 2) creating an open-source tool that enables generative design reactor optimization with evolutionary algorithms, and 3) applying the tool to the FHR to optimize for non-conventional geometries and fuel distributions}, school = {University of Illinois at Urbana-Champaign}, author = {Chee, Gwendolyn Jin Yi}, month = aug, year = {2022}, file = {2022-chee-dissertation-pres.pdf:C\:\\Users\\Sun Myung\\Zotero\\storage\\Y93FYTHR\\2022-chee-dissertation-pres.pdf:application/pdf;Chee - 2021 - Fluoride-Salt-Cooled High Temperature Reactor Desi.pdf:C\:\\Users\\Sun Myung\\Zotero\\storage\\EXF7M46A\\Chee - 2021 - Fluoride-Salt-Cooled High Temperature Reactor Desi.pdf:application/pdf}, }
35
0.831265
1
0.831265
scientific-computing
AI_DATA
0.999042
scientific-computing
0
0
1
matter-labs/era-contracts
1,447
l1-contracts/test/foundry/l1/upgrades/DefaultUpgrade.t.sol
// SPDX-License-Identifier: MIT pragma solidity 0.8.28; import {Test} from "forge-std/Test.sol"; import {DefaultUpgrade} from "contracts/upgrades/DefaultUpgrade.sol"; import {PubdataPricingMode, FeeParams} from "contracts/state-transition/chain-deps/ZKChainStorage.sol"; import {Diamond} from "contracts/state-transition/libraries/Diamond.sol"; import {BaseUpgrade} from "./_SharedBaseUpgrade.t.sol"; import {BaseUpgradeUtils} from "./_SharedBaseUpgradeUtils.t.sol"; contract DummyDefaultUpgrade is DefaultUpgrade, BaseUpgradeUtils {} contract DefaultUpgradeTest is BaseUpgrade { DummyDefaultUpgrade baseZkSyncUpgrade; function setUp() public { baseZkSyncUpgrade = new DummyDefaultUpgrade(); _prepareProposedUpgrade(); baseZkSyncUpgrade.setPriorityTxMaxGasLimit(1 ether); baseZkSyncUpgrade.setPriorityTxMaxPubdata(1000000); } function test_SuccessUpgrade() public { bytes32 result = baseZkSyncUpgrade.upgrade(proposedUpgrade); assertEq(result, Diamond.DIAMOND_INIT_SUCCESS_RETURN_VALUE); assertEq(baseZkSyncUpgrade.getProtocolVersion(), proposedUpgrade.newProtocolVersion); assertEq(baseZkSyncUpgrade.getVerifier(), proposedUpgrade.verifier); assertEq(baseZkSyncUpgrade.getL2DefaultAccountBytecodeHash(), proposedUpgrade.defaultAccountHash); assertEq(baseZkSyncUpgrade.getL2BootloaderBytecodeHash(), proposedUpgrade.bootloaderHash); } }
35
0.502123
1
0.502123
distributed-systems
SYSTEMS
0.465448
distributed-systems
0.575967
1
0.575967
RyuZhihao123/CHITreeProject
1,942
TreeDatasetGenerator/platforms/ui_dialog.h
/******************************************************************************** ** Form generated from reading UI file 'dialog.ui' ** ** Created by: Qt User Interface Compiler version 5.8.0 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_DIALOG_H #define UI_DIALOG_H #include <QtCore/QVariant> #include <QtWidgets/QAction> #include <QtWidgets/QApplication> #include <QtWidgets/QButtonGroup> #include <QtWidgets/QDialog> #include <QtWidgets/QDialogButtonBox> #include <QtWidgets/QHeaderView> #include <QtWidgets/QTextEdit> QT_BEGIN_NAMESPACE class Ui_Dialog { public: QDialogButtonBox *buttonBox; QTextEdit *textEdit; void setupUi(QDialog *Dialog) { if (Dialog->objectName().isEmpty()) Dialog->setObjectName(QStringLiteral("Dialog")); Dialog->resize(400, 141); buttonBox = new QDialogButtonBox(Dialog); buttonBox->setObjectName(QStringLiteral("buttonBox")); buttonBox->setGeometry(QRect(50, 100, 341, 32)); buttonBox->setOrientation(Qt::Horizontal); buttonBox->setStandardButtons(QDialogButtonBox::Cancel|QDialogButtonBox::Ok); textEdit = new QTextEdit(Dialog); textEdit->setObjectName(QStringLiteral("textEdit")); textEdit->setGeometry(QRect(10, 10, 371, 64)); retranslateUi(Dialog); QObject::connect(buttonBox, SIGNAL(accepted()), Dialog, SLOT(accept())); QObject::connect(buttonBox, SIGNAL(rejected()), Dialog, SLOT(reject())); QMetaObject::connectSlotsByName(Dialog); } // setupUi void retranslateUi(QDialog *Dialog) { Dialog->setWindowTitle(QApplication::translate("Dialog", "Dialog", Q_NULLPTR)); } // retranslateUi }; namespace Ui { class Dialog: public Ui_Dialog {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_DIALOG_H
35
0.774929
1
0.774929
desktop-app
APP_WEB
0.993334
desktop-app
0.482466
0
0.517534
chchenhui/mlrbench
4,017
agent_results/end2end_codex/iclr2025_bi_align/codex/experiment.py
#!/usr/bin/env python3 import os import sys import json import random import numpy as np import matplotlib.pyplot as plt def simulate_user(theta, phi_i, phi_j): """Simulate user feedback y=1 if prefers i over j, else 0.""" diff = theta.dot(phi_i - phi_j) p = 1 / (1 + np.exp(-diff)) return 1 if random.random() < p else 0 class BayesianPreferenceModel: def __init__(self, dim): self.dim = dim self.mu = np.zeros(dim) self.Sigma = np.eye(dim) self.Sigma_inv = np.eye(dim) def predict(self, phi): mu = self.mu.dot(phi) var = phi.dot(self.Sigma).dot(phi) return mu, var def update(self, phi_diff, y): # approximate Bayesian update with Laplace approximation p = 1 / (1 + np.exp(-self.mu.dot(phi_diff))) W = p * (1 - p) self.Sigma_inv = self.Sigma_inv + W * np.outer(phi_diff, phi_diff) self.Sigma = np.linalg.inv(self.Sigma_inv) grad = (y - p) * phi_diff self.mu = self.mu + self.Sigma.dot(grad) def run_experiment(num_items=50, dim=5, K=10, T=100, threshold=2.0): phi = np.random.randn(num_items, dim) theta_true = np.random.randn(dim) results = {'static': [], 'passive': [], 'udca': []} queries = {'static': 0, 'passive': 0, 'udca': 0} models = { 'static': BayesianPreferenceModel(dim), 'passive': BayesianPreferenceModel(dim), 'udca': BayesianPreferenceModel(dim), } tau = threshold for t in range(T): idx = np.random.choice(num_items, K, replace=False) phis = phi[idx] for name, model in models.items(): mus = np.array([model.predict(p)[0] for p in phis]) a_idx = np.argmax(mus) a = phis[a_idx] util = theta_true.dot(a) results[name].append(util) if name == 'static': continue if name == 'passive': i, j = random.sample(range(K), 2) y = simulate_user(theta_true, phis[i], phis[j]) models[name].update(phis[i] - phis[j], y) queries[name] += 1 if name == 'udca': vars_ = np.array([model.predict(p)[1] for p in phis]) if vars_.max() > tau: p_i = np.argmax(vars_) p_j = random.choice([x for x in range(K) if x != p_i]) y = simulate_user(theta_true, phis[p_i], phis[p_j]) models[name].update(phis[p_i] - phis[p_j], y) queries[name] += 1 tau *= 0.99 out_dir = os.path.join(os.getcwd(), 'codex') os.makedirs(out_dir, exist_ok=True) json.dump({'results': results, 'queries': queries}, open(os.path.join(out_dir, 'results.json'), 'w')) plt.figure() T_range = np.arange(T) for name, vals in results.items(): plt.plot(np.cumsum(vals) / (T_range + 1), label=name) plt.xlabel('Iteration') plt.ylabel('Avg true utility') plt.title('Decision Quality over Time') plt.legend() fig1 = os.path.join(out_dir, 'decision_quality.png') plt.savefig(fig1) plt.close() plt.figure() pces = {} for name, model in models.items(): mus = phi.dot(model.mu) pces[name] = float(np.mean((phi.dot(theta_true) - mus)**2)) names = list(pces.keys()) vals = [pces[n] for n in names] plt.bar(names, vals) plt.ylabel('Preference Calibration Error') plt.title('Final PCE') fig2 = os.path.join(out_dir, 'pce.png') plt.savefig(fig2) plt.close() return out_dir if __name__ == '__main__': import logging log_path = os.path.join('codex', 'log.txt') os.makedirs('codex', exist_ok=True) logging.basicConfig(filename=log_path, level=logging.INFO, filemode='w', format='%(asctime)s %(levelname)s %(message)s') logging.info('Starting experiment') out = run_experiment() logging.info(f'Results saved to {out}') print('Experiment completed.')
35
0.586383
1
0.586383
scientific-computing
AI_DATA
0.848152
scientific-computing
0.880692
1
0.880692
PaddlePaddle/PaddleTS
5,484
docs/index.rst
Welcome to PaddleTS ====================== PaddleTS is an easy-to-use Python library for deep time series modeling, focusing on the state-of-the-art deep neural network models based on PaddlePaddle deep learning framework. It aims to provide great flexibility and excellent user experiences for practitioners and professionals. It’s featured with: * A unified data structure named TSDataset for representing time series data with one or multiple target variables and optional different kinds of covariates (e.g. known covariates, observed covariates, static covariates, etc.) * A base model class named PaddleBaseModelImpl , which inherits from the PaddleBaseModel and further encapsulates some routine procedures (e.g. data loading, callbacks setup, loss computation, training loop control, etc.) and allows developers to focus on the implementation of network architectures when developing new models * A set of state-of-the-art deep learning models containing NBEATS, NHiTS, LSTNet, TCN, Transformer, DeepAR(Probabilistic), Informer, etc. for forecasting, TS2Vec for representation * A set of transformation operators for data preprocessing (e.g. missing values/outliers handling, one-hot encoding, normalization, and automatic date/time-related covariates generation, etc.) * A set of analysis operators for quick data exploration (e.g. basic statistics and summary) * Automatic time series modeling module (AutoTS) which supports mainstream Hyper Parameter Optimization algorithms and shows significant improvement on multiple models and datasets * Third-party (e.g. scikit-learn) ML models & data transformations integration Recently updated: * Released a new time series representation model, i.e. Contrastive Learning of Disentangled Seasonal-trend Representations(CoST) * Time series anomaly detection model supported, with three deep models released, including AE(AutoEncoder), VAE(Variational AutoEncoder), and AnomalyTransformer * Third-party `pyod <https://github.com/yzhao062/pyod>`_ ML models integration supported * Support time series model ensemble with two types of ensemble forecaster, StackingEnsembleForecaster and WeightingEnsembleForecaster proposed * RNN time series forecasting model supports categorical features and static covariates * New representation forecaster to support representation models to solve time series forecasting task * Support joint training of multiple time series datasets In the future, more advanced features will be coming, including: * More time series anomaly detection models * More time series representation learning models * More probabilistic forecasting models * Scenario-specific pipelines which aim to provide an end-to-end solution for solving real-world business problems * And more Project GitHub: https://github.com/PaddlePaddle/PaddleTS .. toctree:: :maxdepth: 1 :caption: Get Started Get Started <source/get_started/get_started.rst> Run On GPU <source/get_started/run_on_gpu.rst> Joint Training of Multiple Time Series <source/get_started/multiple_time_series.rst> .. toctree:: :maxdepth: 1 :caption: Installation Installation <source/installation/overview.rst> .. toctree:: :maxdepth: 1 :caption: Dataset Dataset <source/modules/datasets/overview.rst> Supported Datasets <source/modules/datasets/supported_datasets.rst> .. toctree:: :maxdepth: 1 :caption: Transform Transform <source/modules/transform/overview.md> Third-Party And User-Define Transform <source/modules/transform/thirdparty_userdefine.rst> .. toctree:: :maxdepth: 1 :caption: Models Forecasting <source/modules/models/overview.rst> Third-party Model <source/modules/models/thirdparty.rst> Probability Forecasting <source/modules/models/probability_forecasting.rst> Representation <source/modules/models/representation.rst> Anomaly Detection <source/modules/models/anomaly.rst> Classification <source/modules/models/classify.rst> Paddle Inference <source/modules/models/paddle_inference.rst> .. toctree:: :maxdepth: 1 :caption: Metrics Metrics <source/modules/metrics/overview.md> .. toctree:: :maxdepth: 1 :caption: Pipeline Pipeline <source/modules/pipeline/overview.rst> .. toctree:: :maxdepth: 1 :caption: Analysis Analysis <source/modules/analysis/overview.md> .. toctree:: :maxdepth: 1 :caption: Backtest Backtest <source/modules/backtest/overview.md> .. toctree:: :maxdepth: 1 :caption: AutoTS AutoTS <source/modules/autots/overview.rst> .. toctree:: :maxdepth: 1 :caption: Ensemble EnsembleForecaster <source/modules/ensemble/ensemble_forecaster.rst> EnsembleAnomaly <source/modules/ensemble/ensemble_anomaly.rst> .. toctree:: :maxdepth: 1 :caption: XAI XAI <source/modules/xai/overview.rst> .. toctree:: :maxdepth: 1 :caption: API paddlets.analysis <source/api/paddlets.analysis.rst> paddlets.automl <source/api/paddlets.automl.rst> paddlets.datasets <source/api/paddlets.datasets.rst> paddlets.metrics <source/api/paddlets.metrics.rst> paddlets.models <source/api/paddlets.models.rst> paddlets.pipeline <source/api/paddlets.pipeline.rst> paddlets.transform <source/api/paddlets.transform.rst> paddlets.ensemble <source/api/paddlets.ensemble.rst> paddlets.utils <source/api/paddlets.utils.rst> paddlets.xai <source/api/paddlets.xai.rst>
35
0.730785
1
0.730785
ml-ai
AI_DATA
0.528866
ml-ai,deep-learning
0.000335
0
0.999665
magichourhq/magic-hour-python
11,739
magic_hour/resources/v1/face_swap_photo/client.py
import typing from magic_hour.helpers.logger import get_sdk_logger from magic_hour.resources.v1.files.client import AsyncFilesClient, FilesClient from magic_hour.resources.v1.image_projects.client import ( AsyncImageProjectsClient, ImageProjectsClient, ) from magic_hour.types import models, params from make_api_request import ( AsyncBaseClient, RequestOptions, SyncBaseClient, default_request_options, to_encodable, type_utils, ) logger = get_sdk_logger(__name__) class FaceSwapPhotoClient: def __init__(self, *, base_client: SyncBaseClient): self._base_client = base_client def generate( self, *, assets: params.V1FaceSwapPhotoGenerateBodyAssets, name: typing.Union[ typing.Optional[str], type_utils.NotGiven ] = type_utils.NOT_GIVEN, wait_for_completion: bool = True, download_outputs: bool = True, download_directory: typing.Optional[str] = None, request_options: typing.Optional[RequestOptions] = None, ): """ Generate face swap photo (alias for create with additional functionality). Swap faces in a photo using AI. Each face swap costs 5 credits. Args: name: The name of image. This value is mainly used for your own identification of the image. assets: Provide the assets for face swap photo wait_for_completion: Whether to wait for the image project to complete download_outputs: Whether to download the outputs download_directory: The directory to download the outputs to. If not provided, the outputs will be downloaded to the current working directory request_options: Additional options to customize the HTTP request Returns: V1ImageProjectsGetResponseWithDownloads: The response from the Face Swap Photo API with the downloaded paths if `download_outputs` is True. Examples: ```py client.v1.face_swap_photo.generate( assets={ "face_swap_mode": "all-faces", "source_file_path": "api-assets/id/1234.png", "target_file_path": "api-assets/id/1234.png", }, name="Face Swap image", wait_for_completion=True, download_outputs=True, download_directory="./outputs/", ) ``` """ file_client = FilesClient(base_client=self._base_client) # Upload source image file if present if "source_file_path" in assets and assets["source_file_path"]: source_file_path = assets["source_file_path"] assets["source_file_path"] = file_client.upload_file(file=source_file_path) # Upload target image file target_file_path = assets["target_file_path"] assets["target_file_path"] = file_client.upload_file(file=target_file_path) # Upload face mappings if present if "face_mappings" in assets and assets["face_mappings"]: for face_mapping in assets["face_mappings"]: if "new_face" in face_mapping and face_mapping["new_face"]: new_face_file_path = face_mapping["new_face"] face_mapping["new_face"] = file_client.upload_file( file=new_face_file_path ) create_response = self.create( assets=assets, name=name, request_options=request_options ) logger.info(f"Face Swap Photo response: {create_response}") image_projects_client = ImageProjectsClient(base_client=self._base_client) response = image_projects_client.check_result( id=create_response.id, wait_for_completion=wait_for_completion, download_outputs=download_outputs, download_directory=download_directory, ) return response def create( self, *, assets: params.V1FaceSwapPhotoCreateBodyAssets, name: typing.Union[ typing.Optional[str], type_utils.NotGiven ] = type_utils.NOT_GIVEN, request_options: typing.Optional[RequestOptions] = None, ) -> models.V1FaceSwapPhotoCreateResponse: """ Face Swap Photo Create a face swap photo. Each photo costs 5 credits. The height/width of the output image depends on your subscription. Please refer to our [pricing](https://magichour.ai/pricing) page for more details POST /v1/face-swap-photo Args: name: The name of image. This value is mainly used for your own identification of the image. assets: Provide the assets for face swap photo request_options: Additional options to customize the HTTP request Returns: Success Raises: ApiError: A custom exception class that provides additional context for API errors, including the HTTP status code and response body. Examples: ```py client.v1.face_swap_photo.create( assets={ "face_mappings": [ { "new_face": "api-assets/id/1234.png", "original_face": "api-assets/id/0-0.png", } ], "face_swap_mode": "all-faces", "source_file_path": "api-assets/id/1234.png", "target_file_path": "api-assets/id/1234.png", }, name="Face Swap image", ) ``` """ _json = to_encodable( item={"name": name, "assets": assets}, dump_with=params._SerializerV1FaceSwapPhotoCreateBody, ) return self._base_client.request( method="POST", path="/v1/face-swap-photo", auth_names=["bearerAuth"], json=_json, cast_to=models.V1FaceSwapPhotoCreateResponse, request_options=request_options or default_request_options(), ) class AsyncFaceSwapPhotoClient: def __init__(self, *, base_client: AsyncBaseClient): self._base_client = base_client async def generate( self, *, assets: params.V1FaceSwapPhotoGenerateBodyAssets, name: typing.Union[ typing.Optional[str], type_utils.NotGiven ] = type_utils.NOT_GIVEN, wait_for_completion: bool = True, download_outputs: bool = True, download_directory: typing.Optional[str] = None, request_options: typing.Optional[RequestOptions] = None, ): """ Generate face swap photo (alias for create with additional functionality). Swap faces in a photo using AI. Each face swap costs 5 credits. Args: name: The name of image. This value is mainly used for your own identification of the image. assets: Provide the assets for face swap photo wait_for_completion: Whether to wait for the image project to complete download_outputs: Whether to download the outputs download_directory: The directory to download the outputs to. If not provided, the outputs will be downloaded to the current working directory request_options: Additional options to customize the HTTP request Returns: V1ImageProjectsGetResponseWithDownloads: The response from the Face Swap Photo API with the downloaded paths if `download_outputs` is True. Examples: ```py await client.v1.face_swap_photo.generate( assets={ "face_swap_mode": "all-faces", "source_file_path": "api-assets/id/1234.png", "target_file_path": "api-assets/id/1234.png", }, name="Face Swap image", wait_for_completion=True, download_outputs=True, download_directory="./outputs/", ) ``` """ file_client = AsyncFilesClient(base_client=self._base_client) # Upload source image file if present if "source_file_path" in assets and assets["source_file_path"]: source_file_path = assets["source_file_path"] assets["source_file_path"] = await file_client.upload_file( file=source_file_path ) # Upload target image file target_file_path = assets["target_file_path"] assets["target_file_path"] = await file_client.upload_file( file=target_file_path ) # Upload face mappings if present if "face_mappings" in assets and assets["face_mappings"]: for face_mapping in assets["face_mappings"]: if "new_face" in face_mapping and face_mapping["new_face"]: new_face_file_path = face_mapping["new_face"] face_mapping["new_face"] = await file_client.upload_file( file=new_face_file_path ) create_response = await self.create( assets=assets, name=name, request_options=request_options ) logger.info(f"Face Swap Photo response: {create_response}") image_projects_client = AsyncImageProjectsClient(base_client=self._base_client) response = await image_projects_client.check_result( id=create_response.id, wait_for_completion=wait_for_completion, download_outputs=download_outputs, download_directory=download_directory, ) return response async def create( self, *, assets: params.V1FaceSwapPhotoCreateBodyAssets, name: typing.Union[ typing.Optional[str], type_utils.NotGiven ] = type_utils.NOT_GIVEN, request_options: typing.Optional[RequestOptions] = None, ) -> models.V1FaceSwapPhotoCreateResponse: """ Face Swap Photo Create a face swap photo. Each photo costs 5 credits. The height/width of the output image depends on your subscription. Please refer to our [pricing](https://magichour.ai/pricing) page for more details POST /v1/face-swap-photo Args: name: The name of image. This value is mainly used for your own identification of the image. assets: Provide the assets for face swap photo request_options: Additional options to customize the HTTP request Returns: Success Raises: ApiError: A custom exception class that provides additional context for API errors, including the HTTP status code and response body. Examples: ```py await client.v1.face_swap_photo.create( assets={ "face_mappings": [ { "new_face": "api-assets/id/1234.png", "original_face": "api-assets/id/0-0.png", } ], "face_swap_mode": "all-faces", "source_file_path": "api-assets/id/1234.png", "target_file_path": "api-assets/id/1234.png", }, name="Face Swap image", ) ``` """ _json = to_encodable( item={"name": name, "assets": assets}, dump_with=params._SerializerV1FaceSwapPhotoCreateBody, ) return await self._base_client.request( method="POST", path="/v1/face-swap-photo", auth_names=["bearerAuth"], json=_json, cast_to=models.V1FaceSwapPhotoCreateResponse, request_options=request_options or default_request_options(), )
35
0.742681
1
0.742681
ml-ai
AI_DATA
0.661698
ml-ai
0.736256
1
0.736256
vancegroup/arduino-boost
1,343
boost/mpl/protect.hpp
#ifndef BOOST_MPL_PROTECT_HPP_INCLUDED #define BOOST_MPL_PROTECT_HPP_INCLUDED // Copyright Peter Dimov 2001 // Copyright Aleksey Gurtovoy 2002-2004 // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/mpl for documentation. // $Id: protect.hpp 49267 2008-10-11 06:19:02Z agurtovoy $ // $Date: 2008-10-10 23:19:02 -0700 (Fri, 10 Oct 2008) $ // $Revision: 49267 $ #include <boost/mpl/aux_/arity.hpp> #include <boost/mpl/aux_/config/dtp.hpp> #include <boost/mpl/aux_/nttp_decl.hpp> #include <boost/mpl/aux_/na_spec.hpp> namespace boost { namespace mpl { template< typename BOOST_MPL_AUX_NA_PARAM(T) , int not_le_ = 0 > struct protect : T { #if BOOST_WORKAROUND(__EDG_VERSION__, == 238) typedef mpl::protect type; #else typedef protect type; #endif }; #if defined(BOOST_MPL_CFG_BROKEN_DEFAULT_PARAMETERS_IN_NESTED_TEMPLATES) namespace aux { template< BOOST_MPL_AUX_NTTP_DECL(int, N), typename T > struct arity< protect<T>, N > : arity<T,N> { }; } // namespace aux #endif BOOST_MPL_AUX_NA_SPEC_MAIN(1, protect) #if !defined(BOOST_MPL_CFG_NO_FULL_LAMBDA_SUPPORT) BOOST_MPL_AUX_NA_SPEC_TEMPLATE_ARITY(1, 1, protect) #endif }} #endif // BOOST_MPL_PROTECT_HPP_INCLUDED
35
0.950424
1
0.950424
compilers-parsers
SYSTEMS
0.802182
compilers-parsers
0.893906
1
0.893906
cvlab-yonsei/AZ-NAS
1,138
ImageNet_MBV2/xautodl/xmisc/__init__.py
##################################################### # Copyright (c) Xuanyi Dong [GitHub D-X-Y], 2021.06 # ##################################################### """The module and yaml related functions.""" from .module_utils import call_by_dict from .module_utils import call_by_yaml from .module_utils import nested_call_by_dict from .module_utils import nested_call_by_yaml from .yaml_utils import load_yaml from .torch_utils import count_parameters from .logger_utils import Logger """The data sampler related classes.""" from .sampler_utils import BatchSampler """The meter related classes.""" from .meter_utils import AverageMeter """The scheduler related classes.""" from .scheduler_utils import CosineParamScheduler, WarmupParamScheduler, LRMultiplier def get_scheduler(indicator, lr): if indicator == "warm-cos": multiplier = WarmupParamScheduler( CosineParamScheduler(lr, lr * 1e-3), warmup_factor=0.001, warmup_length=0.05, warmup_method="linear", ) else: raise ValueError("Unknown indicator: {:}".format(indicator)) return multiplier
35
0.582994
1
0.582994
llm-systems
AI_DATA
0.370514
llm-systems
0.440091
0
0.559909
OPTML-Group/Unlearn-Simple
7,983
TOFU/environment.yml
name: tofu channels: - pytorch - nvidia - defaults dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - anyio=3.5.0=py39h06a4308_0 - archspec=0.2.1=pyhd3eb1b0_0 - argon2-cffi=21.3.0=pyhd3eb1b0_0 - argon2-cffi-bindings=21.2.0=py39h7f8727e_0 - asttokens=2.0.5=pyhd3eb1b0_0 - attrs=22.1.0=py39h06a4308_0 - backcall=0.2.0=pyhd3eb1b0_0 - beautifulsoup4=4.12.2=py39h06a4308_0 - blas=1.0=mkl - bleach=4.1.0=pyhd3eb1b0_0 - boltons=23.0.0=py39h06a4308_0 - brotlipy=0.7.0=py39h27cfd23_1003 - bzip2=1.0.8=h7b6447c_0 - c-ares=1.19.1=h5eee18b_0 - ca-certificates=2023.12.12=h06a4308_0 - certifi=2023.11.17=py39h06a4308_0 - cffi=1.15.1=py39h5eee18b_3 - charset-normalizer=2.0.4=pyhd3eb1b0_0 - comm=0.1.2=py39h06a4308_0 - conda=24.1.0=py39h06a4308_0 - conda-libmamba-solver=24.1.0=pyhd3eb1b0_0 - conda-package-handling=2.2.0=py39h06a4308_0 - conda-package-streaming=0.9.0=py39h06a4308_0 - cryptography=41.0.2=py39h22a60cf_0 - cuda-cudart=11.8.89=0 - cuda-cupti=11.8.87=0 - cuda-libraries=11.8.0=0 - cuda-nvrtc=11.8.89=0 - cuda-nvtx=11.8.86=0 - cuda-opencl=12.3.101=0 - cuda-runtime=11.8.0=0 - debugpy=1.6.7=py39h6a678d5_0 - decorator=5.1.1=pyhd3eb1b0_0 - defusedxml=0.7.1=pyhd3eb1b0_0 - distro=1.8.0=py39h06a4308_0 - entrypoints=0.4=py39h06a4308_0 - executing=0.8.3=pyhd3eb1b0_0 - filelock=3.13.1=py39h06a4308_0 - fmt=9.1.0=hdb19cb5_0 - gmp=6.2.1=h295c915_3 - gmpy2=2.1.2=py39heeb90bb_0 - icu=73.1=h6a678d5_0 - idna=3.4=py39h06a4308_0 - importlib-metadata=6.0.0=py39h06a4308_0 - importlib_metadata=6.0.0=hd3eb1b0_0 - intel-openmp=2023.1.0=hdb19cb5_46306 - ipykernel=6.25.0=py39h2f386ee_0 - ipython=8.12.2=py39h06a4308_0 - ipython_genutils=0.2.0=pyhd3eb1b0_1 - jedi=0.18.1=py39h06a4308_1 - jinja2=3.1.2=py39h06a4308_0 - jsonpatch=1.32=pyhd3eb1b0_0 - jsonpointer=2.1=pyhd3eb1b0_0 - jsonschema=4.17.3=py39h06a4308_0 - jupyter_client=7.4.9=py39h06a4308_0 - jupyter_core=5.3.0=py39h06a4308_0 - jupyter_events=0.6.3=py39h06a4308_0 - jupyter_server=1.23.4=py39h06a4308_0 - jupyter_server_terminals=0.4.4=py39h06a4308_1 - jupyterlab_pygments=0.1.2=py_0 - krb5=1.20.1=h143b758_1 - ld_impl_linux-64=2.38=h1181459_1 - libarchive=3.6.2=h6ac8c49_2 - libcublas=11.11.3.6=0 - libcufft=10.9.0.58=0 - libcufile=1.8.1.2=0 - libcurand=10.3.4.107=0 - libcurl=8.5.0=h251f7ec_0 - libcusolver=11.4.1.48=0 - libcusparse=11.7.5.86=0 - libedit=3.1.20230828=h5eee18b_0 - libev=4.33=h7f8727e_1 - libffi=3.4.4=h6a678d5_0 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libmamba=1.5.6=haf1ee3a_0 - libmambapy=1.5.6=py39h2dafd23_0 - libnghttp2=1.57.0=h2d74bed_0 - libnpp=11.8.0.86=0 - libnvjitlink=12.1.105=0 - libnvjpeg=11.9.0.86=0 - libsodium=1.0.18=h7b6447c_0 - libsolv=0.7.24=he621ea3_0 - libssh2=1.10.0=hdbd6064_2 - libstdcxx-ng=11.2.0=h1234567_1 - libxml2=2.10.4=hf1b16e4_1 - libxslt=1.1.37=h5eee18b_1 - llvm-openmp=14.0.6=h9e868ea_0 - lxml=4.9.2=py39h5eee18b_0 - lz4-c=1.9.4=h6a678d5_0 - markupsafe=2.1.1=py39h7f8727e_0 - matplotlib-inline=0.1.6=py39h06a4308_0 - menuinst=2.0.2=py39h06a4308_0 - mistune=0.8.4=py39h27cfd23_1000 - mkl=2023.1.0=h213fc3f_46344 - mpc=1.1.0=h10f8cd9_1 - mpfr=4.0.2=hb69a4c5_1 - mpmath=1.3.0=py39h06a4308_0 - nb_conda_kernels=2.3.1=py39h06a4308_0 - nbclassic=0.5.5=py39h06a4308_0 - nbclient=0.5.13=py39h06a4308_0 - nbconvert=6.5.4=py39h06a4308_0 - nbformat=5.7.0=py39h06a4308_0 - ncurses=6.4=h6a678d5_0 - nest-asyncio=1.5.6=py39h06a4308_0 - notebook=6.5.3=py39h06a4308_0 - notebook-shim=0.2.2=py39h06a4308_0 - openssl=3.0.12=h7f8727e_0 - packaging=23.0=py39h06a4308_0 - pandocfilters=1.5.0=pyhd3eb1b0_0 - parso=0.8.3=pyhd3eb1b0_0 - pcre2=10.42=hebb0a14_0 - pexpect=4.8.0=pyhd3eb1b0_3 - pickleshare=0.7.5=pyhd3eb1b0_1003 - pip=23.2.1=py39h06a4308_0 - platformdirs=3.10.0=py39h06a4308_0 - pluggy=1.0.0=py39h06a4308_1 - prometheus_client=0.14.1=py39h06a4308_0 - prompt-toolkit=3.0.36=py39h06a4308_0 - ptyprocess=0.7.0=pyhd3eb1b0_2 - pure_eval=0.2.2=pyhd3eb1b0_0 - pybind11-abi=4=hd3eb1b0_1 - pycosat=0.6.4=py39h5eee18b_0 - pycparser=2.21=pyhd3eb1b0_0 - pygments=2.15.1=py39h06a4308_1 - pyopenssl=23.2.0=py39h06a4308_0 - pyrsistent=0.18.0=py39heee7806_0 - pysocks=1.7.1=py39h06a4308_0 - python=3.9.17=h955ad1f_0 - python-dateutil=2.8.2=pyhd3eb1b0_0 - python-fastjsonschema=2.16.2=py39h06a4308_0 - python-json-logger=2.0.7=py39h06a4308_0 - pytorch=2.2.0=py3.9_cuda11.8_cudnn8.7.0_0 - pytorch-cuda=11.8=h7e8668a_5 - pytorch-mutex=1.0=cuda - pyyaml=6.0=py39h5eee18b_1 - pyzmq=23.2.0=py39h6a678d5_0 - readline=8.2=h5eee18b_0 - reproc=14.2.4=h295c915_1 - reproc-cpp=14.2.4=h295c915_1 - requests=2.31.0=py39h06a4308_0 - rfc3339-validator=0.1.4=py39h06a4308_0 - rfc3986-validator=0.1.1=py39h06a4308_0 - ruamel.yaml=0.17.21=py39h5eee18b_0 - ruamel.yaml.clib=0.2.6=py39h5eee18b_1 - ruamel_yaml=0.15.100=py39h27cfd23_0 - send2trash=1.8.0=pyhd3eb1b0_1 - setuptools=68.0.0=py39h06a4308_0 - six=1.16.0=pyhd3eb1b0_1 - sniffio=1.2.0=py39h06a4308_1 - soupsieve=2.4=py39h06a4308_0 - sqlite=3.41.2=h5eee18b_0 - stack_data=0.2.0=pyhd3eb1b0_0 - sympy=1.12=py39h06a4308_0 - tbb=2021.8.0=hdb19cb5_0 - terminado=0.17.1=py39h06a4308_0 - tinycss2=1.2.1=py39h06a4308_0 - tk=8.6.12=h1ccaba5_0 - toolz=0.12.0=py39h06a4308_0 - torchtriton=2.2.0=py39 - tornado=6.3.2=py39h5eee18b_0 - traitlets=5.7.1=py39h06a4308_0 - urllib3=1.26.16=py39h06a4308_0 - wcwidth=0.2.5=pyhd3eb1b0_0 - webencodings=0.5.1=py39h06a4308_1 - websocket-client=0.58.0=py39h06a4308_4 - wheel=0.38.4=py39h06a4308_0 - xz=5.4.2=h5eee18b_0 - yaml=0.2.5=h7b6447c_0 - yaml-cpp=0.8.0=h6a678d5_0 - zeromq=4.3.4=h2531618_0 - zipp=3.11.0=py39h06a4308_0 - zlib=1.2.13=h5eee18b_0 - zstandard=0.19.0=py39h5eee18b_0 - zstd=1.5.5=hc292b87_0 - pip: - absl-py==2.1.0 - accelerate==0.26.1 - aiohttp==3.9.3 - aiosignal==1.3.1 - async-timeout==4.0.3 - blessings==1.7 - chardet==5.2.0 - click==8.1.7 - colorama==0.4.6 - dataproperty==1.0.1 - datasets==2.16.1 - dill==0.3.7 - evaluate==0.4.1 - frozenlist==1.4.1 - fsspec==2023.10.0 - gpustat==0.6.0 - huggingface-hub==0.20.3 - joblib==1.3.2 - jsonlines==4.0.0 - lm-dataformat==0.0.20 - lm-eval==0.4.1 - mbstrdecoder==1.1.3 - multidict==6.0.5 - multiprocess==0.70.15 - networkx==3.2.1 - nltk==3.8.1 - numexpr==2.9.0 - numpy==1.26.3 - nvidia-cublas-cu12==12.1.3.1 - nvidia-cuda-cupti-cu12==12.1.105 - nvidia-cuda-nvrtc-cu12==12.1.105 - nvidia-cuda-runtime-cu12==12.1.105 - nvidia-cudnn-cu12==8.9.2.26 - nvidia-cufft-cu12==11.0.2.54 - nvidia-curand-cu12==10.3.2.106 - nvidia-cusolver-cu12==11.4.5.107 - nvidia-cusparse-cu12==12.1.0.106 - nvidia-ml-py3==7.352.0 - nvidia-nccl-cu12==2.19.3 - nvidia-nvjitlink-cu12==12.3.101 - nvidia-nvtx-cu12==12.1.105 - pandas==2.2.0 - pathvalidate==3.2.0 - peft==0.8.2 - portalocker==2.8.2 - psutil==5.9.1 - pyarrow==15.0.0 - pyarrow-hotfix==0.6 - pybind11==2.11.1 - pytablewriter==1.2.0 - pytz==2024.1 - regex==2023.12.25 - responses==0.18.0 - rouge-score==0.1.2 - sacrebleu==2.4.0 - safetensors==0.4.2 - scikit-learn==1.4.0 - scipy==1.12.0 - sqlitedict==2.1.0 - tabledata==1.3.3 - tabulate==0.9.0 - tcolorpy==0.1.4 - threadpoolctl==3.2.0 - tokenizers==0.15.1 - torch==2.2.0 - tqdm==4.66.1 - tqdm-multiprocess==0.0.11 - transformers==4.37.2 - triton==2.2.0 - typepy==1.3.2 - typing-extensions==4.9.0 - tzdata==2023.4 - ujson==5.9.0 - xxhash==3.4.1 - yarl==1.9.4
35
0.642971
1
0.642971
ml-ai
AI_DATA
0.600695
ml-ai,deep-learning
0.000031
0
0.999969
dulingkang/Capture
1,574
Capture/Capture/Lib/BaiduAds/ios_api/BaiduMobAdVideoDelegate.h
// // BaiduMobAdVideoDelegate.h // BaiduMobAdSdk // // Created by lishan04 on 15-6-8. // // #import <Foundation/Foundation.h> #import "BaiduMobAdCommonConfig.h" @class BaiduMobAdVideoView; @protocol BaiduMobAdVideoDelegate <NSObject> @required /** * 应用的APPID */ - (NSString *)publisherId; @optional /** * 启动位置信息 */ -(BOOL) enableLocation; /** * 广告准备播放 */ - (void)didReadyForDisplay:(BaiduMobAdVideoView *)video; /** * 广告展示成功 */ - (void)videoSuccessPresentScreen:(BaiduMobAdVideoView *)video; /** * 广告展示失败 */ - (void)videoFailPresentScreen:(BaiduMobAdVideoView *)video withError:(BaiduMobFailReason) reason; /** * 广告展示结束 */ - (void)videoDidDismissScreen:(BaiduMobAdVideoView *)video; /** * 广告点击 */ - (void)videoClicked:(BaiduMobAdVideoView *)video; ///--------------------------------------------------------------------------------------- /// @name 人群属性板块 ///--------------------------------------------------------------------------------------- /** * 关键词数组 */ -(NSArray*) keywords; /** * 用户性别 */ -(BaiduMobAdUserGender) userGender; /** * 用户生日 */ -(NSDate*) userBirthday; /** * 用户城市 */ -(NSString*) userCity; /** * 用户邮编 */ -(NSString*) userPostalCode; /** * 用户职业 */ -(NSString*) userWork; /** * - 用户最高教育学历 * - 学历输入数字,范围为0-6 * - 0代表小学,1代表初中,2代表中专/高中,3代表专科 * - 4代表本科,5代表硕士,6代表博士 */ -(NSInteger) userEducation; /** * - 用户收入 * - 收入输入数字,以元为单位 */ -(NSInteger) userSalary; /** * 用户爱好 */ -(NSArray*) userHobbies; /** * 其他自定义字段,key以及value都为NSString */ -(NSDictionary*) userOtherAttributes; @end
35
0.603221
1
0.603221
mobile
APP_WEB
0.632391
mobile
0.00212
0
0.99788
strongcourage/uafuzz
9,177
binsec/src/uafuzz/afl-2.52b/qemu_mode_aflgob/qemu-2.10.0/roms/u-boot/arch/arm/mach-tegra/tegra20/warmboot.c
/* * (C) Copyright 2010 - 2011 * NVIDIA Corporation <www.nvidia.com> * * SPDX-License-Identifier: GPL-2.0+ */ #include <common.h> #include <asm/io.h> #include <linux/errno.h> #include <asm/arch/clock.h> #include <asm/arch/emc.h> #include <asm/arch/gp_padctrl.h> #include <asm/arch/pinmux.h> #include <asm/arch/sdram_param.h> #include <asm/arch/tegra.h> #include <asm/arch-tegra/ap.h> #include <asm/arch-tegra/apb_misc.h> #include <asm/arch-tegra/clk_rst.h> #include <asm/arch-tegra/pmc.h> #include <asm/arch-tegra/fuse.h> #include <asm/arch-tegra/warmboot.h> DECLARE_GLOBAL_DATA_PTR; #ifndef CONFIG_TEGRA_CLOCK_SCALING #error "You must enable CONFIG_TEGRA_CLOCK_SCALING to use CONFIG_TEGRA_LP0" #endif /* * This is the place in SRAM where the SDRAM parameters are stored. There * are 4 blocks, one for each RAM code */ #define SDRAM_PARAMS_BASE (NV_PA_BASE_SRAM + 0x188) /* TODO: If we later add support for the Misc GP controller, refactor this */ union xm2cfga_reg { struct { u32 reserved0:2; u32 hsm_en:1; u32 reserved1:2; u32 preemp_en:1; u32 vref_en:1; u32 reserved2:5; u32 cal_drvdn:5; u32 reserved3:3; u32 cal_drvup:5; u32 reserved4:3; u32 cal_drvdn_slwr:2; u32 cal_drvup_slwf:2; }; u32 word; }; union xm2cfgd_reg { struct { u32 reserved0:2; u32 hsm_en:1; u32 schmt_en:1; u32 lpmd:2; u32 vref_en:1; u32 reserved1:5; u32 cal_drvdn:5; u32 reserved2:3; u32 cal_drvup:5; u32 reserved3:3; u32 cal_drvdn_slwr:2; u32 cal_drvup_slwf:2; }; u32 word; }; /* * TODO: This register is not documented in the TRM yet. We could move this * into the EMC and give it a proper interface, but not while it is * undocumented. */ union fbio_spare_reg { struct { u32 reserved:24; u32 cfg_wb0:8; }; u32 word; }; /* We pack the resume information into these unions for later */ union scratch2_reg { struct { u32 pllm_base_divm:5; u32 pllm_base_divn:10; u32 pllm_base_divp:3; u32 pllm_misc_lfcon:4; u32 pllm_misc_cpcon:4; u32 gp_xm2cfga_padctrl_preemp:1; u32 gp_xm2cfgd_padctrl_schmt:1; u32 osc_ctrl_xobp:1; u32 memory_type:3; }; u32 word; }; union scratch4_reg { struct { u32 emc_clock_divider:8; u32 pllm_stable_time:8; u32 pllx_stable_time:8; u32 emc_fbio_spare_cfg_wb0:8; }; u32 word; }; union scratch24_reg { struct { u32 emc_auto_cal_wait:8; u32 emc_pin_program_wait:8; u32 warmboot_wait:8; u32 reserved:8; }; u32 word; }; int warmboot_save_sdram_params(void) { u32 ram_code; struct sdram_params sdram; struct apb_misc_pp_ctlr *apb_misc = (struct apb_misc_pp_ctlr *)NV_PA_APB_MISC_BASE; struct pmc_ctlr *pmc = (struct pmc_ctlr *)NV_PA_PMC_BASE; struct apb_misc_gp_ctlr *gp = (struct apb_misc_gp_ctlr *)NV_PA_APB_MISC_GP_BASE; struct emc_ctlr *emc = emc_get_controller(gd->fdt_blob); union scratch2_reg scratch2; union scratch4_reg scratch4; union scratch24_reg scratch24; union xm2cfga_reg xm2cfga; union xm2cfgd_reg xm2cfgd; union fbio_spare_reg fbio_spare; /* get ram code that is used as index to array sdram_params in BCT */ ram_code = (readl(&apb_misc->strapping_opt_a) >> STRAP_OPT_A_RAM_CODE_SHIFT) & 3; memcpy(&sdram, (char *)((struct sdram_params *)SDRAM_PARAMS_BASE + ram_code), sizeof(sdram)); xm2cfga.word = readl(&gp->xm2cfga); xm2cfgd.word = readl(&gp->xm2cfgd); scratch2.word = 0; scratch2.osc_ctrl_xobp = clock_get_osc_bypass(); /* Get the memory PLL settings */ { u32 divm, divn, divp, cpcon, lfcon; if (clock_ll_read_pll(CLOCK_ID_MEMORY, &divm, &divn, &divp, &cpcon, &lfcon)) return -1; scratch2.pllm_base_divm = divm; scratch2.pllm_base_divn = divn; scratch2.pllm_base_divp = divp; scratch2.pllm_misc_cpcon = cpcon; scratch2.pllm_misc_lfcon = lfcon; } scratch2.gp_xm2cfga_padctrl_preemp = xm2cfga.preemp_en; scratch2.gp_xm2cfgd_padctrl_schmt = xm2cfgd.schmt_en; scratch2.memory_type = sdram.memory_type; writel(scratch2.word, &pmc->pmc_scratch2); /* collect data from various sources for pmc_scratch4 */ fbio_spare.word = readl(&emc->fbio_spare); scratch4.word = 0; scratch4.emc_fbio_spare_cfg_wb0 = fbio_spare.cfg_wb0; scratch4.emc_clock_divider = sdram.emc_clock_divider; scratch4.pllm_stable_time = -1; scratch4.pllx_stable_time = -1; writel(scratch4.word, &pmc->pmc_scratch4); /* collect various data from sdram for pmc_scratch24 */ scratch24.word = 0; scratch24.emc_pin_program_wait = sdram.emc_pin_program_wait; scratch24.emc_auto_cal_wait = sdram.emc_auto_cal_wait; scratch24.warmboot_wait = sdram.warm_boot_wait; writel(scratch24.word, &pmc->pmc_scratch24); return 0; } static u32 get_major_version(void) { u32 major_id; struct apb_misc_gp_ctlr *gp = (struct apb_misc_gp_ctlr *)NV_PA_APB_MISC_GP_BASE; major_id = (readl(&gp->hidrev) & HIDREV_MAJORPREV_MASK) >> HIDREV_MAJORPREV_SHIFT; return major_id; } static int is_production_mode_fuse_set(struct fuse_regs *fuse) { return readl(&fuse->production_mode); } static int is_odm_production_mode_fuse_set(struct fuse_regs *fuse) { return readl(&fuse->security_mode); } static int is_failure_analysis_mode(struct fuse_regs *fuse) { return readl(&fuse->fa); } static int ap20_is_odm_production_mode(void) { struct fuse_regs *fuse = (struct fuse_regs *)NV_PA_FUSE_BASE; if (!is_failure_analysis_mode(fuse) && is_odm_production_mode_fuse_set(fuse)) return 1; else return 0; } static int ap20_is_production_mode(void) { struct fuse_regs *fuse = (struct fuse_regs *)NV_PA_FUSE_BASE; if (get_major_version() == 0) return 1; if (!is_failure_analysis_mode(fuse) && is_production_mode_fuse_set(fuse) && !is_odm_production_mode_fuse_set(fuse)) return 1; else return 0; } static enum fuse_operating_mode fuse_get_operation_mode(void) { u32 chip_id; struct apb_misc_gp_ctlr *gp = (struct apb_misc_gp_ctlr *)NV_PA_APB_MISC_GP_BASE; chip_id = (readl(&gp->hidrev) & HIDREV_CHIPID_MASK) >> HIDREV_CHIPID_SHIFT; if (chip_id == CHIPID_TEGRA20) { if (ap20_is_odm_production_mode()) { printf("!! odm_production_mode is not supported !!\n"); return MODE_UNDEFINED; } else if (ap20_is_production_mode()) return MODE_PRODUCTION; else return MODE_UNDEFINED; } return MODE_UNDEFINED; } static void determine_crypto_options(int *is_encrypted, int *is_signed, int *use_zero_key) { switch (fuse_get_operation_mode()) { case MODE_PRODUCTION: *is_encrypted = 0; *is_signed = 1; *use_zero_key = 1; break; case MODE_UNDEFINED: default: *is_encrypted = 0; *is_signed = 0; *use_zero_key = 0; break; } } static int sign_wb_code(u32 start, u32 length, int use_zero_key) { int err; u8 *source; /* Pointer to source */ u8 *hash; /* Calculate AES block parameters. */ source = (u8 *)(start + offsetof(struct wb_header, random_aes_block)); length -= offsetof(struct wb_header, random_aes_block); hash = (u8 *)(start + offsetof(struct wb_header, hash)); err = sign_data_block(source, length, hash); return err; } int warmboot_prepare_code(u32 seg_address, u32 seg_length) { int err = 0; u32 length; /* length of the signed/encrypt code */ struct wb_header *dst_header; /* Pointer to dest WB header */ int is_encrypted; /* Segment is encrypted */ int is_signed; /* Segment is signed */ int use_zero_key; /* Use key of all zeros */ /* Determine crypto options. */ determine_crypto_options(&is_encrypted, &is_signed, &use_zero_key); /* Get the actual code limits. */ length = roundup(((u32)wb_end - (u32)wb_start), 16); /* * The region specified by seg_address must be in SDRAM and must be * nonzero in length. */ if (seg_length == 0 || seg_address < NV_PA_SDRAM_BASE || seg_address + seg_length >= NV_PA_SDRAM_BASE + gd->ram_size) { err = -EFAULT; goto fail; } /* Things must be 16-byte aligned. */ if ((seg_length & 0xF) || (seg_address & 0xF)) { err = -EINVAL; goto fail; } /* Will the code fit? (destination includes wb_header + wb code) */ if (seg_length < (length + sizeof(struct wb_header))) { err = -EINVAL; goto fail; } dst_header = (struct wb_header *)seg_address; memset((char *)dst_header, 0, sizeof(struct wb_header)); /* Populate the random_aes_block as requested. */ { u32 *aes_block = (u32 *)&(dst_header->random_aes_block); u32 *end = (u32 *)(((u32)aes_block) + sizeof(dst_header->random_aes_block)); do { *aes_block++ = 0; } while (aes_block < end); } /* Populate the header. */ dst_header->length_insecure = length + sizeof(struct wb_header); dst_header->length_secure = length + sizeof(struct wb_header); dst_header->destination = NV_WB_RUN_ADDRESS; dst_header->entry_point = NV_WB_RUN_ADDRESS; dst_header->code_length = length; if (is_encrypted) { printf("!!!! Encryption is not supported !!!!\n"); dst_header->length_insecure = 0; err = -EACCES; goto fail; } else /* copy the wb code directly following dst_header. */ memcpy((char *)(dst_header+1), (char *)wb_start, length); if (is_signed) err = sign_wb_code(seg_address, dst_header->length_insecure, use_zero_key); fail: if (err) printf("Warning: warmboot code copy failed (error=%d)\n", err); return err; }
35
0.995165
1
0.995165
drivers
SYSTEMS
0.61542
drivers,os-kernel
0.992434
1
0.992434
Squidex/squidex
1,160
backend/src/Squidex/Areas/IdentityServer/Controllers/Test/TestController.cs
// ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschraenkt) // All rights reserved. Licensed under the MIT license. // ========================================================================== using Microsoft.AspNetCore.Mvc; using Squidex.Areas.IdentityServer.Config; using Squidex.Domain.Apps.Core.Teams; namespace Squidex.Areas.IdentityServer.Controllers.Test; public sealed class TestController(DynamicSchemeProvider schemes) : IdentityServerController { [Route("test/")] public async Task<IActionResult> Test( [FromQuery] AuthScheme scheme) { var id = await schemes.AddTemporarySchemeAsync(scheme, default); var challengeRedirectUrl = Url.Action(nameof(Success)); var challengeProperties = SignInManager.ConfigureExternalAuthenticationProperties(id, challengeRedirectUrl); return Challenge(challengeProperties, id); } [Route("test/success/")] public IActionResult Success() { return View(); } }
35
0.841196
1
0.841196
testing-qa
OPS
0.771676
testing-qa,web-backend
0.868889
1
0.868889
End of preview. Expand in Data Studio

No dataset card yet

Downloads last month
3