code
stringlengths
46
36.6k
language
stringclasses
9 values
AST_depth
int64
3
30
alphanumeric_fraction
float64
0.2
0.98
max_line_length
int64
13
399
avg_line_length
float64
5.08
140
num_lines
int64
7
299
original_docstring
stringlengths
8
34.8k
source
stringclasses
2 values
void write_stats_core(int prev, int curr, int dis, char *prev_string, char *curr_string) { unsigned long long itv, deltot_jiffies = 1; int tab = 4, next = FALSE; unsigned char offline_cpu_bitmap[BITMAP_SIZE(NR_CPUS)] = {0}; TEST_STDOUT(STDOUT_FILENO); deltot_jiffies = get_global_cpu_mpstats(prev, curr, offline_cpu_bitmap); if (DISPLAY_JSON_OUTPUT(flags)) { xprintf(tab++, "{"); xprintf(tab, "\"timestamp\": \"%s\",", curr_string); } itv = get_interval(uptime_cs[prev], uptime_cs[curr]); if (DISPLAY_CPU(actflags)) { write_cpu_stats(dis, deltot_jiffies, prev, curr, prev_string, curr_string, tab, &next, offline_cpu_bitmap); } if (DISPLAY_NODE(actflags)) { set_node_cpu_stats(prev, curr); write_node_stats(dis, deltot_jiffies, prev, curr, prev_string, curr_string, tab, &next); } if (DISPLAY_IRQ_SUM(actflags)) { write_isumcpu_stats(dis, itv, prev, curr, prev_string, curr_string, tab, &next); } if (DISPLAY_IRQ_CPU(actflags)) { write_irqcpu_stats(st_irqcpu, irqcpu_nr, dis, itv, prev, curr, prev_string, curr_string, tab, &next, M_D_IRQ_CPU); } if (DISPLAY_SOFTIRQS(actflags)) { write_irqcpu_stats(st_softirqcpu, softirqcpu_nr, dis, itv, prev, curr, prev_string, curr_string, tab, &next, M_D_SOFTIRQS); } if (DISPLAY_JSON_OUTPUT(flags)) { printf("\n"); xprintf0(--tab, "}"); } }
c
9
0.58377
78
38.205128
39
/* *************************************************************************** * Core function used to display statistics. * * IN: * @prev Position in array where statistics used as reference are. * Stats used as reference may be the previous ones read, or * the very first ones when calculating the average. * @curr Position in array where statistics for current sample are. * @dis TRUE if a header line must be printed. * @prev_string String displayed at the beginning of a header line. This is * the timestamp of the previous sample, or "Average" when * displaying average stats. * @curr_string String displayed at the beginning of current sample stats. * This is the timestamp of the current sample, or "Average" * when displaying average stats. *************************************************************************** */
function
public abstract class DiscreteFunction2D<ValueType extends Value> extends StateActionFunction<ValueType> { public DiscreteFunction2D(int actionsSize) { super(actionsSize); } public DiscreteFunction2D(StateTranslator range) { super(range); } // private void initStates(StateTranslator range) { // final int tSize = range.observation.length; // DiscreteState state = new DiscreteState(tSize); // state.reset(); // // do { // DiscreteState curr = new DiscreteState( state ); // map.put(curr, new ActionValuesList()); // } while( range.increase( state ) ); // } public ValueType value(DiscreteState state, int action) { DiscreteList<ValueType> actions = getActions(state); return actions.get( action ); } public Iterator<Item> iterator() { return new ItemIterator(); } //===================================================== public class Item { public DiscreteState state; public int action; public ValueType value; public Item(DiscreteState state, int action, ValueType val) { this.state = state; this.action = action; value = val; } } class ItemIterator implements Iterator<Item> { private Iterator<Entry< DiscreteState, DiscreteList<ValueType> >> mapPos = null; private DiscreteState state = null; private DiscreteList<ValueType> list = null; private int action = 0; public ItemIterator() { mapPos = map.entrySet().iterator(); } @Override public boolean hasNext() { if (mapPos.hasNext()==true) { return true; } if ( (action+1) < list.size()) { return true; } return false; } @Override public Item next() { ++action; if (list != null) { if ( action < list.size() ) { /// valid return nextItem(); } } Entry<DiscreteState, DiscreteList<ValueType>> nextElem = mapPos.next(); setPosition( nextElem ); return nextItem(); } private void setPosition(Entry<DiscreteState, DiscreteList<ValueType>> nextElem) { state = nextElem.getKey(); list = nextElem.getValue(); action = 0; } private Item nextItem() { ValueType val = list.get(action); return new Item(state, action, val); } @Override public void remove() { /// not supported } } }
java
14
0.646113
107
20.737864
103
/** * @author bob * * Action-value function. * */
class
func (r RuntimeArgs) ToJSONInterface() []interface{} { result := make([]interface{}, 0) for _, k := range r.KeyOrder { temp := make([]interface{}, 2) temp[0] = k temp[1] = r.Args[k] result = append(result, temp) } return result }
go
11
0.609959
54
23.2
10
// runtime args in deploy are encoded as an array of pairs "key" : "value"
function
class TextEditor extends Editor { Document createDocument() { return new Document() { void open() { System.out.println("Open text file." + this.getTitle()); } void save() { System.out.println("Save text file." + this.getTitle()); } void close() { System.out.println("Close text file. " + this.getTitle()); } }; } }
java
16
0.581967
63
20.588235
17
// Implement abstract methods for text editor class.
class
def baja(self, dni_socio): try: self.datos.baja(dni_socio) except NoExisteDni: raise except: raise
python
9
0.481013
38
21.714286
7
Borra el socio especificado por el dni.
function
function runQuery (url, query) { fetch(url + '?query=' + encodeURIComponent(query) + '&format=json') .then(res => res.json()) .then(json => { let fetchedData = json.results.bindings fetchedData.forEach(item => { item.imageLink.value = item.imageLink.value.replace('http', 'https') }) console.log('fetchedData: ', fetchedData) return fetchedData }) .then(fetchedData => { let newData = cleanDataYear(fetchedData) console.log('cleaned data: ', newData) }) }
javascript
21
0.616698
76
32
16
// The base of this code is Laurens. I changed it to suit my use case
function
void distribuisciCarte(Nodo **listaCarte, Nodo **listaCarteSpeciali, Giocatore giocatori[]) { int i = 0, j = 0; for(i = 0; i < NUM_GIOCATORI; i++) { giocatori[i].carte = (Carta *) malloc(sizeof(Carta) * MANO_GIOCATORE); if(giocatori[i].carte == NULL) exit(-1); giocatori[i].numCarte = MANO_GIOCATORE; } for(i = 0; i < NUM_GIOCATORI; i++) giocatori[i].carte[0] = estraiCarta(listaCarteSpeciali)->carta; for(i = 1; i < MANO_GIOCATORE; i++) for(j = 0; j < NUM_GIOCATORI; j++) giocatori[j].carte[i] = estraiCarta(listaCarte)->carta; }
c
13
0.578352
93
43.285714
14
// Distribuisce 5 carte a ogni giocatore (4 + 1 carta meooow)
function
class SimpleRequest: """ L{SimpleRequest} is a fake implementation of L{Request} which writes a short, fixed string to the transport passed to its C{writeTo} method and returns a succeeded L{Deferred}. This vaguely emulates the behavior of a L{Request} with no body producer. """ persistent = False def writeTo(self, transport): transport.write(b'SOME BYTES') return succeed(None)
python
9
0.690698
77
34.916667
12
L{SimpleRequest} is a fake implementation of L{Request} which writes a short, fixed string to the transport passed to its C{writeTo} method and returns a succeeded L{Deferred}. This vaguely emulates the behavior of a L{Request} with no body producer.
class
@SuppressWarnings("unused") public static void main(final String[] args) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, InvalidKeySpecException, IOException, IllegalBlockSizeException { final BufferedReader input = new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8.name())); System.out.print("Enter the string to encrypt (enter \"-\" to genernate a key): "); System.out.flush(); final String pwd = input.readLine(); if (pwd != null) { if (pwd.equals("-")) { final KeyGenerator keygen = KeyGenerator.getInstance(ALG); final SecretKey cv = keygen.generateKey(); byte[] raw = cv.getEncoded(); System.out.print("new byte[] {"); int i = 0; for (byte b : raw) { System.out.printf("(byte) 0x%02x", b); if (i < raw.length - 1) { System.out.print(", "); } i = i + 1; if (i % 8 == 0) { System.out.print("\n\t"); } } } else { final byte[] cleartext = pwd.getBytes(StandardCharsets.UTF_8.name()); final SecretKey cv = new SecretKeySpec(PasswordUtilities.getKey(), ALG); final Cipher cipher = Cipher.getInstance(ALG_SPEC); cipher.init(Cipher.ENCRYPT_MODE, cv); final byte[] ciphertext = cipher.doFinal(cleartext); System.out.print("The obfuscated password is: "); for (final byte b : ciphertext) { System.out.printf("%02x", b); } System.out.flush(); } } }
java
15
0.511578
213
49.216216
37
/** * Either obfuscate a password or (if "-" is entered for the password), * create a new key. * <p> * To run the main method navigate to constellation\Security\build\classes * on the command prompt and run the following command: * <pre> * java -cp . au.gov.asd.tac.constellation.security.password.PasswordObfuscator * </pre> * <p> * Should you decide to create a new key, note that all existing obfuscated * passwords will need to be re-obfuscated using the new key. You need to * de-obfuscate the passwords using the old key first (via * <code>PasswordDeobfuscator</code>) and re-obfuscate the password with the * new key. * * @param args * @throws NoSuchAlgorithmException * @throws NoSuchPaddingException * @throws InvalidKeyException * @throws IllegalBlockSizeException * @throws BadPaddingException * @throws IOException * @throws InvalidKeySpecException */
function
public abstract class Roulette extends Game implements TableGame { protected ArrayList<Player> players; protected BigDecimal betMinimum; protected BigDecimal betMaximum; protected Wheel wheel; protected Stop result; protected enum Color { GREEN, RED, BLACK } /** * The stops of the roulette wheel. This will work for both American and * European roulette; the only difference is the use of the double zero and * the order of the stops. */ protected enum Stop { ZERO("0", Color.GREEN), DOUBLE_ZERO("00", Color.GREEN), ONE("1", Color.RED), TWO("2", Color.BLACK), THREE("3", Color.RED), FOUR("4", Color.BLACK), FIVE("5", Color.RED), SIX("6", Color.BLACK), SEVEN("7", Color.RED), EIGHT("8", Color.BLACK), NINE("9", Color.RED), TEN("10", Color.BLACK), ELEVEN("11", Color.BLACK), TWELVE("12", Color.RED), THIRTEEN("13", Color.BLACK), FOURTEEN("14", Color.RED), FIFTEEN("15", Color.BLACK), SIXTEEN("16", Color.RED), SEVENTEEN("17", Color.BLACK), EIGHTEEN("18", Color.RED), NINETEEN("19", Color.RED), TWENTY("20", Color.BLACK), TWENTY_ONE("21", Color.RED), TWENTY_TWO("22", Color.BLACK), TWENTY_THREE("23", Color.RED), TWENTY_FOUR("24", Color.BLACK), TWENTY_FIVE("25", Color.RED), TWENTY_SIX("26", Color.BLACK), TWENTY_SEVEN("27", Color.RED), TWENTY_EIGHT("28", Color.BLACK), TWENTY_NINE("29", Color.BLACK), THIRTY("30", Color.RED), THIRTY_ONE("31", Color.BLACK), THIRTY_TWO("32", Color.RED), THIRTY_THREE("33", Color.BLACK), THIRTY_FOUR("34", Color.RED), THIRTY_FIVE("35", Color.BLACK), THIRTY_SIX("36", Color.RED); private final String value; private final Color color; private Stop(String value, Color color) { this.value = value; this.color = color; } public String getValue() { return value; } public Color getColor() { return color; } public int getValueAsInt() { return Integer.parseInt(value); } } /** * For legibility, this enum combines certain types of bets together that has * the same odds. For example, bets of 0-1-2, 0-00-2, and 0/00-2-3 are special * cases of the corner bets, not street bets; but in the internal logic they are * counted as street bets. For the same reason, 0-1-2-3 is treated as a corner * bet despite technically being a form of the double street bet. */ protected enum betType{ STRAIGHT(new BigDecimal(36)), SPLIT(new BigDecimal(18)), STREET(new BigDecimal(12)), CORNER(new BigDecimal(9)), BASKET(new BigDecimal(7)), DOUBLE_STREET(new BigDecimal(6)), DOZEN(new BigDecimal(3)), HALF(new BigDecimal(2)); /** * Because of the way {@code Bet.awardBet()} works; this field holds the * odds "for 1", not the odds "to 1" (i.e. "2 for 1" in lieu of "1 to 1"). */ private final BigDecimal odds; private betType(BigDecimal odds) { this.odds = odds; } public BigDecimal getOdds() { return odds; } } @Override public void play(ArrayList<Player> players) { play(players, BigDecimal.valueOf(5, 2), BigDecimal.valueOf(1000, 2)); } @Override public void play(ArrayList<Player> players, BigDecimal betMinimum, BigDecimal betMaximum) { this.players = players; this.betMinimum = betMinimum; this.betMaximum = betMaximum; this.wheel = generateWheel(); this.result = Stop.ZERO; /* HACK: supposed to be wheel.getWheelResult(); but * that currently throws a type error */ } public abstract Wheel generateWheel(); }
java
11
0.67611
81
32.578431
102
/** * Because of the need for a different wheel for American and European roulette, * this class is abstract. However, since they are otherwise very similar games, * most of the code will be here, with subclasses called only to handle the * differences between the games. * * @author Jeffrey Hope <[email protected]> */
class
[TestCategory("MSASCMD"), TestMethod()] public void MSASCMD_S19_TC13_Sync_Tasks_FilterType() { #region Call Sync command to verify server supports to filter task when FilterType set to 0. SyncRequest syncRequest = TestSuiteBase.CreateEmptySyncRequest(this.User1Information.TasksCollectionId, 0); SyncResponse syncResponse = this.Sync(syncRequest); Site.Assert.IsNotNull(syncResponse.ResponseData.Item, "The items returned in the Sync command response should not be null."); Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R3053"); Site.CaptureRequirementIfAreEqual<uint>( 1, Convert.ToUInt32(TestSuiteBase.GetCollectionItem(syncResponse, Response.ItemsChoiceType10.Status)), 3053, @"[In FilterType(Sync)] Yes. [Applies to tasks, if FilterType is 0, Status element value is 1.]"); #endregion #region Call Sync command to verify server does not support to filter task when FilterType set to 1. syncRequest = TestSuiteBase.CreateEmptySyncRequest(this.User1Information.TasksCollectionId, 1); syncResponse = this.Sync(syncRequest); Site.Assert.IsNotNull(syncResponse.ResponseData, "The ResponseData should not be null."); Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R3054"); Site.CaptureRequirementIfAreNotEqual<string>( "1", syncResponse.ResponseData.Status, 3054, @"[In FilterType(Sync)] No, [Applies to tasks, if FilterType is 1, status is not 1.]"); #endregion #region Call Sync command to verify server does not support to filter task when FilterType set to 2. syncRequest = TestSuiteBase.CreateEmptySyncRequest(this.User1Information.TasksCollectionId, 2); syncResponse = this.Sync(syncRequest); Site.Assert.IsNotNull(syncResponse.ResponseData, "The ResponseData should not be null."); Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R3055"); Site.CaptureRequirementIfAreNotEqual<string>( "1", syncResponse.ResponseData.Status, 3055, @"[In FilterType(Sync)] No, [Applies to tasks, if FilterType is 2, status is not 1.]"); #endregion #region Call Sync command to verify server does not support to filter task when FilterType set to 3. syncRequest = TestSuiteBase.CreateEmptySyncRequest(this.User1Information.TasksCollectionId, 3); syncResponse = this.Sync(syncRequest); Site.Assert.IsNotNull(syncResponse.ResponseData, "The ResponseData should not be null."); Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R3056"); Site.CaptureRequirementIfAreNotEqual<string>( "1", syncResponse.ResponseData.Status, 3056, @"[In FilterType(Sync)] No, [Applies to tasks, if FilterType is 3, status is not 1.]"); #endregion #region Call Sync command to verify server does not support to filter task when FilterType set to 4. syncRequest = TestSuiteBase.CreateEmptySyncRequest(this.User1Information.TasksCollectionId, 4); syncResponse = this.Sync(syncRequest); Site.Assert.IsNotNull(syncResponse.ResponseData, "The ResponseData should not be null."); Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R3057"); Site.CaptureRequirementIfAreNotEqual<string>( "1", syncResponse.ResponseData.Status, 3057, @"[In FilterType(Sync)] No, [Applies to tasks, if FilterType is 4, status is not 1.]"); #endregion #region Call Sync command to verify server does not support to filter task when FilterType set to 5. syncRequest = TestSuiteBase.CreateEmptySyncRequest(this.User1Information.TasksCollectionId, 5); syncResponse = this.Sync(syncRequest); Site.Assert.IsNotNull(syncResponse.ResponseData, "The ResponseData should not be null."); Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R3058"); Site.CaptureRequirementIfAreNotEqual<string>( "1", syncResponse.ResponseData.Status, 3058, @"[In FilterType(Sync)] No, [Applies to tasks, if FilterType is 5, status is not 1.]"); #endregion #region Call Sync command to verify server does not support to filter task when FilterType set to 6. syncRequest = TestSuiteBase.CreateEmptySyncRequest(this.User1Information.TasksCollectionId, 6); syncResponse = this.Sync(syncRequest); Site.Assert.IsNotNull(syncResponse.ResponseData, "The ResponseData should not be null."); Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R3059"); Site.CaptureRequirementIfAreNotEqual<string>( "1", syncResponse.ResponseData.Status, 3059, @"[In FilterType(Sync)] No, [Applies to tasks, if FilterType is 6, status is not 1.]"); #endregion #region Call Sync command to verify server does not support to filter task when FilterType set to 7. syncRequest = TestSuiteBase.CreateEmptySyncRequest(this.User1Information.TasksCollectionId, 7); syncResponse = this.Sync(syncRequest); Site.Assert.IsNotNull(syncResponse.ResponseData, "The ResponseData should not be null."); Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R3060"); Site.CaptureRequirementIfAreNotEqual<string>( "1", syncResponse.ResponseData.Status, 3060, @"[In FilterType(Sync)] No, [Applies to tasks, if FilterType is 7, status is not 1.]"); #endregion #region Call Sync command to verify server supports to filter task when FilterType set to 8. syncRequest = TestSuiteBase.CreateEmptySyncRequest(this.User1Information.TasksCollectionId, 8); syncResponse = this.Sync(syncRequest); Site.Assert.IsNotNull(syncResponse.ResponseData, "The ResponseData should not be null."); Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R3061"); Site.CaptureRequirementIfAreNotEqual<string>( "1", syncResponse.ResponseData.Status, 3061, @"[In FilterType(Sync)] Yes. [Applies to tasks, if FilterType is 8, Status element value is 1.]"); #endregion }
c#
16
0.637791
137
64.572816
103
/// <summary> /// This test case is used to verify if Sync command for Tasks, the status should be correspond to the value of FilterType. /// </summary>
function
internal sealed class TestingProcess { private bool Terminating; private readonly string Name = "CoyoteTestingProcess"; private readonly Configuration Configuration; private readonly TestingEngine TestingEngine; private SmartSocketClient Server; private ProgressLock ProgressTask; internal static TestingProcess Create(Configuration configuration) { return new TestingProcess(configuration); } public TestReport GetTestReport() { return this.TestingEngine.TestReport.Clone(); } private readonly TextWriter StdOut = Console.Out; internal int Run() { return this.RunAsync().Result; } internal async Task<int> RunAsync() { if (this.Configuration.RunAsParallelBugFindingTask) { await this.ConnectToServer(); this.StartProgressMonitorTask(); } this.TestingEngine.Run(); Console.SetOut(this.StdOut); this.Terminating = true; var task = this.ProgressTask; task?.Wait(30000); if (this.Configuration.RunAsParallelBugFindingTask) { if (this.TestingEngine.TestReport.InternalErrors.Count > 0) { Environment.ExitCode = (int)ExitCode.InternalError; } else if (this.TestingEngine.TestReport.NumOfFoundBugs > 0) { Environment.ExitCode = (int)ExitCode.BugFound; await this.NotifyBugFound(); } await this.SendTestReport(); } if (!this.Configuration.RunTestIterationsToCompletion && this.TestingEngine.TestReport.NumOfFoundBugs > 0 && !this.Configuration.RunAsParallelBugFindingTask) { Console.WriteLine($"... Task {this.Configuration.TestingProcessId} found a bug."); } await this.EmitReports(); if (this.Configuration.IsVerbose) { Console.WriteLine($"... ### Task {this.Configuration.TestingProcessId} is terminating"); } this.Disconnect(); return this.TestingEngine.TestReport.NumOfFoundBugs; } private TestingProcess(Configuration configuration) { this.Name = this.Name + "." + configuration.TestingProcessId; if (configuration.SchedulingStrategy is "portfolio") { TestingPortfolio.ConfigureStrategyForCurrentProcess(configuration); } if (configuration.RandomGeneratorSeed.HasValue) { configuration.RandomGeneratorSeed = configuration.RandomGeneratorSeed.Value + (673 * configuration.TestingProcessId); } configuration.EnableColoredConsoleOutput = true; this.Configuration = configuration; this.TestingEngine = TestingEngine.Create(this.Configuration); } ~TestingProcess() { this.Terminating = true; } / If this is not a parallel testing private async Task ConnectToServer() { string serviceName = this.Configuration.TestingSchedulerEndPoint; var source = new CancellationTokenSource(); var resolver = new SmartSocketTypeResolver(typeof(BugFoundMessage), typeof(TestReportMessage), typeof(TestServerMessage), typeof(TestProgressMessage), typeof(TestTraceMessage), typeof(TestReport), typeof(CoverageInfo), typeof(Configuration)); SmartSocketClient client = null; if (!string.IsNullOrEmpty(this.Configuration.TestingSchedulerIpAddress)) { string[] parts = this.Configuration.TestingSchedulerIpAddress.Split(':'); if (parts.Length is 2) { var endPoint = new IPEndPoint(IPAddress.Parse(parts[0]), int.Parse(parts[1])); while (!source.IsCancellationRequested && client is null) { client = await SmartSocketClient.ConnectAsync(endPoint, this.Name, resolver); } } } else { client = await SmartSocketClient.FindServerAsync(serviceName, this.Name, resolver, source.Token); } if (client is null) { throw new Exception("Failed to connect to server"); } client.Error += this.OnClientError; client.ServerName = serviceName; this.Server = client; await client.OpenBackChannel(this.OnBackChannelConnected); } private void OnBackChannelConnected(object sender, SmartSocketClient e) { Task.Run(() => this.HandleBackChannel(e)); } private async void HandleBackChannel(SmartSocketClient server) { while (!this.Terminating && server.IsConnected) { var msg = await server.ReceiveAsync(); if (msg is TestServerMessage) { this.HandleServerMessage((TestServerMessage)msg); } } } private void OnClientError(object sender, Exception e) { } / If this is not a parallel testing private void Disconnect() { using (this.Server) { if (this.Server != null) { this.Server.Close(); } } } private async Task NotifyBugFound() { await this.Server.SendReceiveAsync(new BugFoundMessage("BugFoundMessage", this.Name, this.Configuration.TestingProcessId)); } private async Task SendTestReport() { var report = this.TestingEngine.TestReport.Clone(); await this.Server.SendReceiveAsync(new TestReportMessage("TestReportMessage", this.Name, this.Configuration.TestingProcessId, report)); } private async Task EmitReports() { string file = Path.GetFileNameWithoutExtension(this.Configuration.AssemblyToBeAnalyzed); file += "_" + this.Configuration.TestingProcessId; CodeCoverageInstrumentation.SetOutputDirectory(this.Configuration, makeHistory: false); Console.WriteLine($"... Emitting task {this.Configuration.TestingProcessId} reports:"); var traces = new List<string>(this.TestingEngine.TryEmitReports(CodeCoverageInstrumentation.OutputDirectory, file)); if (this.Server != null && this.Server.IsConnected) { await this.SendTraces(traces); } } private async Task SendTraces(List<string> traces) { IPEndPoint localEndPoint = (IPEndPoint)this.Server.Socket.LocalEndPoint; IPEndPoint serverEndPoint = (IPEndPoint)this.Server.Socket.RemoteEndPoint; bool differentMachine = localEndPoint.Address.ToString() != serverEndPoint.Address.ToString(); foreach (var filename in traces) { string contents = null; if (differentMachine) { Console.WriteLine($"... Sending trace file: {filename}"); contents = File.ReadAllText(filename); } await this.Server.SendReceiveAsync(new TestTraceMessage("TestTraceMessage", this.Name, this.Configuration.TestingProcessId, filename, contents)); } } private async void StartProgressMonitorTask() { while (!this.Terminating) { await Task.Delay(100); using (this.ProgressTask = new ProgressLock()) { await this.SendProgressMessage(); } } } private async Task SendProgressMessage() { if (this.Server != null && !this.Terminating && this.Server.IsConnected) { double progress = 0.0; try { await this.Server.SendReceiveAsync(new TestProgressMessage("TestProgressMessage", this.Name, this.Configuration.TestingProcessId, progress)); } catch (Exception) { this.TestingEngine.Stop(); } } } private void HandleServerMessage(TestServerMessage tsr) { if (tsr.Stop) { if (this.Configuration.IsVerbose) { this.StdOut.WriteLine($"... ### Client {this.Configuration.TestingProcessId} is being told to stop!"); } this.TestingEngine.Stop(); this.Terminating = true; } } internal class ProgressLock : IDisposable { private bool Disposed; private bool WaitingOnProgress; private readonly object SyncObject = new object(); private readonly ManualResetEvent ProgressEvent = new ManualResetEvent(false); public ProgressLock() { } ~ProgressLock() { this.Dispose(); } public void Wait(int timeout = 10000) { bool wait = false; lock (this.SyncObject) { if (this.Disposed) { return; } this.WaitingOnProgress = true; wait = true; } if (wait) { this.ProgressEvent.WaitOne(timeout); } } public void Dispose() { lock (this.SyncObject) { this.Disposed = true; if (this.WaitingOnProgress) { this.ProgressEvent.Set(); } } GC.SuppressFinalize(this); } } }
c#
22
0.534231
161
38.674242
264
/// <summary> /// A testing process, this can also be the client side of a multi-process test. /// </summary>
class
public class JacksonMapper extends GenericMapper { /** * Instantiates a new {@link JacksonMapper} with a {@link JacksonFacade}. */ public JacksonMapper() { this(new JacksonFacade()); } /** * Instantiates a new {@link JacksonMapper} with a {@link JacksonFacade} * and register jackson {@link Module} specified by `modules`. * * @param modules jackson {@link Module} to register */ public JacksonMapper(Set<Module> modules) { this(new JacksonFacade(modules)); } /** * Instantiates a new {@link JacksonMapper} with a {@link MapperFacade}. * * @param mapperFacade the mapper facade */ public JacksonMapper(MapperFacade mapperFacade) { super(mapperFacade); } /** * Gets the underlying {@link ObjectMapper} instance to configure. * * @return the object mapper instance. */ public ObjectMapper getObjectMapper() { JacksonFacade jacksonFacade = (JacksonFacade) getMapperFacade(); return jacksonFacade.getObjectMapper(); } }
java
10
0.63586
77
27.5
38
/** * A jackson based {@link GenericMapper} implementation. It uses * {@link JacksonFacade} to convert an object into a * Nitrite {@link Document}. * * @author Anindya Chatterjee * @since 1.0 */
class
public void test51466_1() throws Exception { startVMs(1, 2); Connection conn = TestUtil.getConnection(); Statement st = conn.createStatement(); st.execute("create table test (col1 int, col2 int, col3 int) partition " + "by range (col1)(VALUES BETWEEN 0 AND 3, VALUES BETWEEN 3 AND 5)"); st.execute("create view test_v1 as select * from test"); st.execute("create view test_v2 as select * from test_v1"); st.execute("insert into test values(1,1,1), (2,2,2), (3,3,3), (4,4,4), (5,5,5)"); SerializableRunnable csr1 = new SerializableRunnable( "set observer") { @Override public void run() { GemFireXDQueryObserver old = GemFireXDQueryObserverHolder .setInstance(new GemFireXDQueryObserverAdapter() { private static final long serialVersionUID = 1L; @Override public void regionSizeOptimizationTriggered2( com.pivotal.gemfirexd.internal.impl.sql.compile.SelectNode selectNode) { if (selectNode.hasAggregatesInSelectList()) { getLogWriter().info( "csr1 regionSizeOptimizationTriggered2 called"); assertTrue(selectNode.convertCountToRegionSize()); } else { getLogWriter().info( "csr1 regionSizeOptimizationTriggered2 called...no aggregates " + "in the select"); } } }); } }; serverExecute(1, csr1); serverExecute(2, csr1); ResultSet rs = st.executeQuery("select count(*) from test_v1"); rs.next(); assertEquals(5, rs.getInt(1)); rs = st.executeQuery("select count(*) from test_v2"); rs.next(); assertEquals(5, rs.getInt(1)); rs = st.executeQuery("select count(*) from (select * from test) as t"); rs.next(); assertEquals(5, rs.getInt(1)); }
java
25
0.593132
90
42.704545
44
// make sure that region size optimization is applied for query on views
function
bool update_matIf(GAME *game, int swapArray[]) { if ((int)game->board[swapArray[3]][swapArray[4]] >= 65) { game->board[swapArray[0]][swapArray[1]] = game->board[swapArray[3]][swapArray[4]]; game->board[swapArray[3]][swapArray[4]] = ' '; return true; } return false; }
c
10
0.590759
90
37
8
/** * Function updating matrix for fixed position * @param game reference to the game object * @param swapArray determined index of arrays */
function
int Solution::knight(int A, int B, int C, int D, int E, int F) { vector<int> X = {1, 1, -1, -1,2, 2, -2, -2}; vector<int> Y = {2, -2, 2, -2, 1, -1, 1, -1}; vector<vector<int>> visited(A+2, vector<int>(B+2, 0)); queue<pair<int, pair<int, int>>> q; q.push({0,{C, D}}); visited[C][D] = 1; while(!q.empty()){ auto curr = q.front(); int moves = curr.first; int dx = curr.second.first; int dy = curr.second.second; q.pop(); if(dx == E and dy == F) return moves; for(int i = 0; i < 8; i++){ int x = dx + X[i]; int y = dy + Y[i]; if(x >= 1 and y >= 1 and x <= A and y <= B and !visited[x][y]){ visited[x][y] = 1; q.push({moves+1, {x, y}}); } } } return -1; }
c++
14
0.404378
76
32.423077
26
// Explanation 1: // The size of the chessboard is 8x8, the knight is initially at (1, 1) and the knight wants to reach position (8, 8). // The minimum number of moves required for this is 6.
function
def format_table(el): rows = el.findAll("tr") if not rows: return def format_one_row(row_el): return "&".join( format_el(child) for child in row_el.findAll(re.compile("t[dh]")) )+"\\\\" parts = ["\\begin{inlinetable}", "\\begin{tabular}{%s}"%("l"*len(rows[0].findAll(re.compile("t[dh]")))), "\\sptablerule"] parts.extend([ format_one_row(rows[0]), "\\sptablerule\n"]) for row in rows[1:]: parts.append(format_one_row(row)) parts.extend(["\\end{tabular}", "\\end{inlinetable}"]) return hack_table("\n".join(parts))
python
16
0.584642
75
29.210526
19
A formatter for (halfway sane) tables. This doesn't do nested tables or anything else not well behaved, and the resulting tables aren't terribly pretty. This also assumes that the first tr has the table headings. For non-trivial tables, you'll probably need to enable special handling using; let's see how to do it if we really get more tables.
function
private void authenticatedClientLogin(Context context,String authToken) { this.authToken = authToken; SharedPreferences settings = context.getSharedPreferences(PREF, 0); SharedPreferences.Editor editor = settings.edit(); editor.putString(PREF_AUTH_TOKEN, authToken); editor.commit(); Log.i(TAG,"Access Token stored in shared_preferences ->"+authToken); }
java
8
0.721519
74
48.5
8
/** * This method stores the access token and selected account in a shared preferences * file * @param context android App context * @param authToken access token for the requested acoount */
function
def cli( config, aws_access_key_id, aws_secret_access_key, aws_session_token, botocore_session, profile, region, debug): try: if debug: log.warning("Sensitive details may be in output") log.setLevel(logging.DEBUG) session_arguments = {} session_arguments.update( parse_args( { 'aws_access_key_id': aws_access_key_id, 'aws_secret_access_key': aws_secret_access_key, 'aws_session_token': aws_session_token, 'botocore_session': botocore_session, 'profile_name': profile, 'region_name': region})) log.debug("Boto session arguments : {}".format(session_arguments)) config.session = boto3.session.Session(**session_arguments) except Exception as e: log.exception('Error: {}'.format(e)) exit(1)
python
13
0.52077
74
34.285714
28
Creates the connection to AWS with the specified session arguments
function
func (r *Rollout) updateAnnotations(svc *run.Service, stable, candidate string) *run.Service { if r.shouldRollout { now := r.time.Now().Format(time.RFC3339) setAnnotation(svc, LastRolloutAnnotation, now) } if r.promoteToStable { setAnnotation(svc, StableRevisionAnnotation, candidate) delete(svc.Metadata.Annotations, CandidateRevisionAnnotation) return svc } setAnnotation(svc, StableRevisionAnnotation, stable) setAnnotation(svc, CandidateRevisionAnnotation, candidate) if r.shouldRollback { setAnnotation(svc, LastFailedCandidateRevisionAnnotation, candidate) } return svc }
go
12
0.792642
94
34.235294
17
// updateAnnotations updates the annotations to keep some state about the rollout.
function
def _get_single_subject_data(self, subject): file_path_list = self.data_path(subject) sessions = {} for file_path in sorted(file_path_list): session_name = "session_" + file_path.split(os.sep)[-2].replace("session", "") if session_name not in sessions.keys(): sessions[session_name] = {} run_name = "run_" + str(len(sessions[session_name]) + 1) sessions[session_name][run_name] = self._get_single_run_data(file_path) return sessions
python
14
0.583333
90
51.9
10
return data for a single subject
function
[GenerateObservableObject] public partial class StatusMessage : Control, IStatusMessageProps { public static readonly DependencyProperty SuccessMessageIconProperty = DependencyProperty.Register( "SuccessMessageIcon", typeof(Icon), typeof(StatusMessage), new PropertyMetadata(null)); public static readonly DependencyProperty FailureMessageIconProperty = DependencyProperty.Register( "FailureMessageIcon", typeof(Icon), typeof(StatusMessage), new PropertyMetadata(null)); public static readonly DependencyProperty WarningMessageIconProperty = DependencyProperty.Register( "WarningMessageIcon", typeof(Icon), typeof(StatusMessage), new PropertyMetadata(null)); public static readonly DependencyProperty InformationMessageIconProperty = DependencyProperty.Register( "InformationMessageIcon", typeof(Icon), typeof(StatusMessage), new PropertyMetadata(null)); public static readonly DependencyProperty SuccessMessageBrushProperty = DependencyProperty.Register( "SuccessMessageBrush", typeof(Brush), typeof(StatusMessage), new PropertyMetadata(new SolidColorBrush(Color.FromRgb(0, 192, 0)))); public static readonly DependencyProperty FailureMessageBrushProperty = DependencyProperty.Register( "FailureMessageBrush", typeof(Brush), typeof(StatusMessage), new PropertyMetadata(new SolidColorBrush(Color.FromRgb(192, 0, 0)))); public static readonly DependencyProperty WarningMessageBrushProperty = DependencyProperty.Register( "WarningMessageBrush", typeof(Brush), typeof(StatusMessage), new PropertyMetadata(new SolidColorBrush(Colors.Orange))); public static readonly DependencyProperty InformationMessageBrushProperty = DependencyProperty.Register( "InformationMessageBrush", typeof(Brush), typeof(StatusMessage), new PropertyMetadata(new SolidColorBrush(Color.FromRgb(0, 128, 255)))); public static readonly DependencyProperty StatusIconPaddingProperty = DependencyProperty.Register( "StatusIconPadding", typeof(Thickness), typeof(StatusMessage), new PropertyMetadata(new Thickness(8))); public static readonly DependencyProperty ServiceProperty = DependencyProperty.Register( "Service", typeof(IStatusMessageService), typeof(StatusMessage), new PropertyMetadata(null, OnServiceChanged)); private FrameworkElement? _rootElement; private Storyboard? _showMessageStoryboard; static StatusMessage() { DefaultStyleKeyProperty.OverrideMetadata(typeof(StatusMessage), new FrameworkPropertyMetadata(typeof(StatusMessage))); } public Icon SuccessMessageIcon { get => (Icon)GetValue(SuccessMessageIconProperty); set => SetValue(SuccessMessageIconProperty, value); } public Icon FailureMessageIcon { get => (Icon)GetValue(FailureMessageIconProperty); set => SetValue(FailureMessageIconProperty, value); } public Icon WarningMessageIcon { get => (Icon)GetValue(WarningMessageIconProperty); set => SetValue(WarningMessageIconProperty, value); } public Icon InformationMessageIcon { get => (Icon)GetValue(InformationMessageIconProperty); set => SetValue(InformationMessageIconProperty, value); } public Brush SuccessMessageBrush { get => (Brush)GetValue(SuccessMessageBrushProperty); set => SetValue(SuccessMessageBrushProperty, value); } public Brush FailureMessageBrush { get => (Brush)GetValue(FailureMessageBrushProperty); set => SetValue(FailureMessageBrushProperty, value); } public Brush WarningMessageBrush { get => (Brush)GetValue(WarningMessageBrushProperty); set => SetValue(WarningMessageBrushProperty, value); } public Brush InformationMessageBrush { get => (Brush)GetValue(InformationMessageBrushProperty); set => SetValue(InformationMessageBrushProperty, value); } public Thickness StatusIconPadding { get => (Thickness)GetValue(StatusIconPaddingProperty); set => SetValue(StatusIconPaddingProperty, value); } public IStatusMessageService Service { get => (IStatusMessageService)GetValue(ServiceProperty); set => SetValue(ServiceProperty, value); } public override void OnApplyTemplate() { base.OnApplyTemplate(); _rootElement = Guard.OfType<FrameworkElement>(GetTemplateChild("PART_Root"), "PART_Root"); _showMessageStoryboard = Guard.OfType<Storyboard>(_rootElement.Resources["ShowMessageStoryboard"], "ShowMessageStoryboard"); } protected void OnServiceChanged(IStatusMessageService? oldService, IStatusMessageService? newService) { if (oldService != null) oldService.StatusChanged -= OnStatusChanged; if (newService != null) newService.StatusChanged += OnStatusChanged; } private static void OnServiceChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e) { if (sender is StatusMessage sm) sm.OnServiceChanged(e.OldValue as IStatusMessageService, e.NewValue as IStatusMessageService); } private void OnStatusChanged(object sender, StatusChangedEventArgs e) { _showMessageStoryboard!.SkipToFill(); switch (e.Status) { case StatusType.None: (IsLoading, LoadingText, StatusIcon, StatusBrush, StatusText) = (false, null, null, null, null); break; case StatusType.Loading: (IsLoading, LoadingText, StatusIcon, StatusBrush, StatusText) = (true, e.Text, null, null, null); break; case StatusType.Information: (IsLoading, LoadingText, StatusIcon, StatusBrush, StatusText) = (false, null, InformationMessageIcon, InformationMessageBrush, e.Text); _showMessageStoryboard.Begin(); break; case StatusType.Success: (IsLoading, LoadingText, StatusIcon, StatusBrush, StatusText) = (false, null, SuccessMessageIcon, SuccessMessageBrush, e.Text); _showMessageStoryboard.Begin(); break; case StatusType.Warning: (IsLoading, LoadingText, StatusIcon, StatusBrush, StatusText) = (false, null, WarningMessageIcon, WarningMessageBrush, e.Text); _showMessageStoryboard.Begin(); break; case StatusType.Error: (IsLoading, LoadingText, StatusIcon, StatusBrush, StatusText) = (false, null, FailureMessageIcon, FailureMessageBrush, e.Text); _showMessageStoryboard.Begin(); break; default: throw new ArgumentOutOfRangeException($"The status \"{e.Status}\" is unknown."); } } }
c#
19
0.60565
155
46.136095
169
/// <summary> /// Control that displays status messages. /// </summary> /// <seealso cref="Control" />
class
public sealed class DelegateComparer<T> : IComparer<T> { private readonly Comparison<T> _delegate; public DelegateComparer(Comparison<T> comparison) { if (comparison == null) throw new ArgumentNullException("comparison"); _delegate = comparison; } public int Compare(T x, T y) { return _delegate(x, y); } }
c#
11
0.631868
54
25.071429
14
/// <summary> /// Compares two items using a user-defined <see cref="Comparison{T}"/> delegate. (Note: In .NET /// 4.5 or higher use <strong>Comparer&lt;T&gt;.Create()</strong> instead of this class.) /// </summary> /// <typeparam name="T">The type of objects to compare</typeparam>
class
def renderMovie(self): ALL = '*' cleaningString = 'rm %s'%os.path.join(os.getcwd(),self.frameDirectory,ALL) os.system(cleaningString) cmdString = 'cd {0} && mencoder -noskip mf://*.png -mf fps={1}:type=png -ovc lavc -lavcopts vcodec=mpeg4 -o ../output.avi'.format(self.frameDirectory, self.fps) os.system(cmdString) convertString = 'ffmpeg -i ./output.avi -acodec libfaac -b:a 128k -vcodec mpeg4 -b:v 1200k -flags +aic+mv4 ./output.mp4' os.system(convertString)
python
10
0.646035
168
63.75
8
Render the movie with mencoder.
function
func (b *Block) Append(id uint32, val uint32) { if id > BLOCK_IDX_MASK { panic(fmt.Sprintf("ID value %d is too large for this block, max is %d.", id, BLOCK_IDX_MASK)) } if val > BLOCK_VAL_MASK { panic(fmt.Sprintf("Val value %d is too large for this block, max is %d.", val, BLOCK_VAL_MASK)) } if b.Frozen { panic("Attempt to append to a frozen Block, which is not allowed.") } if b.Length > BLOCK_FULL_LENGTH { if id >= b.Length { panic(fmt.Sprintf("Unable to push %d into array-mode block of size %d.", id, b.Length)) } writePacked(b.Values, id, val) } else if b.Length < BLOCK_FULL_LENGTH { b.Values[b.Length] = (id << BLOCK_VAL_BITS) | val b.Length += 1 } else { var tmp [BLOCK_FULL_LENGTH]uint32 for _, kv := range b.Values { k := kv >> BLOCK_VAL_BITS v := kv & BLOCK_VAL_MASK writePacked(tmp[:], k, v) } writePacked(tmp[:], id, val) copy(b.Values, tmp[:]) b.Length = 1 << BLOCK_IDX_BITS } }
go
13
0.626455
97
30.533333
30
// Append an (id, val) pair onto the end of the block. The id must be unique, // and greater than any other id appended to this block before. The val must fit // into the values allowed in this block (i.e: BLOCK_VAL_BITS bits).
function
func InitDB(dataSourceName string) { dbConn, err := sql.Open("postgres", dataSourceName) if err != nil { log.Panicw("could not connect to DB", zap.Error(err)) } db = dbConn if err := db.Ping(); err != nil { log.Panicw("could not ping DB", zap.Error(err)) } log.Debug("connected to DB") driver := darwin.NewGenericDriver(db, darwin.PostgresDialect{}) d := darwin.New(driver, migrations, nil) if err := d.Migrate(); err != nil { log.Panicw("could not migrate database", zap.Error(err)) } log.Info("database migration complete") }
go
10
0.677064
64
31.117647
17
// InitDB creates the database and migrates it to the correct version.
function
function pauseDecorator( settings ) { return function( base ){ var self = this; this.on( constants.events.STATED, function( event, Component ){ event.stopPropagation(); if( Component.hasState( constants.states.PAUSED ) ){ self.disable(); } if( Component.hasState( constants.states.PLAYING ) ){ self.enable(); } } ); }; }
javascript
17
0.602094
67
26.357143
14
/** * Decorates the Button to listen for the 'stated' event and * to disable itself if the control is paused. This is used in * conjunction with the default decorator. * @method pause * @private */
function
func (k *Kyber) Decrypt(packedSK, c []byte) []byte { if len(c) != k.SIZEC() || len(packedSK) != k.SIZEPKESK() { println("Cannot decrypt, inputs do not have correct size.") return nil } sk := k.UnpackPKESK(packedSK) K := k.params.K uhat := decompressVec(c[:K*k.params.DU*n/8], k.params.DU, K) uhat.ntt(K) v := decompressPoly(c[K*k.params.DU*n/8:], k.params.DV) v.ntt() m := vecPointWise(sk.S, uhat, K) m.toMont() m = sub(v, m) m.invntt() m.reduce() m.fromMont() return polyToMsg(m) }
go
13
0.628743
61
25.421053
19
//Decrypt decrypts a ciphertext given a secret key. //The secret key and ciphertext must be give as packed byte array. //The recovered message is returned as byte array. //If an error occurs durirng the decryption process (wrong key format for example), a nil message is returned.
function
public final class Listeners<T> implements Iterable<T> { private final Set<T> mListeners = new LinkedHashSet<>(); private final Set<T> mListenersToAdd = new LinkedHashSet<>(); private final Set<T> mListenersToRemove = new LinkedHashSet<>(); private boolean mIterating; @Override public @NonNull Iterator<T> iterator() { if (mIterating) throw new RuntimeException("finishIterate() must be called before new iteration"); mIterating = true; return mListeners.iterator(); } /** * Completes listeners iteration. Must be called after iteration is done. */ public void finishIterate() { if (!mListenersToRemove.isEmpty()) mListeners.removeAll(mListenersToRemove); if (!mListenersToAdd.isEmpty()) mListeners.addAll(mListenersToAdd); mListenersToAdd.clear(); mListenersToRemove.clear(); mIterating = false; } /** * Safely registers new listener. If registered during iteration, new listener will NOT be called before current iteration is complete. */ public void register(T listener) { if (mIterating) { mListenersToRemove.remove(listener); if (!mListeners.contains(listener)) mListenersToAdd.add(listener); } else mListeners.add(listener); } /** * Safely unregisters listener. If unregistered during iteration, old listener WILL be called in the current iteration. */ public void unregister(T listener) { if (mIterating) { mListenersToAdd.remove(listener); if (mListeners.contains(listener)) mListenersToRemove.add(listener); } else mListeners.remove(listener); } public int getSize() { int res = mListeners.size(); if (mIterating) { res += mListenersToAdd.size(); res -= mListenersToRemove.size(); } return res; } public boolean isEmpty() { return (getSize() <= 0); } }
java
12
0.66597
137
22.62963
81
/** * `Registrator` pattern implementation which allows to maintain the list of listeners, * offers safe adding/removing of listeners during iteration. * <br/>{@link #finishIterate()} must be called after iteration is complete. */
class
private static void LogTrace(string format, params object[] args) { System.Reflection.Assembly a = System.Reflection.Assembly.GetExecutingAssembly(); string output_msg = string.Format("DLL {0} compiled on {1}; {2}", System.IO.Path.GetFileName(a.Location), File.GetLastWriteTime(a.Location), string.Format(format, args)); IGlobal globalInterface = Autodesk.Max.GlobalInterface.Instance; IInterface14 coreInterface = globalInterface.COREInterface14; ILogSys log = coreInterface.Log; log.LogEntry(0x00000004 | 0x00040000 | 0x00010000, false, "", output_msg); }
c#
15
0.634006
93
56.916667
12
/// <summary> /// Information sent to this LogTrace will appear on the Design Automation output /// </summary>
function
public class PieChartViewHolder extends MessageViewHolder { @BindView(R.id.background_layout) public LinearLayout backgroundLayout; @BindView(R.id.text) public TextView chatTextView; @BindView(R.id.piechart) public PieChart pieChart; @BindView(R.id.timestamp) public TextView timeStamp; /** * Instantiates a new Pie chart view holder. * * @param view the view * @param listener the listener */ public PieChartViewHolder(View view, ClickListener listener) { super(view, listener); ButterKnife.bind(this, itemView); } /** * Inflate PieChart * * @param model the ChatMessage object */ public void setView(ChatMessage model) { if (model != null) { try { chatTextView.setText(model.getContent()); timeStamp.setText(model.getTimeStamp()); pieChart.setUsePercentValues(true); pieChart.setDrawHoleEnabled(true); pieChart.setHoleRadius(7); pieChart.setTransparentCircleRadius(10); pieChart.setRotationEnabled(true); pieChart.setRotationAngle(0); pieChart.setDragDecelerationFrictionCoef(0.001f); pieChart.getLegend().setEnabled(false); pieChart.setDescription(""); RealmList<Datum> datumList = model.getDatumRealmList(); final ArrayList<Entry> yVals = new ArrayList<>(); final ArrayList<String> xVals = new ArrayList<>(); for (int i = 0; i < datumList.size(); i++) { yVals.add(new Entry(datumList.get(i).getPercent(), i)); xVals.add(datumList.get(i).getPresident()); } pieChart.setClickable(false); pieChart.setHighlightPerTapEnabled(false); PieDataSet dataSet = new PieDataSet(yVals, ""); dataSet.setSliceSpace(3); dataSet.setSelectionShift(5); ArrayList<Integer> colors = new ArrayList<>(); for (int c : ColorTemplate.VORDIPLOM_COLORS) colors.add(c); for (int c : ColorTemplate.JOYFUL_COLORS) colors.add(c); for (int c : ColorTemplate.COLORFUL_COLORS) colors.add(c); for (int c : ColorTemplate.LIBERTY_COLORS) colors.add(c); for (int c : ColorTemplate.PASTEL_COLORS) colors.add(c); dataSet.setColors(colors); PieData data = new PieData(xVals, dataSet); data.setValueFormatter(new PercentFormatter()); data.setValueTextSize(11f); data.setValueTextColor(Color.GRAY); pieChart.setData(data); pieChart.highlightValues(null); pieChart.invalidate(); } catch (Exception e) { e.printStackTrace(); } } } }
java
19
0.548994
75
38.025316
79
/** * <h1>Pie chart view holder</h1> */
class
public void line(final Vector3d start, final Vector3d end) { final Vector2d s = shade(start); if (s == null) return; final Vector2d e = shade(end); if (e == null) return; g.drawLine(s.getX(), s.getY(), e.getX(), e.getY()); }
java
8
0.618257
60
25.888889
9
/** * shades the vertices and draws a line from one of these pixels to the * other <br> * works like drawing a 3d-line * * @param start * one of the two vertices * @param end * the other vertex */
function
func New(Path string, NameRegexp *regexp.Regexp, Recur bool, Poll bool) *Watcher { return &Watcher{ Path: Path, Recur: Recur, NameRegexp: NameRegexp, Poll: Poll, } }
go
10
0.635417
82
23.125
8
// New creates a new filesystem log source
function
def spin_once(self): count = 0 last_err = '' while not rospy.is_shutdown() and count < self.retry_limit: try: if rospy.is_shutdown(): break self.send_speed_to_motor(float(self.left), float(self.right)) rospy.loginfo_throttle(1, "Sent speed successfully") break except IOError as e: count += 1 last_err = str(e) pass if count > 0: self.err_count += count rospy.logwarn("Failed to send speed %d times or %d total: %s" % (count, self.err_count, last_err)) if count == self.retry_limit: self.reset_arduino()
python
13
0.488435
110
37.736842
19
Sends the speeds to the motor once and retries if it fails
function
func ListAllTags(q Queryable, sortByName bool) (tags []string, err error) { var query string if sortByName { query = "SELECT DISTINCT tag.tag FROM tag ORDER BY tag.tag ASC" } else { query = "SELECT DISTINCT tag.tag FROM tag" } rows, err := q.Query(query) if err != nil { return nil, err } defer rows.Close() return readTags(rows) }
go
8
0.684971
75
23.785714
14
// ListAllTags returns a list (without duplicates) of all tags that appear in // the database. If the 'sortByName' parameter is true, the tags are sorted into // alphabetical order.
function
public class ShareCardContactAdapter extends BaseAdapter { private ArrayList<ContactBean> listData = new ArrayList<>(); private int startPosition; private ContactListManage contactManage = new ContactListManage(); @Override public int getCount() { return listData.size(); } @Override public Object getItem(int position) { return listData.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_contactcard, parent, false); holder = new ViewHolder(convertView); convertView.setTag(holder); } else { holder = (ViewHolder)convertView.getTag(); } ContactBean contactBean = listData.get(position); ContactBean lastBean = position == 0 ? null : listData.get(position-1); String letter = contactManage.checkShowFriendTop(contactBean,lastBean); if(TextUtils.isEmpty(letter)){ holder.txt.setVisibility(View.GONE); }else{ holder.txt.setVisibility(View.VISIBLE); switch (contactBean.getStatus()){ case 2: Drawable draGroup = parent.getContext().getResources().getDrawable(R.mipmap.contract_group_chat3x); draGroup.setBounds(0, 0, draGroup.getMinimumWidth(), draGroup.getMinimumHeight()); holder.txt.setCompoundDrawables(draGroup,null,null,null); holder.txt.setText(R.string.Link_Group); break; case 3: Drawable draFavorite = parent.getContext().getResources().getDrawable(R.mipmap.contract_favorite13x); draFavorite.setBounds(0, 0, draFavorite.getMinimumWidth(), draFavorite.getMinimumHeight()); holder.txt.setCompoundDrawables(draFavorite,null,null,null); holder.txt.setText(R.string.Link_Favorite_Friend); break; case 4: holder.txt.setCompoundDrawables(null,null,null,null); holder.txt.setText(letter); break; default: break; } } GlideUtil.loadAvater(holder.roundimg,contactBean.getAvatar()); holder.name.setText(contactBean.getName()); return convertView; } public int getPositionForSection(char selectchar) { if(listData.size() - startPosition == 0) return -1; for (int i = startPosition; i < listData.size(); i++) { ContactBean entity = listData.get(i); String showName = entity.getName(); String firstChar = PinyinUtil.chatToPinyin(showName.charAt(0)); if (firstChar.charAt(0) == selectchar) { return i; } } return -1; } public void setStartPosition(int count) { this.startPosition = count; } public void setDataNotify(List<ContactBean> list) { listData.clear(); listData.addAll(list); notifyDataSetChanged(); } static class ViewHolder { @Bind(R.id.txt) TextView txt; @Bind(R.id.roundimg) RoundedImageView roundimg; @Bind(R.id.tvName) TextView name; ViewHolder(View view) { ButterKnife.bind(this, view); } } }
java
16
0.587459
121
34.656863
102
/** * Created by Administrator on 2017/2/20. */
class
public final class IpV4SecurityOptionHandlingRestrictions extends NamedNumber<Short, IpV4SecurityOptionHandlingRestrictions> { /** */ private static final long serialVersionUID = 3041825811304706489L; private static final Map<Short, IpV4SecurityOptionHandlingRestrictions> registry = new HashMap<Short, IpV4SecurityOptionHandlingRestrictions>(); static { } /** * @param value value * @param name name */ public IpV4SecurityOptionHandlingRestrictions(Short value, String name) { super(value, name); } /** * @param value value * @return a IpV4SecurityOptionHandlingRestrictions object. */ public static IpV4SecurityOptionHandlingRestrictions getInstance(Short value) { if (registry.containsKey(value)) { return registry.get(value); } else { return new IpV4SecurityOptionHandlingRestrictions(value, "unknown"); } } /** * @param number number * @return a IpV4SecurityOptionHandlingRestrictions object. */ public static IpV4SecurityOptionHandlingRestrictions register( IpV4SecurityOptionHandlingRestrictions number) { return registry.put(number.value(), number); } @Override public String valueAsString() { return "0x" + ByteArrays.toHexString(value(), ""); } @Override public int compareTo(IpV4SecurityOptionHandlingRestrictions o) { return value().compareTo(o.value()); } }
java
11
0.728051
84
26.490196
51
/** * Handling Restrictions of IPv4 Security Option * * @see <a href="https://tools.ietf.org/html/rfc791">RFC 791</a> * @author Kaito Yamada * @since pcap4j 0.9.11 */
class
class RemoveElement { public static void main(String[] args) { RemoveElement r = new RemoveElement(); // int[] A = { 1 }; // int[] A = { 1, 2, 3, 4 }; int[] A = { 1, 2, 1 }; int elem = 1; System.out.println(r.removeElement(A, elem)); } /** * Order is not important * Just move the last elem to removed position */ public int removeElement(int[] A, int elem) { if (A == null || A.length == 0) return 0; int i = 0; int j = A.length; while (i < j) { if (A[i] == elem) { A[i] = A[j - 1]; // move last element j--; // decrease length } else i++; // move on } return j; } }
java
13
0.44137
53
27.148148
27
/** * Given an array and a value, remove all instances of that value in place and * return the new length. * * The order of elements can be changed. It doesn't matter what you leave * beyond the new length. * * Tags: Array, Two pointers */
class
async def async_get_events( self, hass: HomeAssistant, start_date: datetime, end_date: datetime ) -> list[dict[str, Any]]: event_list: list[dict[str, Any]] = [] page_token: str | None = None while True: try: items, page_token = await self._calendar_service.async_list_events( self._calendar_id, start_time=start_date, end_time=end_date, search=self._search, page_token=page_token, ) except ServerNotFoundError as err: _LOGGER.error("Unable to connect to Google: %s", err) return [] event_list.extend(filter(self._event_filter, items)) if not page_token: break return event_list
python
14
0.501767
83
39.47619
21
Get all events in a specific time frame.
function
public class Log4j2ThreadContextSnapshot { private final Map<String, String> contextMap; private final ThreadContext.ContextStack contextStack; private Log4j2ThreadContextSnapshot(Map<String, String> contextMap, ThreadContext.ContextStack contextStack) { this.contextMap = contextMap; this.contextStack = contextStack; } /** * Captures a snapshot of the {@code ThreadContext} data from the current thread. * * @return Log4j 2 {@code ThreadContext} snapshot from the current thread. */ public static Log4j2ThreadContextSnapshot captureFromCurrentThread() { // Get a copy of context map and context stack return new Log4j2ThreadContextSnapshot(ThreadContext.getImmutableContext(), ThreadContext.getImmutableStack()); } /** * Apply the Log4j 2 {@code ThreadContext} snapshot data to the current thread. * <p> * This method does <strong>not</strong> clear the current {@code ThreadContext} values before applying * this context. If you want that to happen, please call {@link ThreadContext#clearAll()} before applying * the snapshot. * * @see ThreadContext#clearAll() */ public void applyToCurrentThread() { ThreadContext.putAll(this.contextMap); for (String element : this.contextStack) { ThreadContext.push(element); } } /** * Returns an unmodifiable view of the {@code ThreadContext} map contained in this snapshot. * * @return {@code ThreadContext} map contained in this snapshot */ public Map<String, String> getContextMap() { return contextMap; } /** * Returns an unmodifiable view of the {@code ThreadContext} stack contained * in this snapshot. * * @return {@code ThreadContext} stack contained in this snapshot */ public ThreadContext.ContextStack getContextStack() { return contextStack; } @Override public String toString() { return getClass().getSimpleName() + "{contextMap=" + contextMap + ", contextStack=" + contextStack + '}'; } }
java
14
0.662796
119
34.311475
61
/** * Snapshot of the data from the Log4j 2 {@link ThreadContext} of a specific thread at a certain point in the past. */
class
void IPTestClient::testEIN( CIMClient &client, CIMName className, Boolean verbose) { try { Boolean deepInheritance = true; Boolean localOnly = true; Boolean includeQualifiers = false; Boolean includeClassOrigin = false; _testLog("IPTestClient: Starting EI for class " + className.getString()); Array<CIMInstance> cimNInstances = client.enumerateInstances(NAMESPACE, className, deepInheritance, localOnly, includeQualifiers, includeClassOrigin); Uint32 numberInstances = cimNInstances.size(); if (verbose) { cout << numberInstances << " instance(s) of " << className.getString() << endl; } for (Uint32 i = 0; i < numberInstances; i++) { CIMObjectPath instanceRef = cimNInstances[i].getPath (); if (verbose) cout<<"Instance ClassName is " << instanceRef.getClassName().getString() << endl; if( !(instanceRef.getClassName().equal( className.getString() ) ) ) { _errorExit("EnumInstances failed"); } _validateProperties(cimNInstances[i], className, verbose); } _testLog("IPTestClient: EI Passed for class " + className.getString()); } catch(Exception& e) { _errorExit(e.getMessage()); } }
c++
15
0.555328
79
33.069767
43
// // testEnumerateInstances of the IP provider. //
function
def main() -> Sequence[DataSourceStatus]: canvas_env = ENV.get('CANVAS', {}) lti_processor = CanvasLtiPlacementProcessor( canvas_env.get("CANVAS_URL"), canvas_env.get("CANVAS_TOKEN")) lti_processor.generate_lti_course_report( canvas_env.get("CANVAS_ACCOUNT_ID", 1), canvas_env.get("CANVAS_TERM_IDS", []), canvas_env.get("ADD_COURSE_IDS", []), True) lti_processor.output_report() return [DataSourceStatus(ValidDataSourceName.CANVAS_LTI)]
python
10
0.644841
61
41.083333
12
This method is invoked when its module is executed as a standalone program.
function
def diff_strings(a, b): in_a_not_in_b = [] in_b_not_in_a = [] json_a = json.loads(a) json_b = json.loads(b) if json_a == json_b: pass else: a_list = parse_json_path(json_a) b_list = parse_json_path(json_b) pop_list = b_list[:] for item in a_list: if item not in pop_list: in_a_not_in_b.append(item) else: pop_list.remove(item) pop_list = a_list[:] for item in b_list: if item not in pop_list: in_b_not_in_a.append(item) else: pop_list.remove(item) return in_a_not_in_b, in_b_not_in_a
python
14
0.474227
42
28.565217
23
Takes two "custom JSONPath" strings and returns two lists of strings, enumerating the things in list a that are not in list b, and vice versa.
function
public sealed class ProcessAdapter : GrAdapterProxyBase<IProcess> { protected override string AdapterName => nameof(ProcessAdapter); public ProcessAdapter() : base(() => new ProcessService()) { } public System.Diagnostics.Process Start(string process, string args) { return CreateProxy().Start(process, args); } }
c#
10
0.624679
76
34.454545
11
/// <summary> /// Adapter for <see cref="IProcess"/>. /// </summary>
class
private void OnSynchronizeElevationAngle(object sender, SynchronizeElevationAngleEventArgs e) { if (m_refKinectsensor != null) { try { m_refKinectsensor.ElevationAngle = e.Elevation; } catch (InvalidOperationException ex) { DisplayDebugLog("Exception Elevation angle", true); throw new KinectException(ex.Message); } } }
c#
14
0.484848
93
34.266667
15
/// <summary> /// Callback when the elevation of kinect sensor is modified in PropertiesKinect /// </summary> /// <param name="sender"></param> /// <param name="e"></param>
function
private class ClickEventReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (MEDIACENTER_CANCEL_NOTIFICATION.equals(action)) { Log.i("TAG", "onReceive----->cancelNotification"); mHwAudioPlayerManager.stop(); } } }
java
11
0.591479
66
39
10
// Receives intents when closing from notification bar
class
int l2_cpu_learning_with_vlan(int unit, int port) { int rv; bcm_l2_learn_msgs_config_t learn_msgs; bcm_l2_addr_distribute_t distribution; int age_seconds; bcm_l2_addr_t l2addr_1, l2addr_2; l2_learning_info_init(unit, port); rv = vlan__init_vlan(unit, l2_learning_info.vlan_1); if (rv != BCM_E_NONE) { printf("Error, in vlan__init_vlan with vlan#1 %d\n", l2_learning_info.vlan_1); print rv; return rv; } rv = l2_addr_add(unit, &l2addr_1, _dest_mac_1, l2_learning_info.out_port , l2_learning_info.vlan_1); if (BCM_FAILURE(rv)) { printf("Error, in l2_addr_add#1\n"); return rv; } bcm_l2_learn_msgs_config_t_init(&learn_msgs); learn_msgs.flags = BCM_L2_LEARN_MSG_SHADOW; learn_msgs.dest_port = l2_learning_info.cpu_port; learn_msgs.flags |= BCM_L2_LEARN_MSG_ETH_ENCAP; learn_msgs.ether_type = 0xab00; learn_msgs.tpid = 0x8100; learn_msgs.vlan = l2_learning_info.vlan_1; sal_memcpy(learn_msgs.src_mac_addr, _src_mac_address, 6); sal_memcpy(learn_msgs.dst_mac_addr, _dest_mac_address, 6); rv = bcm_l2_learn_msgs_config_set(unit, &learn_msgs); if (rv != BCM_E_NONE) { printf("Error, bcm_l2_learn_msgs_config_set \n"); return rv; } rv = bcm_switch_control_set(unit, bcmSwitchL2LearnMode, BCM_L2_INGRESS_CENT); if (rv != BCM_E_NONE) { print rv; printf("Error, bcm_switch_control_set \n"); return rv; } distribution.vid = l2_learning_info.vlan_1; distribution.flags = BCM_L2_ADDR_DIST_LEARN_EVENT | BCM_L2_ADDR_DIST_STATION_MOVE_EVENT | BCM_L2_ADDR_DIST_AGED_OUT_EVENT | BCM_L2_ADDR_DIST_SET_SHADOW_DISTRIBUTER; rv = bcm_l2_addr_msg_distribute_set(unit, &distribution); if (rv != BCM_E_NONE) { print rv; printf("Error, bcm_l2_addr_msg_distribute_set \n"); return rv; } return BCM_E_NONE; }
c
9
0.615741
127
37.9
50
/* Configure the DSP messages with vlan in the ethernet header */
function
public static class GuessBean { private char c; private Visit v; public GuessBean(char c, Visit v) { this.c = c; this.v = v; } public String getLetter() { return String.valueOf(c); } public String makeGuess() { return v.makeGuess(c); } }
java
8
0.602151
36
15.470588
17
/** * Added for the JSF version. A bean that holds a letter and an * action method for guessing the letter. */
class
public class ConnectionBase { private volatile bool _gotPong; private readonly VolatileVar<string> _handle = new VolatileVar<string>(); private volatile byte _lastPing; private volatile int _numberOfMissedPongs; private readonly UdpServerBase _parent; private readonly VolatileVar<DateTime?> _pingTime = new VolatileVar<DateTime?>(); private readonly VolatileVar<DateTime?> _pongTime = new VolatileVar<DateTime?>(); public ConnectionBase(IPEndPoint endpoint, UdpServerBase parent) { Handle = string.Empty; GotPong = false; PingTime = null; PongTime = null; LastPing = 0; EndPoint = endpoint; _parent = parent; } internal IPEndPoint EndPoint { get; } public bool GotPong { get { return _gotPong; } internal set { _gotPong = value; } } public string Handle { get { return _handle.Get(); } set { _handle.Set(value); } } public byte LastPing { get { return _lastPing; } internal set { _lastPing = value; } } public int NumberOfMissedPongs { get { return _numberOfMissedPongs; } internal set { _numberOfMissedPongs = value; } } public UdpServerBase Parent => _parent; public DateTime? PingTime { get { return _pingTime.Get(); } internal set { _pingTime.Set(value); } } public DateTime? PongTime { get { return _pongTime.Get(); } internal set { _pongTime.Set(value); } } public void SendData(DatagramBase datagram) { if (!OnBeforeSendData(datagram)) return; try { Parent.Send(datagram.Pack().Data, EndPoint); } catch (Exception) { Parent.RemoveClient(this); } OnAfterSendData(datagram); } internal void SendPing() { GotPong = false; PingTime = DateTime.Now; PongTime = null; if (LastPing < byte.MaxValue - 1) LastPing++; else LastPing = 0; PingPong data = new PingPong {ChkVal = LastPing}; SendData(data); } #region Virtual Functions public virtual void OnAfterSendData(DatagramBase datagram) { } public virtual bool OnBeforeSendData(DatagramBase datagram) { return true; } #endregion }
c#
14
0.513504
89
30.505747
87
/// <summary> /// The base class for all client Udp Socket Connections to the server. /// This class tracks connection information /// </summary>
class
public class Workflow implements AutoCloseable { private static final Logger logger = LoggerFactory.getLogger(Workflow.class); public static final String IN = "in"; public static final String OUT = "out"; Map<String, ModelInfo> models; Map<String, WorkflowExpression> expressions; /** * Constructs a workflow containing only a single model. * * @param model the model for the workflow */ public Workflow(ModelInfo model) { String modelName = "model"; models = Collections.singletonMap(modelName, model); expressions = Collections.singletonMap( OUT, new WorkflowExpression(modelName, Collections.singletonList(IN))); } /** * Constructs a workflow. * * @param models a map of executableNames for a model (how it is referred to in the {@link * WorkflowExpression}s to model * @param expressions a map of names to refer to an expression to the expression */ public Workflow(Map<String, ModelInfo> models, Map<String, WorkflowExpression> expressions) { this.models = models; this.expressions = expressions; } /** * Returns the models used in the workflow. * * @return the models used in the workflow */ public Collection<ModelInfo> getModels() { return models.values(); } /** * Executes a workflow with an input. * * @param wlm the wlm to run the workflow with * @param input the input * @return a future of the result of the execution */ public CompletableFuture<Output> execute(WorkLoadManager wlm, Input input) { logger.debug("Beginning execution of workflow"); // Construct variable map to contain each expression and the input Map<String, CompletableFuture<Input>> vars = new ConcurrentHashMap<>(expressions.size() + 1); vars.put(IN, CompletableFuture.completedFuture(input)); return execute(wlm, OUT, vars, new HashSet<>()).thenApply(i -> (Output) i); } @SuppressWarnings("unchecked") private CompletableFuture<Input> execute( WorkLoadManager wlm, String target, Map<String, CompletableFuture<Input>> vars, Set<String> targetStack) { if (vars.containsKey(target)) { return vars.get(target).thenApply(i -> i); } // Use targetStack, the set of targets in the "call stack" to detect cycles if (targetStack.contains(target)) { // If a target is executed but already in the stack, there must be a cycle throw new IllegalStateException( "Your workflow contains a cycle with target: " + target); } targetStack.add(target); WorkflowExpression expr = expressions.get(target); if (expr == null) { throw new IllegalArgumentException( "Expected to find variable but it is not defined: " + target); } ModelInfo model = models.get(expr.getExecutableName()); if (model == null) { throw new IllegalArgumentException( "Expected to find model but it is not defined: " + target); } CompletableFuture<Input>[] processedArgs = expr.getArgs() .stream() .map(arg -> execute(wlm, arg, vars, targetStack)) .toArray(CompletableFuture[]::new); if (processedArgs.length != 1) { throw new IllegalArgumentException( "In the definition for " + target + ", the model " + expr.getExecutableName() + " should have one arg, but has " + processedArgs.length); } return CompletableFuture.allOf(processedArgs) .thenApply( v -> { CompletableFuture<Output> result = wlm.runJob(new Job(model, processedArgs[0].join())); vars.put(target, result.thenApply(o -> o)); result.thenAccept( r -> { targetStack.remove(target); logger.debug( "Workflow computed target " + target + " with value:\n" + r.toString()); }); return result.join(); }); } /** {@inheritDoc} * */ @Override public void close() { for (ModelInfo m : getModels()) { m.close(); } } }
java
22
0.5193
97
36.514925
134
/** A flow of executing {@link ai.djl.Model}s. */
class
final class LineInfo { private final int startIndex; private final int endIndex; LineInfo(int pStartIndex, int pEndIndex) { startIndex = pStartIndex; endIndex = pEndIndex; } public int getStartIndex() { return startIndex; } public int getEndIndex() { return endIndex; } }
java
7
0.670927
42
13.272727
22
/** * Pair of two integers for the first and last index of a line */
class
function stopConfigs() { var deferred = Q.defer(); viewModel.statusMessage("stopping File Export configs"); listPromisesRequests = []; for( var i = 0; i < configsCreatedFileExportModules.length; i++ ) { configID = configsCreatedFileExportModules[i].id; var url; if (listConfigsPreStatus[i] == 'running') url = viewModel.hostUrl() + "FileExport/" + configID + "/control/stopThis"; else url = viewModel.hostUrl() + "FileExport/" + configID + "/control/stop"; listPromisesRequests.push(createDeferAjaxGetRequest(url)); } Q.all(listPromisesRequests) .then(function () { deferred.resolve(); }) .fail(function (error) { deferred.reject(new Error("Error occurred: " + error)); }) .done(); return deferred.promise; }
javascript
17
0.691176
79
31.565217
23
/** * this function creates a promise that will stop all file export configs (dependend of the config's chained module pre status) * @returns the promise used to perform the task */
function
public class HttpRequest { private final ClientLogger logger = new ClientLogger(HttpRequest.class); private HttpMethod httpMethod; private URL url; private HttpHeaders headers; private byte[] body; private Map<Object, Object> tags; /** * Create a new HttpRequest instance. * * @param httpMethod The HTTP request method. * @param url The target address to send the request to. * @throws IllegalArgumentException if the url is malformed. */ public HttpRequest(HttpMethod httpMethod, String url) { this.httpMethod = Util.requireNonNull(httpMethod, "'httpMethod' is required."); Util.requireNonNull(url, "'url' is required."); try { this.url = new URL(url); } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning(new IllegalArgumentException("'url' must be a valid URL", ex)); } this.headers = new HttpHeaders(); this.tags = new HashMap<>(0); } /** * Create a new HttpRequest instance. * * @param httpMethod The HTTP request method. * @param url The target address to send the request to. * @param headers The HTTP headers to use with this request. * @param body The request content. * @throws IllegalArgumentException if the url is malformed. */ public HttpRequest(HttpMethod httpMethod, String url, HttpHeaders headers, byte[] body) { this.httpMethod = Util.requireNonNull(httpMethod, "'httpMethod' is required."); Util.requireNonNull(url, "'url' is required."); try { this.url = new URL(url); } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning(new IllegalArgumentException("'url' must be a valid URL", ex)); } this.headers = Util.requireNonNull(headers, "'headers' is required."); this.body = Util.requireNonNull(body, "'body' is required."); this.tags = new HashMap<>(0); } /** * Get the request method. * * @return the request method */ public HttpMethod getHttpMethod() { return httpMethod; } /** * Set the request method. * * @param httpMethod the request method * @return this HttpRequest */ public HttpRequest setHttpMethod(HttpMethod httpMethod) { this.httpMethod = httpMethod; return this; } /** * Get the target address. * * @return the target address */ public URL getUrl() { return url; } /** * Set the target address to send the request to. * * @param url target address. * @return this HttpRequest * @throws IllegalArgumentException if the url is malformed. */ public HttpRequest setUrl(String url) { try { this.url = new URL(url); } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning(new IllegalArgumentException("'url' must be a valid URL", ex)); } return this; } /** * Get the request headers. * * @return headers to be sent */ public HttpHeaders getHeaders() { return headers; } /** * Set the request headers. * * @param headers the set of headers * @return this HttpRequest */ public HttpRequest setHeaders(HttpHeaders headers) { this.headers = headers; return this; } /** * Set a request header, replacing any existing value. * A null for {@code value} will remove the header if one with matching name exists. * * @param name the header name * @param value the header value * @return this HttpRequest */ public HttpRequest setHeader(String name, String value) { headers.put(name, value); return this; } /** * Get the request content. * * @return the content to be send */ public byte[] getBody() { return body; } /** * Set the request content. * * @param content the request content * @return this HttpRequest */ public HttpRequest setBody(String content) { final byte[] bodyBytes = content.getBytes(Charset.forName("UTF-8")); return setBody(bodyBytes); } /** * Set the request content. * The Content-Length header will be set based on the given content's length * * @param content the request content * @return this HttpRequest */ public HttpRequest setBody(byte[] content) { headers.put("Content-Length", String.valueOf(content.length)); this.body = content; return this; } /** * Gets the tags-store associated with the request. * * <p> * Tags are key-value data stored in a map and carried with the request. * Use it to store any arbitrary data (such as debugging info) that you want to access * from the request later in the call stack. * </p> * * @return The tags. */ public Map<Object, Object> getTags() { return this.tags; } /** * Creates a copy of the request. * * The main purpose of this is so that this HttpRequest can be changed and the resulting * HttpRequest can be a backup. This means that the cloned HttpHeaders and body must * not be able to change from side effects of this HttpRequest. * * @return a new HTTP request instance with cloned instances of all mutable properties. */ public HttpRequest copy() { HttpRequest requestCopy = new HttpRequest(this.httpMethod, this.url.toString(), new HttpHeaders(this.headers), this.body); // shallow-copy the tags. requestCopy.tags = new HashMap<>(this.tags); return requestCopy; } }
java
14
0.600807
110
28.889447
199
/** * The outgoing Http request. It provides ways to construct {@link HttpRequest} with {@link HttpMethod}, * {@code url}, {@link HttpHeader} and request body. */
class
def validate_type_union(args: argparse.Namespace, type_union: object) -> object: type_annotation = TypeAnnotation(type_union) errors = [] for sub_type in type_annotation.get_underlyings_if_union(): if isinstance(sub_type.raw_type, type) and issubclass(sub_type.raw_type, TypedArgs): try: return sub_type.raw_type(args) except Exception as e: errors.append(str(e)) if len(errors) == 0: raise TypeError(f"Type union {type_union} did not contain any sub types of type TypedArgs.") else: errors_str = "\n".join([f" - {error}" for error in errors]) raise TypeError(f"Validation failed against all sub types of union type:\n{errors_str}")
python
15
0.637466
100
52.071429
14
Helper function to validate args against a type union (but with untyped return).
function
public class Item{ private int id,inv;//item id and inventory number /** * Constructor for an item with a given id and inventory number * @param i id * @param j inventory number */ public Item(int i,int j){ id=i; inv=j; } /** * Returns the id of the item * @return item id */ public int getId(){ return id; } /** * Returns the inventory number of the item * @return inventory number */ public int getInv(){ return inv; } /** * Compares the item to another item using their id * @param other item to be compared to * @return difference in id */ public int compareTo(Item other){ return id-other.getId(); } /** * Checks to see if an item has the same id * @param other item to be compared to * @return boolean based on whether the items have the same id */ public boolean equals(Item other){ return id==other.getId(); } /** * Prints the item's id and inventory number */ public String toString(){ return getId()+" "+getInv(); } }
java
10
0.559001
67
23.208333
48
/** * @author Richard Huang */
class
class Builder<K extends Rule, M extends Mapper<?, V>, V> implements Supplier<Map<String, M>> { Map<String, M> map = new HashMap<>(); /** * Add a mapping * * @param ruleOrToken The key is the actual rule or token * @param mapper The mapper * @return {@code this}, for chaining. */ public Builder<K, M, V> add(K ruleOrToken, M mapper) { map.put(ruleOrToken.getName(), mapper); return this; } @Override public Map<String, M> get() { return map; } }
java
10
0.509182
94
26.272727
22
/** * A mapper builder. * * @author Philippe Poulard * * @param <K> The type of the key : String, Rule, or Token. * @param <M> A subclass of Mapper. * @param <V> The type of the target value. */
class
public class JsonAdaptedSemesterYear { public static final String MISSING_FIELD_MESSAGE_FORMAT = "SemesterYear's %s field is missing!"; protected final String sem; protected final int academicYear; /** * Constructs a {@code JsonAdaptedPerson} with the given person details. */ @JsonCreator public JsonAdaptedSemesterYear(@JsonProperty("sem") String sem, @JsonProperty("academicYear") int academicYear) { this.sem = sem; this.academicYear = academicYear; } /** * Converts a given {@code SemesterYear} into this class for Jackson use. */ public JsonAdaptedSemesterYear(SemesterYear source) { sem = source.getSemester().toString(); academicYear = source.getAcademicYear(); } /** * Converts this Jackson-friendly adapted SemesterYear object into the model's {@code SemesterYear} object. * * @throws IllegalValueException if there were any data constraints violated in the SemesterYear. */ public SemesterYear toModelType() throws IllegalValueException { if (sem == null) { throw new IllegalValueException(String.format(MISSING_FIELD_MESSAGE_FORMAT, Name.class.getSimpleName())); } final Semester modelSem = Semester.valueOf(sem); final int modelAcademicYear = academicYear; return new SemesterYear(modelSem, modelAcademicYear); } }
java
14
0.685816
117
34.275
40
/** * Jackson-friendly version of {@link SemesterYear}. */
class
public void register() { OPFPushLog.methodD(OPFPushHelper.class, "register"); checkInitDone(); synchronized (registrationLock) { final State state = settings.getState(); OPFPushLog.d("Register state : " + state.toString()); switch (state) { case REGISTERING: case REGISTERED: break; case UNREGISTERED: settings.saveState(REGISTERING); if (configuration.isSelectSystemPreferred() && registerSystemPreferredProvider()) { return; } registerFirstAvailableProvider(); break; case UNREGISTERING: throw new UnregistrationNotCompletedStateException(); } } }
java
13
0.488189
73
37.695652
23
/** * Start select push provider and registered it. * <p/> * If you want to modify current registered provider, you must call unregister() first. * <p/> * * @throws OPFPushException When try call this method while init not done. * @throws UnregistrationNotCompletedStateException If unregistration process in progress. */
function
private void DisposeAsyncState() { if (asyncState != null) { asyncState.Dispose(); asyncState = null; } }
c#
9
0.396825
37
22.75
8
/// <summary> /// Disposes the current async state and sets the reference to null. /// </summary>
function
[Serializable] public abstract class EntitySetOperation : EntityFieldOperation { public EntitySetBase GetEntitySet(OperationExecutionContext context) { var session = context.Session; var key = context.TryRemapKey(Key); var target = session.Query.Single(key); return (EntitySetBase) target.GetFieldValue(Field); } protected EntitySetOperation(Key key, FieldInfo field) : base(key, field) { Type fieldType; string fieldName = string.Empty; if (field.IsDynamicallyDefined) { fieldType = field.ValueType; var name = field.Name; } else { fieldType = field.UnderlyingProperty.PropertyType; var name = field.UnderlyingProperty.GetShortName(true); } if (!WellKnownOrmTypes.EntitySetBase.IsAssignableFrom(fieldType)) throw new ArgumentOutOfRangeException( Strings.ExTypeOfXMustBeADescendantOfYType, fieldName, WellKnownOrmTypes.EntitySetBase.GetShortName()); } protected EntitySetOperation(SerializationInfo info, StreamingContext context) : base(info, context) { } }
c#
15
0.675
82
33.147059
34
/// <summary> /// Describes an operation with <see cref="Entity"/> field of <see cref="EntitySet{TItem}"/> type. /// </summary>
class
applyReplace(expression, nodes, newNodes, addOptions = {}) { const updateCount = Math.min(nodes.length, newNodes.length); let expressionValue = expression.value; let offset = 0; for (let i = 0; i < updateCount; ++i) { const updateNode = nodes[i]; const withNode = newNodes[i]; const newValue = DSLUpdateUtil.updateNodeTextString( expressionValue, updateNode, withNode, offset ); offset += newValue.length - expressionValue.length; expressionValue = newValue; } const newExpression = new DSLExpression(expressionValue); if (newNodes.length < nodes.length) { const deleteNodes = nodes.slice(updateCount).map(node => { node.position = node.position.map(([start, end]) => { return [start + offset, end + offset]; }); return node; }); return DSLUpdateUtil.applyDelete(newExpression, deleteNodes); } if (newNodes.length > nodes.length) { return DSLUpdateUtil.applyAdd( newExpression, newNodes.slice(updateCount), addOptions ); } return newExpression; }
javascript
19
0.621951
67
31.828571
35
/** * Replace the given nodes in the expression with the new array of nodes * taking correcting actions if the lengths do not match. * * @param {DSLExpression} expression - The expression to update * @param {Array} nodes - The node(s) to update * @param {Array} newNodes - The node(s) to update with * @param {Object} [addOptions] - Options for adding nodes * @returns {DSLExpression} expression - The updated expression */
function
func highestEmissionLevel(sub *SubChunk, x, y, z uint8) uint8 { storages := sub.storages l := len(storages) if l == 0 { return 0 } if l == 1 { id := storages[0].RuntimeID(x, y, z) if id == 0 { return 0 } return LightBlocks[id] } if l == 2 { var highest uint8 id := storages[0].RuntimeID(x, y, z) if id != 0 { highest = LightBlocks[id] } id = storages[1].RuntimeID(x, y, z) if id != 0 { if v := LightBlocks[id]; v > highest { highest = v } } return highest } var highest uint8 for i := range storages { if l := LightBlocks[storages[i].RuntimeID(x, y, z)]; l > highest { highest = l } } return highest }
go
12
0.58006
68
17.942857
35
// highestEmissionLevel checks for the block with the highest emission level at a position and returns it.
function
public class CarbonWebappLoader extends WebappLoader { public CarbonWebappLoader() { super(); } public CarbonWebappLoader(ClassLoader parent) { super(parent); } @Override protected void startInternal() throws LifecycleException { WebappClassloadingContext webappClassloadingContext; try { webappClassloadingContext = ClassloadingContextBuilder.buildClassloadingContext(getWebappFilePath()); } catch (Exception e) { throw new LifecycleException(e.getMessage(), e); } //Adding provided classpath entries, if any for (String repository : webappClassloadingContext.getProvidedRepositories()) { addRepository(repository); } super.startInternal(); //Adding the WebappClassloadingContext to the WebappClassloader ((CarbonWebappClassLoader) getClassLoader()).setWebappCC(webappClassloadingContext); } @Override protected void stopInternal() throws LifecycleException { super.stopInternal(); } //TODO Refactor private String getWebappFilePath() throws IOException { String webappFilePath = null; if (getContainer() instanceof Context) { //Value of the following variable depends on various conditions. Sometimes you get just the webapp directory //name. Sometime you get absolute path the webapp directory or war file. Context ctx = (Context) getContainer(); String docBase = ctx.getDocBase(); Host host = (Host) ctx.getParent(); String appBase = host.getAppBase(); File canonicalAppBase = new File(appBase); if (canonicalAppBase.isAbsolute()) { canonicalAppBase = canonicalAppBase.getCanonicalFile(); } else { canonicalAppBase = new File(System.getProperty("carbon.home"), appBase) .getCanonicalFile(); } File webappFile = new File(docBase); if (webappFile.isAbsolute()) { webappFilePath = webappFile.getCanonicalPath(); } else { webappFilePath = (new File(canonicalAppBase, docBase)).getPath(); } } return webappFilePath; } }
java
17
0.618865
120
33.470588
68
/** * Customized WebappLoader for Carbon. */
class
@Override public void discoveryFinishedByTimeout() { RigLog.d("RigLeDiscoveryManager.discoveryFinishedByTimeout"); mIsDiscoveryRunning = false; if (mObserver != null) { mObserver.discoveryDidTimeout(); } }
java
8
0.642023
69
31.25
8
/** * This callback is received when the discovery operation times out based on the timeout * specified in the initial discovery request. If no timeout is specified, then this callback * will not be received. */
function
private APIReturn<T> ApiGet<T>(HttpClient client,string requestUri, CancellationToken token = default(CancellationToken)) { APIReturn<T> apiReturn = new APIReturn<T>(); try { token.ThrowIfCancellationRequested(); var resp = client.GetAsync(requestUri, token).Result; if (!token.IsCancellationRequested) { System.Collections.Generic.IEnumerable<string> RemainIEnum; bool hasRateLimitRemain = resp.Headers.TryGetValues("X-RateLimit-Remaining", out RemainIEnum); System.Collections.Generic.IEnumerable<string> RateResetIEnum; bool hasRateReset = resp.Headers.TryGetValues("X-RateLimit-Reset", out RateResetIEnum); int numAPICallsRemain; if (hasRateLimitRemain && hasRateReset) { int.TryParse(((string[])RemainIEnum)[0], out numAPICallsRemain); int ResetUnixTime; int.TryParse(((string[])RateResetIEnum)[0], out ResetUnixTime); System.DateTime dt = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc); apiReturn.RateReset = dt.AddSeconds(ResetUnixTime).ToLocalTime(); apiReturn.NumCallsLeft = numAPICallsRemain; } string respStr = resp.Content.ReadAsStringAsync().Result; if (respStr.Contains("message")) { apiReturn.isSuccess = false; ParseErrorAndRaiseEvent(resp); } else { apiReturn.isSuccess = true; apiReturn.q_obj = JsonToObject<T>(resp.Content.ReadAsStringAsync().Result); } return apiReturn; } else { return default(APIReturn<T>); } } catch (HttpRequestException ex) { APIGetErrorArg arg = new APIGetErrorArg(); arg.httpRequestException = ex; OnHttpGetError(this, arg); return apiReturn; } }
c#
19
0.497897
121
47.55102
49
/// <summary> /// Method used to make a GET call to Questrade API /// </summary> /// <typeparam name="T">Return type</typeparam> /// <param name="client">Authenticated http client</param> /// <param name="requestUri">Request URIm</param> /// <returns></returns>
function
func (q *SimpleQueue) SaveSubscribers(ctx context.Context, user cn.CapUser) (err *mft.Error) { if q.SubscriberStorage == nil { return nil } if !q.Subscribers.mxFileSave.TryLock(ctx) { return GenerateError(10031000) } defer q.Subscribers.mxFileSave.Unlock() if !q.Subscribers.mx.RTryLock(ctx) { return GenerateError(10031001) } if q.Subscribers.SaveRv == q.Subscribers.ChangesRv { q.Subscribers.mx.RUnlock() return nil } changesRv := q.Subscribers.ChangesRv data, errMarshal := json.MarshalIndent(q.Subscribers, "", "\t") chLen := len(q.Subscribers.SaveWait) q.Subscribers.mx.RUnlock() if errMarshal != nil { return GenerateErrorE(10031002, errMarshal) } err = q.SubscriberStorage.Save(ctx, SubscribersFileName, data) if err != nil { return GenerateErrorE(10031003, err, SubscribersFileName) } if !q.Subscribers.mx.TryLock(ctx) { return GenerateError(10031004) } q.Subscribers.SaveRv = changesRv if len(q.Subscribers.SaveWait) > 0 && chLen > 0 { saveWait := make([]chan bool, 0) for i := chLen; i < len(q.Subscribers.SaveWait); i++ { saveWait = append(saveWait, q.Subscribers.SaveWait[i]) } approve := q.Subscribers.SaveWait[0:chLen] q.Subscribers.SaveWait = saveWait go func() { for _, v := range approve { v <- true } }() } q.Subscribers.mx.Unlock() return nil }
go
14
0.702479
94
27.956522
46
// SaveSubscribers save subscribers info of queue // When MetaStorage == nil returns nil // When SaveRv == ChangesRv do nothing and returns nil
function
func HyphenizeText(s string) string { for _, k := range byLen { v := hyphm[k] s = strings.Replace(s, k, v, -1) } return s }
go
10
0.592308
37
17.714286
7
// HyphenizeText replaces "mittelfristig" with "mittel|fristig" // Hyphenization is done _once_ during creation of the questionare JSON template. // // // We replace longer keys first, // to prevent erratic results for example from // // desa|cuer|do // acuer|do //
function
def propagate(self, x: np.array, add_bias: bool = True) -> np.array: stride = self.params["stride"] padding = self.params["padding"] weights = torch.Tensor(self.params["weight"]) bias = torch.Tensor(self.params["bias"]) in_shape = self.params["in_shape"] out_size = np.prod(self.out_shape(in_shape)) x_2d = torch.Tensor(x.T.reshape((-1, *in_shape))) y_2d = tf.conv2d(x_2d, weight=weights, stride=stride, padding=padding) if add_bias: y_2d[-1, :, :, :] += bias.view(-1, 1, 1) y = y_2d.detach().numpy().reshape(-1, out_size).T return y
python
12
0.563981
78
47.769231
13
Propagates trough the mapping (by applying the activation function or layer-operation). Args: x : The input as a np.array. Assumed to be a NxM vector where the rows represent nodes and the columns represent coefficients of the symbolic bounds. Can be used on concrete values instead of equations by shaping them into an Nx1 array. add_bias : Adds bias if relevant, for example for FC and Conv layers. Returns: The value of the activation function at x
function
def skip_check(*dargs): def wrapper(func): @wraps(func) def wrapped(self, *args): attrs = [getattr(self, darg) for darg in dargs] if any(attrs): func(self, *args) return wrapped return wrapper
python
14
0.530303
59
28.444444
9
Decorator to determine if method can be skipped
function
public static final class ArgBlock { /** The name of the argument referenced by this "@arg" tag. */ private final FieldName argName; /** The text block describing the argument. */ private final TextBlock textBlock; /** * Creates a representation of an "@arg" block in a CALDoc comment. * * @param argName * the name of the argument referenced by this tagged block. * @param textBlock * the text block that forms the trailing portion of this * tagged block. */ ArgBlock(final FieldName argName, final TextBlock textBlock) { this.argName = argName; this.textBlock = textBlock; } /** * @return the name of the argument referenced by this "@arg" tag. */ public FieldName getArgName() { return argName; } /** * @return the text block describing the argument. */ public TextBlock getTextBlock() { return textBlock; } /** @return a string representation of this instance. */ @Override public final String toString() { final StringBuilder result = new StringBuilder(); toStringBuilder(result, 0); return result.toString(); } /** * Fills the given StringBuilder with a string representation of this instance. * @param result the StringBuilder to fill. * @param indentLevel the indent level to use in indenting the generated text. */ public void toStringBuilder(final StringBuilder result, final int indentLevel) { addSpacesToStringBuilder(result, indentLevel); result.append("[ArgBlock - ").append(argName).append(":\n"); textBlock.toStringBuilder(result, indentLevel + INDENT_LEVEL); addSpacesToStringBuilder(result, indentLevel); result.append("]\n"); } /** * Write this instance of ArgBlock to the RecordOutputStream. * @param s the RecordOutputStream to be written to. */ void write(final RecordOutputStream s) throws IOException { FieldNameIO.writeFieldName(argName, s); textBlock.write(s); } /** * Load an instance of ArgBlock from the RecordInputStream. * @param s the RecordInputStream to be read from. * @param moduleName the name of the module being loaded * @param msgLogger the logger to which to log deserialization messages. * @return an ArgBlock instance deserialized from the stream. */ static ArgBlock load(final RecordInputStream s, final ModuleName moduleName, final CompilerMessageLogger msgLogger) throws IOException { final FieldName argName = FieldNameIO.load(s, moduleName, msgLogger); final TextBlock textBlock = TextBlock.load(s); return new ArgBlock(argName, textBlock); } }
java
11
0.565765
144
38.197531
81
/** * Represents the "@arg" CALDoc tag. The tagged block contains a reference * to an argument name, and is therefore valid only for a CALDoc function * comment or a CALDoc data constructor comment. * * @author Joseph Wong */
class
public class ThreadControl { public void RunMain (String username, String password, String[] hosts, String[] commands,String Operation) throws IOException { String line = null; ArrayList<String> hostList = new ArrayList<>(); ArrayList<String> commandList = new ArrayList<>(); try { for(int i =0;i < hosts.length;i++) { hostList.add(hosts[i]); } ExecutorService executor = Executors.newFixedThreadPool(hostList.size()); for(int i=0;i<commands.length;i++) { commandList.add(commands[i]); } System.out.println(Arrays.toString(commands)); System.out.println("Starting Processes"); System.out.println("all Processes started. \n" + "depending your commands this proccess may not teminate.\n" + "it may be necessary to quit this application as a result."); // Wait until all threads are finish if (Operation.equals("SSH")){ for (int i = 0; i < hostList.size(); i++) { String host = hostList.get(i); Runnable worker = new SSHMyRunnable(host,username,password,commandList); executor.execute(worker); } executor.shutdown(); while (!executor.isTerminated()) { MainWindow.lblStatus.setText("Running: \\\r"); Thread.sleep(100); MainWindow.lblStatus.setText("Running: |\r"); Thread.sleep(100); MainWindow.lblStatus.setText("Running: /\r"); Thread.sleep(100); MainWindow.lblStatus.setText("Running: -\r"); Thread.sleep(100); } MainWindow.lblStatus.setText("Done!"); MainWindow.btnRun.setEnabled(true); }if (Operation.equals("Telnet")){ for (int i = 0; i < hostList.size(); i++) { String host = hostList.get(i); Runnable worker = new TELNETMyRunnable(host,username,password,commandList); executor.execute(worker); } executor.shutdown(); while (!executor.isTerminated()) { MainWindow.lblStatus.setText("Running: \\\r"); Thread.sleep(100); MainWindow.lblStatus.setText("Running: |\r"); Thread.sleep(100); MainWindow.lblStatus.setText("Running: /\r"); Thread.sleep(100); MainWindow.lblStatus.setText("Running: -\r"); Thread.sleep(100); } MainWindow.lblStatus.setText("Done!"); MainWindow.btnRun.setEnabled(true); } } catch (Exception e){ System.out.println(e); } } public static class SSHMyRunnable implements Runnable { private final String hostname; private final String username; private final String password; private final ArrayList<String> commandsList; SSHMyRunnable(String hostname, String username, String password,ArrayList<String> commands) { this.hostname = hostname; this.username = username; this.password = password; this.commandsList = commands; } @Override public void run() { String user = username; String host = hostname; JSch jsch=new JSch(); Date date = new Date(); SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd"); System.out.println("Status: " + hostname + "\t" + "Starting\t"); try { Session session=jsch.getSession(user, host, 22); session.setPassword(password); session.setConfig("StrictHostKeyChecking", "no"); session.setTimeout(30000);; session.connect(); Channel channel=session.openChannel("shell"); //Create filename File file = new File(host + "-" + ft.format(date) + ".log"); FileOutputStream fos = new FileOutputStream(file, true); PrintStream ps = new PrintStream(fos); //sets system.out to write to text file OutputStream inputstream_for_the_channel = channel.getOutputStream(); PrintStream commander = new PrintStream(inputstream_for_the_channel, true); channel.setOutputStream(ps, true); channel.connect(); for (int i = 0; i < commandsList.size(); i++) { String command = commandsList.get(i); commander.println(command); } System.out.println("Status: " + hostname + "\t" + "Running\t"); do { Thread.sleep(1000); } while(!channel.isEOF()); session.disconnect(); commander.close(); System.out.println("Status: " + hostname + "\t" + "Done\t"); } catch (Exception e){ System.out.println(host + e); } } } public static class TELNETMyRunnable implements Runnable { private final String hostname; private final String username; private final String password; private final ArrayList<String> commandsList; TELNETMyRunnable(String hostname, String username, String password,ArrayList<String> commands) { this.hostname = hostname; this.username = username; this.password = password; this.commandsList = commands; } @Override public void run() { Telnet t = new Telnet(); t.TelnetMain(username, password, hostname, commandsList); } } }
java
17
0.529098
135
36.024691
162
/* * * @author Michael Curtis */
class
def crossover_two_n_point(individuals : list, n_points : int = 1, prob : float = 0.5, island=None) -> list: assert len(individuals) > 1, "Not enough individuals given!" mother = individuals[0] father = individuals[1] size = min(len(mother.chromosome), len(father.chromosome)) point_cut_list = random.sample(range(1,size-1), n_points) point_cut_list.sort() point_cut_list.insert(0,0) point_cut_list.append(size) for i in range(len(point_cut_list)-1): if random.random() < prob: b = point_cut_list[i] e = point_cut_list[i+1] mother.chromosome[b:e], father.chromosome[b:e] = father.chromosome[b:e], mother.chromosome[b:e] return [mother, father]
python
12
0.637741
107
47.466667
15
Classic crossover method to randomly select N points for crossover. Args: individuals (list): A list (length of 2) of Individuals to perform crossover. n_points (int): The amount of random points to split at (default = 1). prob (float): The probability of swapping genes. island (Island): The Island calling the method (default = None). Returns: list: Two new Individuals.
function
bool autonomousTest(int periodLengthMilliseconds) { float milliseconds = time1[timer1]; if (milliseconds > periodLengthMilliseconds) { clearTimer(timer1); milliseconds = 0; } const float L = periodLengthMilliseconds; if (milliseconds >= 0.0 * L && milliseconds < 0.2 * L) { mecanumDrive(0, 127, 0); } else if (milliseconds >= 0.2 * L && milliseconds < 0.4 * L) { mecanumDrive(127, 0, 0); } else if (milliseconds >= 0.4 * L && milliseconds < 0.6 * L) { mecanumDrive(0, -127, 0); } else if (milliseconds >= 0.6 * L && milliseconds < 0.8 * L) { mecanumDrive(-127, 0, 0); } else { mecanumDrive(0, 0, 0); return true; } return false; }
c
15
0.639939
65
30.52381
21
// Uses the mecanumDrive() function to drive in set patterns, testing whether everything was wired correctly. // // Remember that this function provides instantaneous motion, and must be // called in a loop to take place continuously. // // Arguments: // - periodLengthMilliseconds: The duration of the programmed cycle of behavior. // Must be less than 32,767 (the maximum duration of the vex timers.) // // Return values: // - True if we've reached the end of our cycle, false otherwise. The cycle // will repeat itself again naturally unless you stop calling autonomousTest().
function
class Zenith: """ Class representing a Zenith installation. """ #: The base domain of the target Zenith instance base_domain: str #: The external URL of the registrar of the target Zenith instance registrar_external_url: str #: The admin URL of the registrar of the target Zenith instance registrar_admin_url: str #: The address of the SSHD service of the target Zenith instance sshd_host: str #: The port for the SSHD service of the target Zenith instance sshd_port: int #: Indicates whether SSL should be verified when determining whether a service is ready verify_ssl: bool #: Indicates whether SSL should be verified by clients when associating keys with the #: registrar using the external endpoint verify_ssl_clients: bool #: The URL for the console script console_script_url: str def service_is_ready(self, fqdn: str, readiness_path: str = "/") -> t.Optional[str]: """ Given an FQDN for a Zenith service, return the redirect URL if it is ready or `None` otherwise. Optionally, a readiness path can be given that will be used for the readiness check. """ url = f"http://{fqdn}" # While the URL returns a 404, 503 or a certificate error (probably because cert-manager # is still negotiating the certificate), the service is not ready try: resp = requests.get("{}{}".format(url, readiness_path), verify = self.verify_ssl) except requests.exceptions.SSLError: return None else: return url if resp.status_code not in {404, 503} else None def reserve_subdomain(self) -> ZenithReservation: """ Reserves a subdomain and returns a `ZenithReservation` for the subdomain. """ response = requests.post(f"{self.registrar_admin_url}/admin/reserve") response.raise_for_status() response_data = response.json() return ZenithReservation( response_data["subdomain"], response_data["fqdn"], response_data["token"] ) def web_console_userdata(self) -> str: """ Returns a userdata string that installs the web console on a machine. """ return "\n".join([ "#!/usr/bin/env bash", "set -eo pipefail", "curl -fsSL {} | bash -s console".format(self.console_script_url) ])
python
14
0.631385
96
39.131148
61
Class representing a Zenith installation.
class
void Decryption(const std::string &algorithm) { auto input_file = GetInputFile(); auto output_file = GetOutputFile(input_file); std::ifstream in(input_file); std::ofstream out(output_file); if(!in || !out) { PrintCannotOpenFile(); return; } if(algorithm == "caesar" || algorithm == "CAESAR" || algorithm == "Caesar") CaeserCipherDecode(in, out); else if(algorithm == "shift" || algorithm == "SHIFT" || algorithm == "Shift") ShiftCipherDecode(in,out); else if(algorithm == "XOR" || algorithm == "Xor" || algorithm == "xor") XorCipherDecode(in, out); else if(algorithm == "vigenere" || algorithm == "VIGENERE" || algorithm == "Vigenere") VigenereCipherDecode(in,out); else if(algorithm == "DES" || algorithm == "Des" || algorithm == "des") DESCipherDecode(input_file); else if(algorithm == "RC4" || algorithm == "Rc4" || algorithm == "rc4") RC4CipherDecode(input_file); else if(algorithm == "3DES" || algorithm == "3des" || algorithm == "3Des") ThreeDESCipherDecode(input_file); }
c++
21
0.598383
90
41.846154
26
/** * @brief Calls appropriate function based on algorithm parameter for decryption * @param algorithm Algorithm used for decryption * @param input_file Address of input file * @param output_file Address of output file */
function
func SignJWTClaims(claims *jwtpb.JWTClaims, signingKey string) (string, error) { token, err := ProtoToToken(claims) if err != nil { return "", err } return SignToken(token, signingKey) }
go
8
0.713542
80
26.571429
7
// SignJWTClaims signs the claim using the given signing key.
function
def _add_limit_lines(self): if self.uwl is not None: uwl_pts = ((self.x_data[0], self.uwl), (self.x_data[-1], self.uwl)) uwl_line = FloatCanvas.Line(uwl_pts, LineColor=wx.YELLOW, LineWidth=1, LineStyle="LongDash" ) self.canvas.AddObject(uwl_line) if self.lwl is not None: lwl_pts = ((self.x_data[0], self.lwl), (self.x_data[-1], self.lwl)) lwl_line = FloatCanvas.Line(lwl_pts, LineColor=wx.YELLOW, LineWidth=1, LineStyle="LongDash" ) self.canvas.AddObject(lwl_line) if self.ucl is not None: ucl_pts = ((self.x_data[0], self.ucl), (self.x_data[-1], self.ucl)) ucl_line = FloatCanvas.Line(ucl_pts, LineColor=wx.RED, LineWidth=1, LineStyle="LongDash" ) self.canvas.AddObject(ucl_line) if self.lcl is not None: lcl_pts = ((self.x_data[0], self.lcl), (self.x_data[-1], self.lcl)) lcl_line = FloatCanvas.Line(lcl_pts, LineColor=wx.RED, LineWidth=1, LineStyle="LongDash" ) self.canvas.AddObject(lcl_line) return
python
11
0.353846
60
46.921053
38
Creates the limit lines and adds them to the plot
function
private static void assertModelsAreEqual(SimulinkModel mdlModel, SimulinkModel slxModel) throws UnsupportedEncodingException { assertParametersAreEqual(extractParameters(mdlModel), extractParameters(slxModel)); for (SimulinkBlock mdlBlock : mdlModel.getSubBlocks()) { String name = mdlBlock.getName(); assertThat(name, notNullValue()); SimulinkBlock slxBlock = slxModel .getSubBlock(unescapeNewlines(name)); assertThat("Not block found in SLX for " + name, slxBlock, notNullValue()); assertBlocksAreEqual(mdlBlock, slxBlock); } }
java
11
0.762324
64
39.642857
14
/** Assert that models are equal in sub blocks and parameters. */
function
protected void saveCacheData(IgniteCache<Object, Object> cache) { for (int i = 0; i < ROWS_CNT; i++) cache.put(i, new EntityValueValue(new EntityValue(i + 2), i, i + 1)); cache.query(new SqlFieldsQuery( "CREATE INDEX " + INDEX_NAME + " ON \"" + TEST_CACHE_NAME + "\".EntityValueValue " + "(intVal1, val, intVal2)")).getAll(); }
java
15
0.527711
104
58.428571
7
/** * Create a complex index (int, pojo, int). Check that middle POJO object is correctly available from inline. * * @param cache to be filled with data. Results may be validated in {@link #validateResultingCacheData(IgniteCache, String)}. */
function
public class FolderWrapper:IFolderWrapper { readonly string basePath; public FolderWrapper(string basePath) { this.basePath = basePath; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { } public bool Exists(string relativePath) { var filePath = System.IO.Path.Combine(basePath, relativePath); return File.Exists(filePath); } public Stream Stream(string relativePath) { var filePath = System.IO.Path.Combine(basePath, relativePath); if (!File.Exists(filePath)) return null; return File.OpenRead(filePath); } }
c#
13
0.631799
70
24.642857
28
/// <summary> /// This is a class to allow access to resources within a folder. /// It is a sibling to ZipWrapper that can access resources within a zip file /// </summary>
class
func AutomateElasticsearch(t *testing.T) *deployment.Service { pkg := habpkg.New("chef", "automate-elasticsearch") return &deployment.Service{ Installable: &pkg, DeploymentState: deployment.Running, SSLKey: testCertData["automate-elasticsearch"].Key, SSLCert: testCertData["automate-elasticsearch"].Cert, } }
go
13
0.714706
63
36.888889
9
// AutomateElasticsearch returns a sample elasticsearch service
function
private void TriggerNewWorld(GuiWorldSelection gui){ List<WorldTypeNode> types = DefaultWorldGenerator.modConfig.getSettings().getWorldList(); List<WorldTypeNode> selectable = new LinkedList<>(); GuiScreen screen; for(WorldTypeNode n : types){ if(((BooleanTypeNode)n.getField(WorldTypeNode.Fields.SHOW_IN_LIST)).getValue()){ selectable.add(n); } } if(selectable.size()==0){ if(types.size()==0){ screen = new GuiCreateCustomWorld(Minecraft.getMinecraft().currentScreen,new WorldTypeNode(null)); } else{ screen = new GuiCreateCustomWorld(Minecraft.getMinecraft().currentScreen,types.get(0)); } } else{ screen = new DefaultWorldSelectionList(Minecraft.getMinecraft().currentScreen, selectable); } gui.mc.displayGuiScreen(screen); }
java
14
0.605932
114
41.954545
22
/** * Open the Customized New World Gui * * @param gui the active WorldSelectionScreen */
function
class Trie: """ Data structure based on tree to get the set of sentences based on their prefix. """ def __init__(self): """ Initialize trie with empty hash map of the characters. """ self.letters = {} def add(self, text): """ Add a text into trie recursievly. :param text: prefix to add """ if len(text) > 0: self.letters.setdefault(text[0], Trie()).add(text[1:]) else: self.letters[''] = None # terminate text by \n def get(self, prefix): """ Generator to get the names based on the prefix. :param prefix: to get the list (can be full name) :return: generator of the texts """ if len(prefix) > 0: if prefix[0] in self.letters: # return only if prefix is in the trie for text in self.letters.get(prefix[0]).get(prefix[1:]): yield ''.join((prefix[0], text)) else: # end of the prefix: get all the elements for text in self: yield text def __iter__(self): """ Generator of all the texts in the trie. :return: all the texts """ for letter,trie in self.letters.items(): if trie is None: # terminated text yield letter == '' yield letter else: for text in trie: # yield all children texts yield ''.join((letter, text))
python
17
0.493622
72
28.055556
54
Data structure based on tree to get the set of sentences based on their prefix.
class
static bool cgraph_check_inline_limits (struct cgraph_node *to, struct cgraph_node *what, const char **reason, bool one_only) { int times = 0; struct cgraph_edge *e; int newsize; int limit; if (one_only) times = 1; else for (e = to->callees; e; e = e->next_callee) if (e->callee == what) times++; if (to->global.inlined_to) to = to->global.inlined_to; if (to->local.self_insns > what->local.self_insns) limit = to->local.self_insns; else limit = what->local.self_insns; limit += limit * PARAM_VALUE (PARAM_LARGE_FUNCTION_GROWTH) / 100; newsize = cgraph_estimate_size_after_inlining (times, to, what); if (newsize >= to->global.insns && newsize > PARAM_VALUE (PARAM_LARGE_FUNCTION_INSNS) && newsize > limit) { if (reason) *reason = N_("--param large-function-growth limit reached"); return false; } return true; }
c
11
0.622807
77
27.53125
32
/* Return false when inlining WHAT into TO is not good idea as it would cause too large growth of function bodies. When ONE_ONLY is true, assume that only one call site is going to be inlined, otherwise figure out how many call sites in TO calls WHAT and verify that all can be inlined. */
function
bool ParseTreeHelpers::IsInferredDeclaration ( ParseTree::Statement *pStatement, SourceFile *pFile, Location *pLoc ) { if (!pStatement || !pFile || !(pFile->GetOptionFlags() & OPTION_OptionInfer)) { return false; } if (pStatement->Opcode == ParseTree::Statement::VariableDeclaration) { ParseTree::VariableDeclarationList *pDeclarations = pStatement->AsVariableDeclaration()->Declarations; while (pDeclarations && pDeclarations->Element && !pDeclarations->Element->TextSpan.ContainsExtended(pLoc)) { pDeclarations = pDeclarations->Next; } if (pDeclarations && pDeclarations->Element && pDeclarations->Element->Opcode == ParseTree::VariableDeclaration::WithInitializer && !pDeclarations->Element->Type) { return true; } } else if (pStatement->Opcode == ParseTree::Statement::ForFromTo || pStatement->Opcode == ParseTree::Statement::ForEachIn) { ParseTree::ForStatement *pForStatement = pStatement->AsFor(); if (pForStatement && !pForStatement->ControlVariableDeclaration) { return true; } } return false; }
c++
13
0.595073
110
29.952381
42
//============================================================================= // IsInferredDeclaration // Is Option Infer On and does the given statement represent an inferred type // i.e. no explicit type in the declaration. // Note: Using statement looks like a variable declaration at this point. //=============================================================================
function
func Infer(k string, value interface{}) KeyValue { if value == nil { return String(k, "<nil>") } if stringer, ok := value.(fmt.Stringer); ok { return String(k, stringer.String()) } rv := reflect.ValueOf(value) switch rv.Kind() { case reflect.Array, reflect.Slice: return Array(k, value) case reflect.Bool: return Bool(k, rv.Bool()) case reflect.Int, reflect.Int8, reflect.Int16: return Int(k, int(rv.Int())) case reflect.Int32: return Int32(k, int32(rv.Int())) case reflect.Int64: return Int64(k, int64(rv.Int())) case reflect.Uint, reflect.Uint8, reflect.Uint16: return Uint(k, uint(rv.Uint())) case reflect.Uint32: return Uint32(k, uint32(rv.Uint())) case reflect.Uint64, reflect.Uintptr: return Uint64(k, rv.Uint()) case reflect.Float32: return Float32(k, float32(rv.Float())) case reflect.Float64: return Float64(k, rv.Float()) case reflect.String: return String(k, rv.String()) } return String(k, fmt.Sprint(value)) }
go
13
0.687694
50
27.470588
34
// Infer creates a new key-value pair instance with a passed name and // automatic type inference. This is slower, and not type-safe.
function
function belowThresholdBonus(battleInfo, belowThresholdMod, modSource, charToUse) { "use strict"; for (var stat in belowThresholdMod.stat_mod) { battleInfo[charToUse][stat] += belowThresholdMod.stat_mod[stat]; battleInfo.logMsg += "<li class='battle-interaction'><span class='" + charToUse + "'><strong>" + battleInfo[charToUse].name + "</strong></span> gains " + belowThresholdMod.stat_mod[stat].toString() + " " + statWord(stat) + " for having HP ≤ " + (belowThresholdMod.threshold * 100).toString() +"% [" + modSource + "].</li>"; } return battleInfo; }
javascript
20
0.696809
325
69.625
8
// battleInfo contains all battle information, belowThresholdMod contains all information for the bonuses, modSource is the source of the bonuses, charToUse is either "attacker" or "defender"
function
private void updateProvider() { int providerID = readPositiveInteger("Enter the Provider ID of the member to update: ", in); in.nextLine(); if (controller.searchProvider(providerID) == null) { System.out.println("Provider with ID " + providerID + " not found."); return; } Provider provider = createProvider(); controller.removeProvider(providerID); controller.addProvider(provider); }
java
11
0.624733
100
41.727273
11
/** * Method that updates a provider in the database */
function
class Screen: public AOutput { public: Screen(); ~Screen(); void print(const std::string &); private: C12832 *shieldLCD = NULL; }
c++
8
0.674074
34
16
8
/** * LCD screen on mbed shield. * Inherits from AOutput and implement the print method. */
class
public static int[] sortArrayAscending( double[] valuesToSort ) { int M = valuesToSort.length; DoubleIntegerPair[] pairs = new DoubleIntegerPair[ M ]; for( int i = 0; i < M; i++ ) { pairs[ i ] = new DoubleIntegerPair( valuesToSort[i], i ); } Arrays.sort( pairs, new DefaultComparator<DoubleIntegerPair>() ); int[] indices = new int[ M ]; for( int i = 0; i < M; i++ ) { indices[i] = pairs[i].getIndex(); } return indices; }
java
10
0.501779
73
30.277778
18
/** * Returns the indices of the array sorted in ascending order * @param valuesToSort values that should be sorted in ascending order, * via a call to Arrays.sort(), does not change values of "valuesToSort" * @return indices of the ascending-ordered valuesToSort, so that * index[0] is the smallest value, and index[index.length-1] is the biggest */
function
class FxConfirm extends FxAction { connectedCallback() { this.message = this.hasAttribute('message') ? this.getAttribute('message') : null; } perform() { if (window.confirm(this.message)) { super.perform(); } } }
javascript
11
0.635983
86
20.818182
11
/** * `fx-confirm` * Displays a simple confirmation before actually executing the nested actions. * * @customElement * @demo demo/project.html */
class
std::size_t construct_escape_string(unsigned char *buf, std::uint_fast32_t codepoint) { std::stringstream stream; if (codepoint < 0x1000u) { stream << std::setfill('0') << std::setw(4); } stream << std::hex << std::uppercase << codepoint; stream.read(reinterpret_cast<char *>(buf + 3), 6); auto num_chars_read = stream.gcount(); assert(num_chars_read >= 4 && num_chars_read <= 6); std::size_t idx_of_ending_singlequote = static_cast<std::size_t>(num_chars_read + 3); buf[idx_of_ending_singlequote] = '\''; return idx_of_ending_singlequote + 1; }
c++
11
0.625839
89
44.923077
13
/** * Given a buffer and a Unicode code point, this function constructs the escape * string for that code point. The first three bytes of the buffer should be "\u'" * because those will be the same for every escape string. Note that in this docstring * (and elsewhere in the codebase), when describing a sequence of characters, the outer * quotes are external delimiters and SHOULD NOT be interpreted as being part of the * sequence. * * For example, given the code point 1000 (hex value 0x3E8) this function would write to the * buffer "\u'03E8'". All letters will be uppercase except the "u" at the beginning. * * Any number whose hex representation would fit in less than 4 hex digits (like 0x3E8) * will be padded by leading zeros to reach 4 characters. No padding is done for larger * values. * @param buf A buffer of length 10 bytes, where the first three bytes are "\u'". * @param codepoint Int representing a Unicode code point; must be a number in [0, 2^21). * @return The number of characters in the escape string. Will be 8, 9, or 10. */
function
func policiesUsingProtector(protector *actions.Protector) []*actions.Policy { mounts, err := filesystem.AllFilesystems() if err != nil { log.Print(err) return nil } var policies []*actions.Policy for _, mount := range mounts { if _, _, err := mount.GetProtector(protector.Descriptor()); err != nil { continue } policyDescriptors, err := mount.ListPolicies() if err != nil { log.Printf("listing policies: %s", err) continue } ctx := *protector.Context ctx.Mount = mount for _, policyDescriptor := range policyDescriptors { policy, err := actions.GetPolicy(&ctx, policyDescriptor) if err != nil { log.Printf("reading policy: %s", err) continue } if policy.UsesProtector(protector) { policies = append(policies, policy) } } } return policies }
go
13
0.664596
77
25
31
// policiesUsingProtector searches all the mountpoints for any policies // protected with the specified protector.
function
public bool Remove(XCommoner item) { Boolean flag = false; if (item != null) { this.XCollection_Children.Remove(item); item.Data.Remove(); flag = true; } return flag; }
c#
11
0.410959
55
25.636364
11
/// <summary> /// Removes an Xcommoner from the collection /// </summary> /// <param name="item">The item to be removed</param> /// <returns>True if the item is removed</returns>
function
protected static boolean boolType(String thing, String col) throws SurveyException { if (Arrays.asList(trueValues).contains(thing.toLowerCase())) return true; else if (Arrays.asList(falseValues).contains(thing.toLowerCase())) return false; else throw new MalformedBooleanException(thing, col); }
java
10
0.685879
84
48.714286
7
/** * Returns the internal boolean representation of a boolean-valued input to CSV or JSON. * @param thing The raw text being parsed. * @param col The associated column/key (used for debugging). * @return Internal boolean representation of the input data. * @throws SurveyException */
function
public class QuickLog { private static File logFile = null; private static DateFormat timestampFormat = null; private static List<String> fileOutputQueue = new ArrayList<>(); public static void initialize() throws IOException { timestampFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); logFile = new File("./logs/" + new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss").format(Calendar.getInstance().getTime()) + ".txt"); if (!logFile.getParentFile().isDirectory() && !logFile.getParentFile().mkdirs()) throw new IOException("Failed to create a directory for log files."); try { logToFile("[" + timestampFormat.format(Calendar.getInstance().getTime()) + "][INFO] QuickLog: Logging has begun."); } catch (IOException ex) { throw new IOException("Failed to log to file: " + ex.getMessage()); } } public static void msg(IMessage message) { if (message.getGuild() == null) { logSafely("MSG/PRIVATE/" + message.getAuthor().getName() + "#" + message.getAuthor().getDiscriminator(), message.getContent()); } else { logSafely("MSG/" + message.getGuild().getName() + "/" + message.getChannel().getName() + "/" + message.getAuthor().getName() + "#" + message.getAuthor().getDiscriminator(), message.getContent()); } } public static void reply(IMessage message, String s) { if (message.getGuild() == null) { logSafely("REPLY/PRIVATE/" + message.getAuthor().getName() + "#" + message.getAuthor().getDiscriminator(), s); } else { logSafely("REPLY/" + message.getGuild().getName() + "/" + message.getChannel().getName() + "/" + message.getAuthor().getName() + "#" + message.getAuthor().getDiscriminator(), s); } } public static void replyFailure(IMessage message, String s, Exception ex) { String channel = message.getGuild() == null ? message.getAuthor().getName() + "#" + message.getAuthor().getDiscriminator() : message.getGuild().getName() + "/" + message.getChannel().getName() + "/" + message.getAuthor().getName() + "#" + message.getAuthor().getDiscriminator(); StringWriter sw = new StringWriter(); ex.printStackTrace(new PrintWriter(sw)); severe("Failed to send reply to " + channel + "."); severe("Reply content: " + s); severe(ex.getClass().getSimpleName() + ": " + ex.getMessage()); severe(sw.toString()); } public static void info(String message) { logSafely("INFO", message); } public static void severe(String message) { logSafely("SEVERE", message); } public static void exception(Exception ex) { StringWriter sw = new StringWriter(); ex.printStackTrace(new PrintWriter(sw)); severe(ex.getClass().getSimpleName() + ": " + ex.getMessage()); severe(sw.toString()); } private static void logSafely(String mode, String message) { String fullMessage = "[" + timestampFormat.format(Calendar.getInstance().getTime()) + "][" + mode + "] " + message; try { logToFile(fullMessage); } catch (Exception ex) { System.out.println("[LOGFILE FAILED]" + fullMessage); return; } System.out.println(fullMessage); } private static void logToFile(String message) throws IOException { fileOutputQueue.add(message); while (fileOutputQueue.get(0) != message); FileUtils.writeStringToFile(logFile, message + "\n", Charsets.UTF_8, true); fileOutputQueue.remove(0); } }
java
20
0.612452
207
45.75641
78
/** * Created by LukeSmalley on 10/15/2016. */
class
public void sortByGrouping(List<Condition<GameObject>> conditions, List<Comparator<GameObject>> comparators) { Map<Condition<GameObject>, List<GameObject>> mapConditionToSublist = new HashMap<>(); Map<Condition<GameObject>, Comparator<GameObject>> mapConditionToComparator = new HashMap<>(); for(int i = 0; i < conditions.size(); i++) { mapConditionToSublist.put(conditions.get(i), new ArrayList<GameObject>()); mapConditionToComparator.put(conditions.get(i),comparators.get(i)); } for(Condition<GameObject> condition : conditions) { List<GameObject> filtered = ListUtility.filter(gameObjects, condition); mapConditionToSublist.get(condition).addAll(filtered); } gameObjects.clear(); for(Condition<GameObject> condition : conditions) { List<GameObject> sublist = mapConditionToSublist.get(condition); Collections.sort(sublist, mapConditionToComparator.get(condition)); gameObjects.addAll(sublist); } }
java
11
0.673893
110
58
18
/** * @param conditions - must be mutually exclusive */
function
HRESULT DXUTInit( bool bParseCommandLine, bool bHandleDefaultHotkeys, bool bShowMsgBoxOnError, bool bHandleAltEnter ) { GetDXUTState().SetDXUTInitCalled( true ); InitCommonControls(); STICKYKEYS sk = {sizeof(STICKYKEYS), 0}; SystemParametersInfo(SPI_GETSTICKYKEYS, sizeof(STICKYKEYS), &sk, 0); GetDXUTState().SetStartupStickyKeys( sk ); TOGGLEKEYS tk = {sizeof(TOGGLEKEYS), 0}; SystemParametersInfo(SPI_GETTOGGLEKEYS, sizeof(TOGGLEKEYS), &tk, 0); GetDXUTState().SetStartupToggleKeys( tk ); FILTERKEYS fk = {sizeof(FILTERKEYS), 0}; SystemParametersInfo(SPI_GETFILTERKEYS, sizeof(FILTERKEYS), &fk, 0); GetDXUTState().SetStartupFilterKeys( fk ); HINSTANCE hInstWinMM = LoadLibrary( L"winmm.dll" ); if( hInstWinMM ) { LPTIMEBEGINPERIOD pTimeBeginPeriod = (LPTIMEBEGINPERIOD)GetProcAddress( hInstWinMM, "timeBeginPeriod" ); if( NULL != pTimeBeginPeriod ) pTimeBeginPeriod(1); FreeLibrary(hInstWinMM); } GetDXUTState().SetShowMsgBoxOnError( bShowMsgBoxOnError ); GetDXUTState().SetHandleDefaultHotkeys( bHandleDefaultHotkeys ); GetDXUTState().SetHandleAltEnter( bHandleAltEnter ); if( bParseCommandLine ) DXUTParseCommandLine(); if( !D3DXCheckVersion( D3D_SDK_VERSION, D3DX_SDK_VERSION ) ) { DXUTDisplayErrorMessage( DXUTERR_INCORRECTVERSION ); return DXUT_ERR( L"D3DXCheckVersion", DXUTERR_INCORRECTVERSION ); } IDirect3D9* pD3D = DXUTGetD3DObject(); if( pD3D == NULL ) { pD3D = DXUT_Dynamic_Direct3DCreate9( D3D_SDK_VERSION ); GetDXUTState().SetD3D( pD3D ); } if( pD3D == NULL ) { DXUTDisplayErrorMessage( DXUTERR_NODIRECT3D ); return DXUT_ERR( L"Direct3DCreate9", DXUTERR_NODIRECT3D ); } DXUTGetGlobalTimer()->Reset(); GetDXUTState().SetDXUTInited( true ); return S_OK; }
c++
11
0.689254
117
40.086957
46
//-------------------------------------------------------------------------------------- // Optionally parses the command line and sets if default hotkeys are handled // // Possible command line parameters are: // -adapter:# forces app to use this adapter # (fails if the adapter doesn't exist) // -windowed forces app to start windowed // -fullscreen forces app to start full screen // -forcehal forces app to use HAL (fails if HAL doesn't exist) // -forceref forces app to use REF (fails if REF doesn't exist) // -forcepurehwvp forces app to use pure HWVP (fails if device doesn't support it) // -forcehwvp forces app to use HWVP (fails if device doesn't support it) // -forceswvp forces app to use SWVP // -forcevsync:# if # is 0, forces app to use D3DPRESENT_INTERVAL_IMMEDIATE otherwise force use of D3DPRESENT_INTERVAL_DEFAULT // -width:# forces app to use # for width. for full screen, it will pick the closest possible supported mode // -height:# forces app to use # for height. for full screen, it will pick the closest possible supported mode // -startx:# forces app to use # for the x coord of the window position for windowed mode // -starty:# forces app to use # for the y coord of the window position for windowed mode // -constantframetime:# forces app to use constant frame time, where # is the time/frame in seconds // -quitafterframe:x forces app to quit after # frames // -noerrormsgboxes prevents the display of message boxes generated by the framework so the application can be run without user interaction // -nostats prevents the display of the stats // -relaunchmce re-launches the MCE UI after the app exits // -automation every CDXUTDialog created will have EnableKeyboardInput(true) called, enabling UI navigation with keyboard // This is useful when automating application testing. // // Hotkeys handled by default are: // Alt-Enter toggle between full screen & windowed (hotkey always enabled) // ESC exit app // F3 toggle HAL/REF // F8 toggle wire-frame mode // Pause pause time //--------------------------------------------------------------------------------------
function
public class RedirectUrlBuilder { private String scheme; private String serverName; private int port; private String contextPath; private String servletPath; private String pathInfo; private String query; public void setScheme(String scheme) { if (!("http".equals(scheme) | "https".equals(scheme))) { throw new IllegalArgumentException("Unsupported scheme '" + scheme + "'"); } this.scheme = scheme; } public void setServerName(String serverName) { this.serverName = serverName; } public void setPort(int port) { this.port = port; } public void setContextPath(String contextPath) { this.contextPath = contextPath; } public void setServletPath(String servletPath) { this.servletPath = servletPath; } public void setPathInfo(String pathInfo) { this.pathInfo = pathInfo; } public void setQuery(String query) { this.query = query; } public String getUrl() { StringBuilder sb = new StringBuilder(); Assert.notNull(scheme, "scheme cannot be null"); Assert.notNull(serverName, "serverName cannot be null"); sb.append(scheme).append("://").append(serverName); // Append the port number if it's not standard for the scheme if (port != (scheme.equals("http") ? 80 : 443)) { sb.append(":").append(port); } if (contextPath != null) { sb.append(contextPath); } if (servletPath != null) { sb.append(servletPath); } if (pathInfo != null) { sb.append(pathInfo); } if (query != null) { sb.append("?").append(query); } return sb.toString(); } }
java
13
0.682975
77
20.305556
72
/** * Internal class for building redirect URLs. * * Could probably make more use of the classes in java.net for this. * * @author Luke Taylor * @since 2.0 */
class
def plot_topomap(self, times=None, ch_type='mag', layout=None, vmin=None, vmax=None, cmap='RdBu_r', sensors=True, colorbar=True, scale=None, scale_time=1e3, unit=None, res=64, size=1, format="%3.1f", time_format='%01d ms', proj=False, show=True, show_names=False, title=None, mask=None, mask_params=None, outlines='head', contours=6, image_interp='bilinear', average=None): return plot_evoked_topomap(self, times=times, ch_type=ch_type, layout=layout, vmin=vmin, vmax=vmax, cmap=cmap, sensors=sensors, colorbar=colorbar, scale=scale, scale_time=scale_time, unit=unit, res=res, proj=proj, size=size, format=format, time_format=time_format, show=show, show_names=show_names, title=title, mask=mask, mask_params=mask_params, outlines=outlines, contours=contours, image_interp=image_interp, average=average)
python
7
0.44731
76
66.9
20
Plot topographic maps of specific time points Parameters ---------- times : float | array of floats | None. The time point(s) to plot. If None, 10 topographies will be shown will a regular time spacing between the first and last time instant. ch_type : 'mag' | 'grad' | 'planar1' | 'planar2' | 'eeg' The channel type to plot. For 'grad', the gradiometers are collec- ted in pairs and the RMS for each pair is plotted. layout : None | Layout Layout instance specifying sensor positions (does not need to be specified for Neuromag data). If possible, the correct layout file is inferred from the data; if no appropriate layout file was found, the layout is automatically generated from the sensor locations. vmin : float | callable The value specfying the lower bound of the color range. If None, and vmax is None, -vmax is used. Else np.min(data). If callable, the output equals vmin(data). vmax : float | callable The value specfying the upper bound of the color range. If None, the maximum absolute value is used. If vmin is None, but vmax is not, defaults to np.min(data). If callable, the output equals vmax(data). cmap : matplotlib colormap Colormap. Defaults to 'RdBu_r' sensors : bool | str Add markers for sensor locations to the plot. Accepts matplotlib plot format string (e.g., 'r+' for red plusses). If True, a circle will be used (via .add_artist). Defaults to True. colorbar : bool Plot a colorbar. scale : float | None Scale the data for plotting. If None, defaults to 1e6 for eeg, 1e13 for grad and 1e15 for mag. scale_time : float | None Scale the time labels. Defaults to 1e3 (ms). res : int The resolution of the topomap image (n pixels along each side). size : scalar Side length of the topomaps in inches (only applies when plotting multiple topomaps at a time). format : str String format for colorbar values. time_format : str String format for topomap values. Defaults to "%01d ms" proj : bool | 'interactive' If true SSP projections are applied before display. If 'interactive', a check box for reversible selection of SSP projection vectors will be shown. show : bool Call pyplot.show() at the end. show_names : bool | callable If True, show channel names on top of the map. If a callable is passed, channel names will be formatted using the callable; e.g., to delete the prefix 'MEG ' from all channel names, pass the function lambda x: x.replace('MEG ', ''). If `mask` is not None, only significant sensors will be shown. title : str | None Title. If None (default), no title is displayed. mask : ndarray of bool, shape (n_channels, n_times) | None The channels to be marked as significant at a given time point. Indicies set to `True` will be considered. Defaults to None. mask_params : dict | None Additional plotting parameters for plotting significant sensors. Default (None) equals: dict(marker='o', markerfacecolor='w', markeredgecolor='k', linewidth=0, markersize=4) outlines : 'head' | dict | None The outlines to be drawn. If 'head', a head scheme will be drawn. If dict, each key refers to a tuple of x and y positions. The values in 'mask_pos' will serve as image mask. If None, nothing will be drawn. Defaults to 'head'. contours : int | False | None The number of contour lines to draw. If 0, no contours will be drawn. image_interp : str The image interpolation to be used. All matplotlib options are accepted. average : float | None The time window around a given time to be used for averaging (seconds). For example, 0.01 would translate into window that starts 5 ms before and ends 5 ms after a given time point. Defaults to None, which means no averaging.
function