text
stringlengths 101
197k
| meta
stringlengths 167
272
|
---|---|
// Copyright (c) 2019 Hugo Amiard [email protected]
// This software is licensed under the terms of the GNU General Public License v3.0.
// See the attached LICENSE.txt file or https://www.gnu.org/licenses/gpl-3.0.en.html.
// This notice and the license may not be removed or altered from any source distribution.
#include <core/Event/EventRelay.h>
#include <core/World/World.h>
#include <core/Entity/Entity.h>
#include <core/Event/Event.h>
#include <core/Event/EventTube.h>
using namespace two; namespace toy
{
EventRelay::EventRelay(Entity& entity)
: m_entity(entity)
, m_abstractEventTube()
, m_eventTubes()
{}
void EventRelay::subscribeEvent(EventSubscriber& subscriber)
{
for(EventTube* tube : m_eventTubes)
tube->subscribe(subscriber);
}
void EventRelay::subscribeReceived(EventSubscriber& subscriber)
{
m_receivedSubscribers.insert(&subscriber);
for(EventTubeEnd* tubeEnd : m_eventTubeEnds)
tubeEnd->subscribe(subscriber);
}
void EventRelay::sendEvent(Event& event)
{
//mEventWorld->dispatch(event);
m_abstractEventTube.dispatch(event);
for(EventTube* tube : m_eventTubes)
tube->dispatch(event);
// @todo : collapse all same events that arrived through different tubes into one ?
}
void EventRelay::appendEventTube(EventTube& tube)
{
m_eventTubes.insert(&tube);
}
void EventRelay::removeEventTube(EventTube& tube)
{
m_eventTubes.erase(&tube);
}
void EventRelay::appendEventTubeEnd(EventTubeEnd& tube)
{
m_eventTubeEnds.insert(&tube);
for(EventSubscriber* sub : m_receivedSubscribers)
tube.subscribe(*sub);
}
void EventRelay::removeEventTubeEnd(EventTubeEnd& tube)
{
m_eventTubeEnds.erase(&tube);
}
}
| {'repo_name': 'hugoam/toy', 'stars': '1312', 'repo_language': 'C++', 'file_name': 'blendish_clear.yml', 'mime_type': 'text/plain', 'hash': -5485772975490595973, 'source_dataset': 'data'} |
/*
- * Freeplane - mind map editor
* Copyright (C) 2008 Joerg Mueller, Daniel Polansky, Christian Foltin, Dimitry Polivaev
*
* This file is modified by Dimitry Polivaev in 2008.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.freeplane.features.clipboard.mindmapmode;
import java.awt.event.ActionEvent;
import org.freeplane.core.ui.AFreeplaneAction;
import org.freeplane.features.clipboard.ClipboardController;
import org.freeplane.features.map.NodeModel;
import org.freeplane.features.mode.Controller;
class PasteAction extends AFreeplaneAction {
private static final long serialVersionUID = 1L;
public PasteAction() {
super("PasteAction");
}
public void actionPerformed(final ActionEvent e) {
final MClipboardController clipboardController = (MClipboardController) ClipboardController
.getController();
final NodeModel parent = Controller.getCurrentController().getSelection().getSelected();
clipboardController.paste(clipboardController.getClipboardContents(), parent, false, parent.isNewChildLeft());
}
}
| {'repo_name': 'BeelGroup/Docear-Desktop', 'stars': '251', 'repo_language': 'Java', 'file_name': 'MANIFEST.MF', 'mime_type': 'text/plain', 'hash': -1682420131445303529, 'source_dataset': 'data'} |
//
// asio_ssl.cpp
// ~~~~~~~~~~~~
//
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#include "asio/ssl/impl/src.hpp"
| {'repo_name': 'chriskohlhoff/asio', 'stars': '2334', 'repo_language': 'C++', 'file_name': 'start_member.hpp', 'mime_type': 'text/x-c++', 'hash': 745659778687576717, 'source_dataset': 'data'} |
/*
* Copyright 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.css.compiler.passes;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.google.common.css.SourceCodeLocation;
import com.google.common.css.compiler.ast.BackDoorNodeMutation;
import com.google.common.css.compiler.ast.CssBlockNode;
import com.google.common.css.compiler.ast.CssCompositeValueNode;
import com.google.common.css.compiler.ast.CssConstantReferenceNode;
import com.google.common.css.compiler.ast.CssDeclarationNode;
import com.google.common.css.compiler.ast.CssDefinitionNode;
import com.google.common.css.compiler.ast.CssLiteralNode;
import com.google.common.css.compiler.ast.CssNode;
import com.google.common.css.compiler.ast.CssNumericNode;
import com.google.common.css.compiler.ast.CssPropertyNode;
import com.google.common.css.compiler.ast.CssPropertyValueNode;
import com.google.common.css.compiler.ast.CssRootNode;
import com.google.common.css.compiler.ast.CssRulesetNode;
import com.google.common.css.compiler.ast.CssSelectorNode;
import com.google.common.css.compiler.ast.CssTree;
import com.google.common.css.compiler.ast.ErrorManager;
import com.google.common.css.compiler.ast.GssError;
import com.google.common.css.compiler.ast.MutatingVisitController;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Matchers;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
/**
* Unit tests for {@link ReplaceConstantReferences}.
*
* @author [email protected] (Oana Florescu)
*/
@RunWith(MockitoJUnitRunner.class)
public class ReplaceConstantReferencesTest {
@Mock MutatingVisitController mockVisitController;
@Mock CssTree mockTree;
@Mock ConstantDefinitions mockDefinitions;
@Mock SourceCodeLocation mockLoc;
@Mock CssConstantReferenceNode mockRefNode;
@Mock ErrorManager mockErrorManager;
@Captor ArgumentCaptor<List<CssNode>> cssNodesCaptor;
@Test
public void testRunPass() {
when(mockTree.getMutatingVisitController()).thenReturn(mockVisitController);
ReplaceConstantReferences pass =
new ReplaceConstantReferences(
mockTree,
new ConstantDefinitions(),
true /* removeDefs */,
new DummyErrorManager(),
true /* allowUndefinedConstants */);
mockVisitController.startVisit(pass);
pass.runPass();
}
@Test
public void testEnterDefinitionNode() {
when(mockTree.getMutatingVisitController()).thenReturn(mockVisitController);
ReplaceConstantReferences pass =
new ReplaceConstantReferences(
mockTree,
new ConstantDefinitions(),
true /* removeDefs */,
new DummyErrorManager(),
true /* allowUndefinedConstants */);
mockVisitController.removeCurrentNode();
CssDefinitionNode node = new CssDefinitionNode(new CssLiteralNode("COLOR"));
pass.enterDefinition(node);
}
@Test
public void testEnterValueNode() {
CssDefinitionNode def = new CssDefinitionNode(new CssLiteralNode("COLOR"));
def.getParameters().add(new CssLiteralNode("red"));
CssPropertyNode prop1 = new CssPropertyNode("padding", null);
CssPropertyValueNode value1 = new CssPropertyValueNode();
BackDoorNodeMutation.addChildToBack(value1, new CssNumericNode("5", "px"));
CssPropertyNode prop2 = new CssPropertyNode("color", null);
CssPropertyValueNode value2 = new CssPropertyValueNode();
CssConstantReferenceNode ref = new CssConstantReferenceNode("COLOR", null);
BackDoorNodeMutation.addChildToBack(value2, ref);
CssDeclarationNode decl1 = new CssDeclarationNode(prop1);
decl1.setPropertyValue(value1);
CssDeclarationNode decl2 = new CssDeclarationNode(prop2);
decl2.setPropertyValue(value2);
CssRulesetNode ruleset = new CssRulesetNode();
CssSelectorNode sel = new CssSelectorNode("foo", null);
ruleset.addSelector(sel);
ruleset.addDeclaration(decl1);
ruleset.addDeclaration(decl2);
CssBlockNode body = new CssBlockNode(false);
BackDoorNodeMutation.addChildToBack(body, ruleset);
CssRootNode root = new CssRootNode(body);
CssTree tree = new CssTree(null, root);
ConstantDefinitions constantDefinitions = new ConstantDefinitions();
constantDefinitions.addConstantDefinition(def);
ReplaceConstantReferences pass =
new ReplaceConstantReferences(tree, constantDefinitions,
true /* removeDefs */, new DummyErrorManager(),
true /* allowUndefinedConstants */);
pass.runPass();
assertThat(tree.getRoot().getBody().toString())
.isEqualTo("[[foo]{[padding:[5px], color:[red]]}]");
}
// TODO(oana): Added a task in tracker for fixing these dependencies and
// making the mocking of objects easier.
@Test
public void testEnterArgumentNode() {
CssDefinitionNode def = new CssDefinitionNode(new CssLiteralNode("COLOR"));
when(mockTree.getMutatingVisitController()).thenReturn(mockVisitController);
when(mockDefinitions.getConstantDefinition("COLOR")).thenReturn(def);
ReplaceConstantReferences pass =
new ReplaceConstantReferences(
mockTree,
mockDefinitions,
true /* removeDefs */,
new DummyErrorManager(),
true /* allowUndefinedConstants */);
CssConstantReferenceNode node = new CssConstantReferenceNode("COLOR", null);
pass.enterArgumentNode(node);
Mockito.verify(mockVisitController)
.replaceCurrentBlockChildWith(cssNodesCaptor.capture(), eq(true));
assertThat(cssNodesCaptor.getValue()).hasSize(1);
assertThat(cssNodesCaptor.getValue().get(0).getClass()).isEqualTo(CssCompositeValueNode.class);
}
@Test
public void testAllowUndefinedConstants() {
when(mockRefNode.getValue()).thenReturn("Foo");
when(mockRefNode.getSourceCodeLocation()).thenReturn(mockLoc);
ReplaceConstantReferences allowingPass =
new ReplaceConstantReferences(
mockTree,
mockDefinitions,
true /* removeDefs */,
mockErrorManager,
true /* allowUndefinedConstants */);
allowingPass.replaceConstantReference(mockRefNode);
// This should not cause an error to be reported.
verify(mockErrorManager, times(0)).report(Matchers.<GssError>any());
}
@Test
public void testAllowUndefinedConstantsError() {
when(mockRefNode.getValue()).thenReturn("Foo");
when(mockRefNode.getSourceCodeLocation()).thenReturn(mockLoc);
ReplaceConstantReferences nonAllowingPass =
new ReplaceConstantReferences(
mockTree,
mockDefinitions,
true /* removeDefs */,
mockErrorManager,
false /* allowUndefinedConstants */);
nonAllowingPass.replaceConstantReference(mockRefNode);
// This should cause an error to be reported.
verify(mockErrorManager).report(Matchers.<GssError>any());
}
}
| {'repo_name': 'google/closure-stylesheets', 'stars': '293', 'repo_language': 'Java', 'file_name': 'NewFunctionalTestBase.java', 'mime_type': 'text/x-java', 'hash': -474480046162450523, 'source_dataset': 'data'} |
/*
* Copyright 2016-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
// This file was automatically generated from cancellation-and-timeouts.md by Knit tool. Do not edit.
package kotlinx.coroutines.guide.exampleCancel01
import kotlinx.coroutines.*
fun main() = runBlocking {
val job = launch {
repeat(1000) { i ->
println("job: I'm sleeping $i ...")
delay(500L)
}
}
delay(1300L) // delay a bit
println("main: I'm tired of waiting!")
job.cancel() // cancels the job
job.join() // waits for job's completion
println("main: Now I can quit.")
}
| {'repo_name': 'Kotlin/kotlinx.coroutines', 'stars': '7815', 'repo_language': 'Kotlin', 'file_name': 'Result.kt', 'mime_type': 'text/plain', 'hash': -4119484125472466824, 'source_dataset': 'data'} |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.contacts.vcard;
import android.accounts.Account;
import android.net.Uri;
import com.android.contacts.model.account.AccountWithDataSet;
import com.android.vcard.VCardSourceDetector;
/**
* Class representing one request for importing vCard (given as a Uri).
*
* Mainly used when {@link ImportVCardActivity} requests {@link VCardService}
* to import some specific Uri.
*
* Note: This object's accepting only One Uri does NOT mean that
* there's only one vCard entry inside the instance, as one Uri often has multiple
* vCard entries inside it.
*/
public class ImportRequest {
/**
* Can be null (typically when there's no Account available in the system).
*/
public final Account account;
/**
* Uri to be imported. May have different content than originally given from users, so
* when displaying user-friendly information (e.g. "importing xxx.vcf"), use
* {@link #displayName} instead.
*
* If this is null {@link #data} contains the byte stream of the vcard.
*/
public final Uri uri;
/**
* Holds the byte stream of the vcard, if {@link #uri} is null.
*/
public final byte[] data;
/**
* String to be displayed to the user to indicate the source of the VCARD.
*/
public final String displayName;
/**
* Can be {@link VCardSourceDetector#PARSE_TYPE_UNKNOWN}.
*/
public final int estimatedVCardType;
/**
* Can be null, meaning no preferable charset is available.
*/
public final String estimatedCharset;
/**
* Assumes that one Uri contains only one version, while there's a (tiny) possibility
* we may have two types in one vCard.
*
* e.g.
* BEGIN:VCARD
* VERSION:2.1
* ...
* END:VCARD
* BEGIN:VCARD
* VERSION:3.0
* ...
* END:VCARD
*
* We've never seen this kind of a file, but we may have to cope with it in the future.
*/
public final int vcardVersion;
/**
* The count of vCard entries in {@link #uri}. A receiver of this object can use it
* when showing the progress of import. Thus a receiver must be able to torelate this
* variable being invalid because of vCard's limitation.
*
* vCard does not let us know this count without looking over a whole file content,
* which means we have to open and scan over {@link #uri} to know this value, while
* it may not be opened more than once (Uri does not require it to be opened multiple times
* and may become invalid after its close() request).
*/
public final int entryCount;
public ImportRequest(AccountWithDataSet account,
byte[] data, Uri uri, String displayName, int estimatedType, String estimatedCharset,
int vcardVersion, int entryCount) {
this.account = account != null ? account.getAccountOrNull() : null;
this.data = data;
this.uri = uri;
this.displayName = displayName;
this.estimatedVCardType = estimatedType;
this.estimatedCharset = estimatedCharset;
this.vcardVersion = vcardVersion;
this.entryCount = entryCount;
}
}
| {'repo_name': 'aosp-mirror/platform_packages_apps_contacts', 'stars': '285', 'repo_language': 'Java', 'file_name': 'test.sh', 'mime_type': 'text/x-shellscript', 'hash': 1986773448605138563, 'source_dataset': 'data'} |
package io.fabric8.servicecatalog.examples; /**
* Copyright (C) 2015 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import io.fabric8.servicecatalog.api.model.ClusterServiceClassList;
import io.fabric8.servicecatalog.client.ServiceCatalogClient;
public class ListServiceClasses {
public static void main(String[] args) {
ServiceCatalogClient client = ClientFactory.newClient(args);
System.out.println("Listing Cluster Service Classes:");
ClusterServiceClassList list = client.clusterServiceClasses().list();
list.getItems().stream()
.forEach(b -> {
System.out.println(b.getSpec().getClusterServiceBrokerName() + "\t\t" + b.getSpec().getExternalName() + "\t\t\t\t" + b.getMetadata().getName());
});
System.out.println("Done");
}
}
| {'repo_name': 'fabric8io/kubernetes-client', 'stars': '1437', 'repo_language': 'Java', 'file_name': 'StarList.java', 'mime_type': 'text/x-java', 'hash': -6484085143469133711, 'source_dataset': 'data'} |
{
"a": "http://www.google.com?search=noprivacy",
"b": "http://www.google.com?search=noprivacy"
}
| {'repo_name': 'sksamuel/hoplite', 'stars': '222', 'repo_language': 'Kotlin', 'file_name': 'com.sksamuel.hoplite.decoder.Decoder', 'mime_type': 'text/plain', 'hash': 7495322746298575795, 'source_dataset': 'data'} |
# make sure that your dns has a cname set for pydio-cells
server {
listen 443 ssl;
listen [::]:443 ssl;
server_name pydio-cells.*;
include /config/nginx/ssl.conf;
client_max_body_size 0;
# enable for ldap auth, fill in ldap details in ldap.conf
#include /config/nginx/ldap.conf;
# enable for Authelia
#include /config/nginx/authelia-server.conf;
location / {
# enable the next two lines for http auth
#auth_basic "Restricted";
#auth_basic_user_file /config/nginx/.htpasswd;
# enable the next two lines for ldap auth
#auth_request /auth;
#error_page 401 =200 /ldaplogin;
# enable for Authelia
#include /config/nginx/authelia-location.conf;
include /config/nginx/proxy.conf;
resolver 127.0.0.11 valid=30s;
set $upstream_app pydio-cells;
set $upstream_port 8080;
set $upstream_proto https;
proxy_pass $upstream_proto://$upstream_app:$upstream_port;
}
location /ws {
# enable the next two lines for http auth
#auth_basic "Restricted";
#auth_basic_user_file /config/nginx/.htpasswd;
# enable the next two lines for ldap auth
#auth_request /auth;
#error_page 401 =200 /ldaplogin;
# enable for Authelia
#include /config/nginx/authelia-location.conf;
include /config/nginx/proxy.conf;
resolver 127.0.0.11 valid=30s;
set $upstream_app pydio-cells;
set $upstream_port 8080;
set $upstream_proto https;
proxy_pass $upstream_proto://$upstream_app:$upstream_port;
proxy_buffering off;
}
}
| {'repo_name': 'linuxserver/reverse-proxy-confs', 'stars': '251', 'repo_language': 'None', 'file_name': 'allowed_names.yml', 'mime_type': 'text/plain', 'hash': 4127496777786250092, 'source_dataset': 'data'} |
import { Observable } from 'rxjs';
import { User } from './user';
import { Message } from './message';
export interface IFileUploadAdapter
{
uploadFile(file: File, participantId: any): Observable<Message>;
}
| {'repo_name': 'rpaschoal/ng-chat', 'stars': '111', 'repo_language': 'TypeScript', 'file_name': 'app.e2e-spec.ts', 'mime_type': 'text/x-java', 'hash': -5875596455712882967, 'source_dataset': 'data'} |
$MeshFormat
2.1 0 8
$EndMeshFormat
$Nodes
552
1 0.1 -0.3 0
2 0.6 -0.3 0
3 0.1 0.1 0
4 0.6 0.1 0
5 0.1208333333332611 -0.3 0
6 0.1416666666665221 -0.3 0
7 0.1624999999997832 -0.3 0
8 0.1833333333330442 -0.3 0
9 0.2041666666663053 -0.3 0
10 0.2249999999995663 -0.3 0
11 0.2458333333328274 -0.3 0
12 0.2666666666660884 -0.3 0
13 0.2874999999993495 -0.3 0
14 0.3083333333326105 -0.3 0
15 0.3291666666658716 -0.3 0
16 0.3499999999991327 -0.3 0
17 0.3708333333324515 -0.3 0
18 0.3916666666657704 -0.3 0
19 0.4124999999990893 -0.3 0
20 0.4333333333324082 -0.3 0
21 0.454166666665727 -0.3 0
22 0.4749999999990459 -0.3 0
23 0.4958333333325383 -0.3 0
24 0.5166666666660306 -0.3 0
25 0.5374999999995229 -0.3 0
26 0.5583333333330153 -0.3 0
27 0.5791666666665076 -0.3 0
28 0.1208333333332611 0.1 0
29 0.1416666666665221 0.1 0
30 0.1624999999997832 0.1 0
31 0.1833333333330442 0.1 0
32 0.2041666666663053 0.1 0
33 0.2249999999995663 0.1 0
34 0.2458333333328274 0.1 0
35 0.2666666666660884 0.1 0
36 0.2874999999993495 0.1 0
37 0.3083333333326105 0.1 0
38 0.3291666666658716 0.1 0
39 0.3499999999991327 0.1 0
40 0.3708333333324515 0.1 0
41 0.3916666666657704 0.1 0
42 0.4124999999990893 0.1 0
43 0.4333333333324082 0.1 0
44 0.454166666665727 0.1 0
45 0.4749999999990459 0.1 0
46 0.4958333333325383 0.1 0
47 0.5166666666660306 0.1 0
48 0.5374999999995229 0.1 0
49 0.5583333333330153 0.1 0
50 0.5791666666665076 0.1 0
51 0.1 -0.2789473684211074 0
52 0.1 -0.2578947368422148 0
53 0.1 -0.2368421052633222 0
54 0.1 -0.2157894736844296 0
55 0.1 -0.1947368421055279 0
56 0.1 -0.1736842105265988 0
57 0.1 -0.1526315789476697 0
58 0.1 -0.1315789473687406 0
59 0.1 -0.1105263157898115 0
60 0.1 -0.08947368421084587 0
61 0.1 -0.06842105263184373 0
62 0.1 -0.04736842105284156 0
63 0.1 -0.02631578947383945 0
64 0.1 -0.005263157894837278 0
65 0.1 0.01578947368413747 0
66 0.1 0.03684210526310311 0
67 0.1 0.05789473684206875 0
68 0.1 0.07894736842103439 0
69 0.6 -0.2789473684211074 0
70 0.6 -0.2578947368422148 0
71 0.6 -0.2368421052633222 0
72 0.6 -0.2157894736844296 0
73 0.6 -0.1947368421055279 0
74 0.6 -0.1736842105265988 0
75 0.6 -0.1526315789476697 0
76 0.6 -0.1315789473687406 0
77 0.6 -0.1105263157898115 0
78 0.6 -0.08947368421084587 0
79 0.6 -0.06842105263184373 0
80 0.6 -0.04736842105284156 0
81 0.6 -0.02631578947383945 0
82 0.6 -0.005263157894837278 0
83 0.6 0.01578947368413747 0
84 0.6 0.03684210526310311 0
85 0.6 0.05789473684206875 0
86 0.6 0.07894736842103439 0
87 0.2470719077479455 -0.08137746849645747 0
88 0.3054058064435218 -0.1012342697436091 0
89 0.4380697339231016 -0.0827118221232104 0
90 0.3807942613624612 -0.09678276730759705 0
91 0.5198469101507254 -0.1231687440773327 0
92 0.1802622630417262 -0.123171984374864 0
93 0.4825700977066876 -0.2070684945454482 0
94 0.2015298637981154 -0.006993569505099995 0
95 0.2165436539135884 -0.2017891299473061 0
96 0.5204030848169011 -0.2175389816731 0
97 0.1874205002459193 0.02891264865738236 0
98 0.1763264909436028 -0.2205792713186028 0
99 0.1654833561015513 0.04021905283900101 0
100 0.1628145777279844 -0.2342731739828429 0
101 0.5320703325620801 0.03736745274485404 0
102 0.1189937521102307 0.06892609331402982 0
103 0.5810058730852516 0.06892610391816889 0
104 0.5835638075422199 -0.2651991384269491 0
105 0.2790859505232555 -0.1898971686883984 0
106 0.3192244036865693 -0.1988121468199329 0
107 0.387263330538928 -0.1888443385362997 0
108 0.3437254937791907 -0.1998696557697752 0
109 0.3347408414814464 -0.02763455676175131 0
110 0.3003960377931847 0.001113778029359358 0
111 0.3794612890415798 -0.004964897638084942 0
112 0.2617711321386343 0.002723371253666118 0
113 0.2451823476113867 -0.2602732211099869 0
114 0.1832187596039515 -0.07280090247561771 0
115 0.516705735256796 -0.07281741773760697 0
116 0.4634798923975467 -0.15153968344229 0
117 0.2365231641201183 -0.1419063810242819 0
118 0.4729056839404947 -0.05467848701170441 0
119 0.4682429113758851 0.05483288406416553 0
120 0.2279521428057974 0.04934382519953762 0
121 0.4573001234641445 -0.248854286806804 0
122 0.2221082629691096 -0.2583174609067478 0
123 0.4778470795289662 -0.0990587139155909 0
124 0.2186683837114814 -0.0996928867129464 0
125 0.5594022964206263 -0.04395801020445422 0
126 0.1405724266801488 -0.04395927433734265 0
127 0.20062887066475 -0.2579607475238861 0
128 0.4987369404434219 0.05871198101497743 0
129 0.5003501315124206 -0.2537641218733945 0
130 0.5612585538931373 -0.1919010986231683 0
131 0.5542773721131288 -0.0007939083535721814 0
132 0.1457037833119315 -0.0007944138633162456 0
133 0.5587108015918932 -0.09716416749419243 0
134 0.1413107984311285 -0.09720288029856577 0
135 0.1817323872938597 -0.1726229214780654 0
136 0.5191301480116987 -0.1714711231846025 0
137 0.5578814576784318 -0.1456004511896953 0
138 0.1422158922602929 -0.1459386744175477 0
139 0.5724526303831008 0.03073084889400651 0
140 0.1275439297858139 0.03073075404948794 0
141 0.4131918220554367 -0.1126151493976764 0
142 0.5854100782110143 -0.2475916495007203 0
143 0.5854600785583737 0.04636933659691583 0
144 0.1215335301147904 -0.2466810040680078 0
145 0.1145391606516862 0.04636931553742768 0
146 0.3478817589993298 -0.1116942157170982 0
147 0.1474715579929102 0.05652193886658563 0
148 0.1541326657436418 -0.2558880173235988 0
149 0.5525186987486118 0.05652219524713581 0
150 0.296383692106492 -0.146017220508318 0
151 0.4145880145186823 -0.03727205463234201 0
152 0.4311321455285507 -0.1742926296292673 0
153 0.2636635332699749 0.0473248817014032 0
154 0.3146598861194549 0.04023374717783718 0
155 0.4351007452118419 0.04141500583359453 0
156 0.3580365457706112 0.04870705599351999 0
157 0.3136308694716773 -0.1790373984143993 0
158 0.2702324007238833 -0.2395538729946796 0
159 0.3854169827984786 -0.2464135537686218 0
160 0.382068336740565 -0.05044713274513948 0
161 0.310090619029229 -0.2475718817115574 0
162 0.2947461683999582 -0.03167967213783296 0
163 0.2678186396306346 -0.1248905079285385 0
164 0.3649507914904094 -0.1501421863408875 0
165 0.3444788268639593 -0.07002643238559164 0
166 0.3222677957187681 -0.06952312580561676 0
167 0.3317467879693237 -0.1704787909334478 0
168 0.4504712142226927 -0.04424826882537825 0
169 0.2564259357085437 -0.04181863002114222 0
170 0.4550608719704144 -0.178787274551921 0
171 0.4850348383381963 0.01806653735461716 0
172 0.2602171723662765 -0.1595076030010912 0
173 0.2237299587107645 -0.1808100049645664 0
174 0.5347712792554061 -0.03112529487482307 0
175 0.1651542866344013 -0.03112598512087633 0
176 0.2584495932589829 -0.2220086368379338 0
177 0.4696627122385009 -0.02883447515053511 0
178 0.235532611614233 -0.02646548990050201 0
179 0.3423185622406266 0.01195478675571393 0
180 0.4266224365883683 -0.1284932778163518 0
181 0.2304274506617864 0.009501860026812525 0
182 0.4606115894802353 -0.1123931953172367 0
183 0.4779092664012362 -0.1837945873312068 0
184 0.2383915397252227 -0.102823678673501 0
185 0.1882872624215261 -0.04578338937091009 0
186 0.5149704931383053 -0.04820288963204311 0
187 0.2407163518851088 0.02409921070413162 0
188 0.4190093996273253 0.00892740689825855 0
189 0.451662772368407 -0.230377427480022 0
190 0.2415447630610819 -0.202946736051072 0
191 0.1599316915193432 -0.1597368199399238 0
192 0.5404206058567622 -0.1592563737198348 0
193 0.2569820637951829 0.07999017628715432 0
194 0.5414933406809067 -0.1090260399059521 0
195 0.1585471262723042 -0.1090573884819125 0
196 0.4445425957085896 0.08090881199418581 0
197 0.4896962222767453 0.04404914586342029 0
198 0.2044208309265129 0.04978763190867314 0
199 0.2057601134422185 -0.1605539077618815 0
200 0.2024051576984777 -0.1879125837023813 0
201 0.4945989582600112 -0.164093080572191 0
202 0.4571350989461092 -0.2128889121531545 0
203 0.1384055182774142 -0.174519330613215 0
204 0.5575928256294952 -0.1698628075286041 0
205 0.5367533516397638 -0.05823733230119735 0
206 0.1631979286313223 -0.05823485558085245 0
207 0.4095248868877049 -0.2170486548294097 0
208 0.5393057793282089 -0.08408122103645879 0
209 0.1606822856937659 -0.08408608124385453 0
210 0.5415479047071574 -0.134029401468623 0
211 0.1586432300182706 -0.1342604708046178 0
212 0.2007330693685805 -0.1331862443565051 0
213 0.4951459574517622 -0.1366534637096468 0
214 0.148361763293995 -0.0214154550044261 0
215 0.551610261401662 -0.02141486335099324 0
216 0.2105593006119023 -0.02319633085624306 0
217 0.1800077423995289 -0.09761590440942769 0
218 0.5199658559830188 -0.0976471578547182 0
219 0.5335763403406618 -0.005990808310083251 0
220 0.1650229342466775 -0.005918582790681415 0
221 0.1420369139604128 -0.1206045967119691 0
222 0.5580392764563916 -0.1204792369475866 0
223 0.4817841780657586 -0.1180466665833448 0
224 0.2189305015320431 -0.1179410837029307 0
225 0.4992848055436896 -0.1883455199774064 0
226 0.4798292485157329 -0.2543563749259062 0
227 0.491440950544442 -0.2313428110743826 0
228 0.5770235183546231 0.005925276491096254 0
229 0.1229719271092318 0.005925130330095008 0
230 0.1933854823498121 -0.2782676627958575 0
231 0.2799254084445171 0.01136488368166572 0
232 0.4676294127195404 0.07917997870032589 0
233 0.2359220176393671 0.08207389855414837 0
234 0.1814572863726601 -0.1477470992952904 0
235 0.1594070730018736 -0.1869650742746907 0
236 0.5383003908396882 -0.1822526092274951 0
237 0.1373764931764753 -0.07088559646655707 0
238 0.5626145793837435 -0.07087684542590444 0
239 0.5188670404570978 -0.1477445518941722 0
240 0.4996411157626124 -0.1104935267377833 0
241 0.2001427282969873 -0.1098934071100772 0
242 0.1801722808582999 -0.1984524461312528 0
243 0.5194741146852119 -0.195615106777291 0
244 0.2880197303451612 -0.2089113565489933 0
245 0.5132029750226569 0.05075070718581048 0
246 0.1817723075726017 0.04987151470149254 0
247 0.4956795861748466 -0.06322610978849294 0
248 0.2073462435879014 -0.06553295549931695 0
249 0.4753825905749132 -0.07693326431910583 0
250 0.2188941867582095 -0.08132182130733684 0
251 0.3560292297653906 -0.02538091283425259 0
252 0.3909873875037051 -0.1148656838693399 0
253 0.4366621795010527 -0.1052599015848514 0
254 0.1615610745708875 -0.2116555990534352 0
255 0.5405571904312237 -0.2089474504998186 0
256 0.2332316876291905 -0.08643737850052596 0
257 0.182914339430918 0.006461469723815672 0
258 0.2310652080501569 -0.06697552341442756 0
259 0.4985550681668193 -0.08652128449448837 0
260 0.2012050595596787 -0.08633266615724927 0
261 0.5824909171979321 -0.036852836900579 0
262 0.1175021543154942 -0.03685337686312096 0
263 0.197443899141035 -0.216502492109265 0
264 0.487038802679724 0.06679085646457367 0
265 0.530726927584745 -0.2323119596450132 0
266 0.1993170955177949 0.07809717436735908 0
267 0.5041995514042518 0.08082875602526257 0
268 0.5428468156153935 0.01633778597829938 0
269 0.1629341725153253 0.017923692290994 0
270 0.5635755466339785 -0.2124337956237184 0
271 0.1251805973208769 -0.2228048761642643 0
272 0.1863084709505568 -0.2405697458137157 0
273 0.5030168987116159 -0.2129535849715932 0
274 0.3675120257512331 -0.2068182504361809 0
275 0.25686637968739 -0.2802761980599133 0
276 0.5862723680778825 0.02504408643147388 0
277 0.1137274780979562 0.02504408239342404 0
278 0.1714610131559637 -0.2579628524310755 0
279 0.5782913092194693 -0.228391520205303 0
280 0.5173799561532465 -0.2671418414042163 0
281 0.4494721725739133 -0.2835827436694323 0
282 0.5370734843178807 -0.2801497243047565 0
283 0.1593400542233345 -0.2781651816142711 0
284 0.1413434304305956 0.01620554553172976 0
285 0.5586477876493181 0.01620578688571717 0
286 0.5636336482017106 0.06740736467477115 0
287 0.1215534795913843 -0.2675612781311328 0
288 0.1363619062594731 0.0674072500764466 0
289 0.5149819318026856 0.06733882389802731 0
290 0.1849270212969133 0.06454495124718679 0
291 0.5311254375152917 0.06244125652192156 0
292 0.1688501764097003 0.06242411191950437 0
293 0.143541284355881 -0.2386296995685909 0
294 0.1867097904335954 -0.2627025000011893 0
295 0.5546955455456238 0.03673021982803631 0
296 0.1452910417903854 0.0367298508233751 0
297 0.1156815080701525 0.08670168902463288 0
298 0.5843182977128956 0.08670169451950488 0
299 0.3237587291321095 -0.1075642455009612 0
300 0.3681057939284768 0.0301784725846817 0
301 0.2762774702751046 0.06496007582201724 0
302 0.3478738301065293 -0.1797026739954325 0
303 0.3140231231857372 -0.2288176321183975 0
304 0.3488703448396974 0.02976713824299132 0
305 0.3827698985311671 -0.2644155069715744 0
306 0.2956406430826921 0.02412599743795762 0
307 0.3877438679418611 0.03109086685660661 0
308 0.3194589947215258 0.07518403149153546 0
309 0.2901431717442604 -0.1707102898926918 0
310 0.3478338853939874 -0.2415627160714393 0
311 0.2910057877467748 -0.05564003781646282 0
312 0.3128177229794354 0.01944470965623574 0
313 0.397364003148205 -0.01935820703307306 0
314 0.3980141667344105 -0.1651977621440555 0
315 0.3297339350647762 0.02688735292989453 0
316 0.3373743880628577 0.04515445878343649 0
317 0.3793550401124548 -0.02762190857886171 0
318 0.43027884780404 -0.05995275247488185 0
319 0.4123238823377445 -0.01049947918902278 0
320 0.4489298632289699 -0.1609142797793623 0
321 0.3801438896658932 -0.07332710287948313 0
322 0.2775443872500318 -0.1545300975889424 0
323 0.3779253958899513 -0.1676923884743768 0
324 0.3074319044628698 -0.1242600159451257 0
325 0.2902053826971753 0.04699940253626361 0
326 0.3885727530591737 -0.2128666826587368 0
327 0.1184348881212325 -0.01867058938835825 0
328 0.5815622920193261 -0.01867042151261827 0
329 0.4159481216598044 -0.2861847245971875 0
330 0.264827705930688 -0.1428087962384344 0
331 0.3699949380923762 -0.1154542484306769 0
332 0.2515179376813041 -0.1333321414087978 0
333 0.3779782892187462 -0.1322748200528393 0
334 0.4786933441064701 -0.2809249145226345 0
335 0.4078949835853682 -0.06286024332217924 0
336 0.2775434527311128 0.03224832754650192 0
337 0.4313059608597757 -0.1501128509621149 0
338 0.3284264743227941 -0.2504861283914895 0
339 0.2592599008826436 -0.01951635330575408 0
340 0.4085632986984312 -0.1811788371383644 0
341 0.4075006205889878 0.03078657791346423 0
342 0.2984982974792999 -0.2292466379135067 0
343 0.416998496514623 -0.2373580581312496 0
344 0.3474164366637032 -0.160627366118885 0
345 0.3916914669379127 -0.06279186921429208 0
346 0.4336178913146358 -0.2171584841251336 0
347 0.3609366369303569 0.009013645057837416 0
348 0.3589361976495119 -0.1302942742821778 0
349 0.4018034560616576 -0.253846603291459 0
350 0.5851199273624909 -0.07409792156921485 0
351 0.1148789742363733 -0.07410265148839218 0
352 0.3762813941892997 0.04726207549444023 0
353 0.3445015999744213 -0.007645960943807928 0
354 0.4330465542374927 -0.01764742381140755 0
355 0.3712266440262721 -0.2309404456265208 0
356 0.2367127436777742 -0.1244714240448793 0
357 0.2399877132698292 -0.2263234996608563 0
358 0.3963128826375437 -0.2332062881041287 0
359 0.3892238334344216 -0.1486847430910197 0
360 0.3600980843285077 -0.08183319943784845 0
361 0.4208453141488814 -0.1963416012750623 0
362 0.3993029922718296 -0.0986539596482276 0
363 0.43691721759461 0.05930178718823226 0
364 0.4268594773607396 0.0263554511145101 0
365 0.2837693614115718 -0.1303874322015937 0
366 0.2680339734408866 -0.2070410573920922 0
367 0.3346213824849245 -0.05002936488232471 0
368 0.3318799681758446 -0.1877370536223426 0
369 0.3659241231792917 -0.2528598871796974 0
370 0.221664115437801 0.03057449093109949 0
371 0.3591123670238647 -0.05828127019749546 0
372 0.1386388884167461 -0.2568375004300809 0
373 0.4694552583722905 -0.1662815029076221 0
374 0.4167503287836993 -0.162910340931928 0
375 0.2758564452960229 -0.03721507577157912 0
376 0.1250869638309363 -0.1546200335389243 0
377 0.273654274217309 -0.1091176587594838 0
378 0.2287568943740908 -0.1578717714060935 0
379 0.5790094382176659 -0.1595653757508888 0
380 0.2812512535028651 -0.01285271689098855 0
381 0.2343770145792093 -0.2779292419571518 0
382 0.4624327448853782 -0.27082257483671 0
383 0.3650322141443969 -0.01081845109455953 0
384 0.3147445954159115 -0.01724144118643633 0
385 0.3128919544243079 -0.1605609513027727 0
386 0.4480137208835026 -0.1410474705955659 0
387 0.5671392917518243 -0.02765692129406805 0
388 0.13284963124034 -0.02765731426650581 0
389 0.3017812258086763 -0.07803572097509906 0
390 0.4572977549276672 -0.0905175862514101 0
391 0.2596739085087594 0.02399427857884567 0
392 0.3965698041612297 -0.08003966418592079 0
393 0.4462393603140938 0.02667214741572049 0
394 0.2470030260636412 -0.1749176718498492 0
395 0.2614786022810033 -0.1905524734091 0
396 0.4538981489749822 0.06362019328434887 0
397 0.4495978210454092 0.04814420100953215 0
398 0.4568131475743373 -0.0127433040596916 0
399 0.4790399286715761 -0.1506380560115749 0
400 0.3217020849367068 -0.1426864315174425 0
401 0.4032617700220035 -0.1995963639305325 0
402 0.435610704330085 -0.03774971575097019 0
403 0.4192641338172197 0.05090155929347451 0
404 0.2533613328906044 -0.2416645127720604 0
405 0.2873983651779671 -0.2460470035774236 0
406 0.2481409834226865 -0.1517240608214247 0
407 0.3968104565872232 0.006444942462022374 0
408 0.3433026865583973 -0.1441985669445826 0
409 0.4374523122078284 0.004461737993574078 0
410 0.454351121232331 -0.06747673360678344 0
411 0.3648777290866666 -0.03996858832826466 0
412 0.1219197890337412 -0.1126310414020587 0
413 0.5781056448582823 -0.1125813943143051 0
414 0.2540285253378048 -0.1150170495365831 0
415 0.2312000243781364 -0.2411436733940649 0
416 0.3396018612498287 -0.09057782888722404 0
417 0.4106091685960598 -0.1480717752822652 0
418 0.3963998654041049 -0.04414071220187971 0
419 0.4488638357939765 -0.1235860030055168 0
420 0.2996852384433821 -0.1935337587203062 0
421 0.1766846873222137 -0.2795479892086654 0
422 0.553318977393653 -0.2320757100570558 0
423 0.5663225471281128 -0.01252216760403108 0
424 0.1336643986153462 -0.01252252843850227 0
425 0.3584549436442821 -0.09910985152207424 0
426 0.20894509356459 -0.2392883368623654 0
427 0.2785939249083977 -0.2275239254273334 0
428 0.5807584921994017 -0.09245338813404572 0
429 0.1192476758129531 -0.09247036160937186 0
430 0.468118396912116 -0.1328597369932328 0
431 0.3314119901104878 -0.1557104213634261 0
432 0.4178004186731393 -0.08604968648697001 0
433 0.1747990722411374 0.08082946309006411 0
434 0.5252102406422638 0.08085877273283898 0
435 0.3239774453503643 0.003140705388990528 0
436 0.4965918336843311 -0.2740436415931158 0
437 0.1218765931808972 -0.1363341453978184 0
438 0.578044045894423 -0.1361944353417987 0
439 0.4658061604528562 0.03203291456631308 0
440 0.5667319726254546 -0.2491016766145728 0
441 0.4623294454932818 -0.1942627813158794 0
442 0.1408876142374954 -0.2744646106401465 0
443 0.1475579127878978 -0.2222094507404579 0
444 0.5816046200607988 -0.05692918129747301 0
445 0.1183883414014153 -0.05693172880668301 0
446 0.2226108578880435 -0.2213323113374883 0
447 0.5797488674457801 -0.1822867699391316 0
448 0.2078540015643902 0.01238766024688226 0
449 0.2212360810858042 -0.1393218020494286 0
450 0.114768974932794 -0.1747545843759475 0
451 0.2132777162047921 -0.2787458521972739 0
452 0.2696638854074868 -0.1737225983631182 0
453 0.5682944124204453 0.05111434485983907 0
454 0.1317002247650833 0.05111420044455883 0
455 0.3338355602898209 -0.126782958317898 0
456 0.4702971783555264 -0.2319729753472621 0
457 0.5475305139703596 0.07894257321022324 0
458 0.1524649899655459 0.0789358206866107 0
459 0.243663070881699 -0.006023400427532355 0
460 0.401435489566123 -0.1308342415849154 0
461 0.5163586024921024 -0.02208414484714499 0
462 0.1356055501892949 0.08536798085367436 0
463 0.5643922393521007 0.0853684232948953 0
464 0.4254580371025978 -0.003689439527149452 0
465 0.1875143928045893 -0.02001826043940608 0
466 0.3390272295195588 0.0804195878638661 0
467 0.4231917239930276 0.07652907883595578 0
468 0.4343076941402696 -0.2796474780558705 0
469 0.1205999666742913 -0.1972160661428448 0
470 0.348451299854877 0.06327558830952407 0
471 0.300463487444627 0.08067714257581554 0
472 0.3614201276680709 -0.2731033542615865 0
473 0.5806323869343822 -0.2039702851000014 0
474 0.3993084635477278 -0.2753400264891159 0
475 0.2188339680728794 0.08510638355232975 0
476 0.3603487411929295 -0.2890623824964181 0
477 0.3700631589021932 0.06391147164688787 0
478 0.2977593284257806 -0.2882283470638418 0
479 0.3074596867031508 0.06075857943813689 0
480 0.2392163212405668 -0.04865291393591931 0
481 0.4437534402683238 -0.263746659674865 0
482 0.2911866300648628 -0.1119713232131259 0
483 0.2975103392953702 -0.2682558011436676 0
484 0.2215943831886877 -0.006798211735947135 0
485 0.4859402200270201 0.08535991823803246 0
486 0.3158820537071412 -0.2840548817758419 0
487 0.4473907116655629 -0.02723028020181606 0
488 0.3226237270252517 -0.2661241027496615 0
489 0.2441439645479748 0.06093504071214656 0
490 0.318669945312813 -0.08870455602246327 0
491 0.4211834616637961 -0.2617021022020098 0
492 0.3402474776560653 -0.2822026989194442 0
493 0.4640373421146681 0.008828418029357687 0
494 0.2420796334199177 0.03934796712607519 0
495 0.3285611080993543 -0.2345496501568006 0
496 0.3777245384896862 -0.2836535450364491 0
497 0.4433534612336455 -0.1956219471750697 0
498 0.5192033729156242 -0.2499387236419888 0
499 0.3267592148340696 -0.2164565029981947 0
500 0.4639529856461069 -0.2870660466057554 0
501 0.3077016679957033 -0.2126296725198886 0
502 0.3787258762858586 0.01403056887818516 0
503 0.3650771564723788 -0.1863692822296029 0
504 0.2467570898560585 0.01035456256806727 0
505 0.2158771014306959 -0.04431114830473804 0
506 0.2700860463387685 -0.2601459542912364 0
507 0.2718728731801019 -0.08947751810794308 0
508 0.2517474092479106 -0.06221511432503929 0
509 0.2775779376360704 0.0851254789369974 0
510 0.3444126358742435 -0.2610564812622197 0
511 0.3606487221245944 -0.1689067794318369 0
512 0.4374193642656551 -0.243199503070014 0
513 0.4936215319439412 -0.03581591710878024 0
514 0.3495063438103042 -0.04004627975487346 0
515 0.540460277601195 -0.2532191061354495 0
516 0.2793981267354578 -0.2828177167597765 0
517 0.5103947823476116 -0.2342318388105872 0
518 0.3284881888751742 0.06113950738377066 0
519 0.2936015067800144 0.06334880009305827 0
520 0.2602667579720593 0.06330254363068033 0
521 0.1430314873132779 -0.2022663336821967 0
522 0.3476030619806845 -0.2216995368431519 0
523 0.221765003251721 0.06755732571569911 0
524 0.4794281628406113 -0.00650144626129523 0
525 0.2005595143171784 -0.03332728224282433 0
526 0.2047618893325101 0.03059389555589737 0
527 0.2814023849023234 -0.07526746830954451 0
528 0.2582399993086008 -0.09553732253008687 0
529 0.2701720298363758 -0.05784447357502029 0
530 0.263417767370543 -0.0769532275573486 0
531 0.4987550164993607 -0.01321099247121849 0
532 0.2877512317154054 -0.09412202482811011 0
533 0.3592546203184995 0.08267410081828219 0
534 0.3120376866076918 -0.05095409349111854 0
535 0.4023100050633032 0.07973304827238675 0
536 0.5074028815082758 0.02850138716114864 0
537 0.5016905579439696 0.007240317811589014 0
538 0.5148388065515286 -0.003907530948402738 0
539 0.4853668558806035 -0.02109070774795729 0
540 0.3825599885890572 0.0808609459311837 0
541 0.3065646354839715 -0.0625354884692001 0
542 0.5220709557536516 0.01325810073956751 0
543 0.3181781348779865 -0.03550782569189276 0
544 0.5801870548069371 -0.2855515812841702 0
545 0.3286838323563028 -0.01320007718349153 0
546 0.5613023503347262 -0.2724628014563293 0
547 0.3946520979103613 0.05630645590144001 0
548 0.2976474927183699 -0.01611339380505505 0
549 0.5168408790255917 -0.2868892012170148 0
550 0.409854490195978 0.06586753557581426 0
551 0.1225596267492156 -0.2850744902338234 0
552 0.1108482400206192 -0.2910054646637327 0
$EndNodes
$Elements
1102
1 1 3 7 1 0 1 5
2 1 3 7 1 0 5 6
3 1 3 7 1 0 6 7
4 1 3 7 1 0 7 8
5 1 3 7 1 0 8 9
6 1 3 7 1 0 9 10
7 1 3 7 1 0 10 11
8 1 3 7 1 0 11 12
9 1 3 7 1 0 12 13
10 1 3 7 1 0 13 14
11 1 3 7 1 0 14 15
12 1 3 7 1 0 15 16
13 1 3 7 1 0 16 17
14 1 3 7 1 0 17 18
15 1 3 7 1 0 18 19
16 1 3 7 1 0 19 20
17 1 3 7 1 0 20 21
18 1 3 7 1 0 21 22
19 1 3 7 1 0 22 23
20 1 3 7 1 0 23 24
21 1 3 7 1 0 24 25
22 1 3 7 1 0 25 26
23 1 3 7 1 0 26 27
24 1 3 7 1 0 27 2
25 1 3 9 2 0 3 28
26 1 3 9 2 0 28 29
27 1 3 9 2 0 29 30
28 1 3 9 2 0 30 31
29 1 3 9 2 0 31 32
30 1 3 9 2 0 32 33
31 1 3 9 2 0 33 34
32 1 3 9 2 0 34 35
33 1 3 9 2 0 35 36
34 1 3 9 2 0 36 37
35 1 3 9 2 0 37 38
36 1 3 9 2 0 38 39
37 1 3 9 2 0 39 40
38 1 3 9 2 0 40 41
39 1 3 9 2 0 41 42
40 1 3 9 2 0 42 43
41 1 3 9 2 0 43 44
42 1 3 9 2 0 44 45
43 1 3 9 2 0 45 46
44 1 3 9 2 0 46 47
45 1 3 9 2 0 47 48
46 1 3 9 2 0 48 49
47 1 3 9 2 0 49 50
48 1 3 9 2 0 50 4
49 1 3 10 3 0 1 51
50 1 3 10 3 0 51 52
51 1 3 10 3 0 52 53
52 1 3 10 3 0 53 54
53 1 3 10 3 0 54 55
54 1 3 10 3 0 55 56
55 1 3 10 3 0 56 57
56 1 3 10 3 0 57 58
57 1 3 10 3 0 58 59
58 1 3 10 3 0 59 60
59 1 3 10 3 0 60 61
60 1 3 10 3 0 61 62
61 1 3 10 3 0 62 63
62 1 3 10 3 0 63 64
63 1 3 10 3 0 64 65
64 1 3 10 3 0 65 66
65 1 3 10 3 0 66 67
66 1 3 10 3 0 67 68
67 1 3 10 3 0 68 3
68 1 3 8 4 0 2 69
69 1 3 8 4 0 69 70
70 1 3 8 4 0 70 71
71 1 3 8 4 0 71 72
72 1 3 8 4 0 72 73
73 1 3 8 4 0 73 74
74 1 3 8 4 0 74 75
75 1 3 8 4 0 75 76
76 1 3 8 4 0 76 77
77 1 3 8 4 0 77 78
78 1 3 8 4 0 78 79
79 1 3 8 4 0 79 80
80 1 3 8 4 0 80 81
81 1 3 8 4 0 81 82
82 1 3 8 4 0 82 83
83 1 3 8 4 0 83 84
84 1 3 8 4 0 84 85
85 1 3 8 4 0 85 86
86 1 3 8 4 0 86 4
87 2 3 11 5 0 67 102 68
88 2 3 11 5 0 103 85 86
89 2 3 11 5 0 70 104 69
90 2 3 11 5 0 70 142 104
91 2 3 11 5 0 143 85 103
92 2 3 11 5 0 67 145 102
93 2 3 11 5 0 71 142 70
94 2 3 11 5 0 143 84 85
95 2 3 11 5 0 144 53 52
96 2 3 11 5 0 66 145 67
97 2 3 11 5 0 118 177 168
98 2 3 11 5 0 200 95 173
99 2 3 11 5 0 138 203 191
100 2 3 11 5 0 204 137 192
101 2 3 11 5 0 205 125 174
102 2 3 11 5 0 126 206 175
103 2 3 11 5 0 133 208 194
104 2 3 11 5 0 115 208 205
105 2 3 11 5 0 209 134 195
106 2 3 11 5 0 209 114 206
107 2 3 11 5 0 137 210 192
108 2 3 11 5 0 91 210 194
109 2 3 11 5 0 211 138 191
110 2 3 11 5 0 211 92 195
111 2 3 11 5 0 214 126 175
112 2 3 11 5 0 125 215 174
113 2 3 11 5 0 92 217 195
114 2 3 11 5 0 218 91 194
115 2 3 11 5 0 134 221 195
116 2 3 11 5 0 222 133 194
117 2 3 11 5 0 223 123 182
118 2 3 11 5 0 124 224 184
119 2 3 11 5 0 93 225 183
120 2 3 11 5 0 234 135 199
121 2 3 11 5 0 135 234 191
122 2 3 11 5 0 235 135 191
123 2 3 11 5 0 136 236 192
124 2 3 11 5 0 126 237 206
125 2 3 11 5 0 238 125 205
126 2 3 11 5 0 136 239 201
127 2 3 11 5 0 239 136 192
128 2 3 11 5 0 91 240 213
129 2 3 11 5 0 240 91 218
130 2 3 11 5 0 241 92 212
131 2 3 11 5 0 92 241 217
132 2 3 11 5 0 242 135 235
133 2 3 11 5 0 135 242 200
134 2 3 11 5 0 136 243 236
135 2 3 11 5 0 243 136 225
136 2 3 11 5 0 245 128 197
137 2 3 11 5 0 246 97 198
138 2 3 11 5 0 247 115 186
139 2 3 11 5 0 114 248 185
140 2 3 11 5 0 118 249 247
141 2 3 11 5 0 253 141 180
142 2 3 11 5 0 255 130 236
143 2 3 11 5 0 87 256 184
144 2 3 11 5 0 124 256 250
145 2 3 11 5 0 256 124 184
146 2 3 11 5 0 115 259 218
147 2 3 11 5 0 259 115 247
148 2 3 11 5 0 260 114 217
149 2 3 11 5 0 114 260 248
150 2 3 11 5 0 263 95 200
151 2 3 11 5 0 264 119 197
152 2 3 11 5 0 128 264 197
153 2 3 11 5 0 119 264 232
154 2 3 11 5 0 93 273 225
155 2 3 11 5 0 273 93 227
156 2 3 11 5 0 276 84 143
157 2 3 11 5 0 139 276 143
158 2 3 11 5 0 66 277 145
159 2 3 11 5 0 277 140 145
160 2 3 11 5 0 278 100 148
161 2 3 11 5 0 71 279 142
162 2 3 11 5 0 100 293 148
163 2 3 11 5 0 101 295 149
164 2 3 11 5 0 296 99 147
165 2 3 11 5 0 297 28 3
166 2 3 11 5 0 297 68 102
167 2 3 11 5 0 68 297 3
168 2 3 11 5 0 50 298 4
169 2 3 11 5 0 86 298 103
170 2 3 11 5 0 298 86 4
171 2 3 11 5 0 190 173 95
172 2 3 11 5 0 200 199 135
173 2 3 11 5 0 173 199 200
174 2 3 11 5 0 205 186 115
175 2 3 11 5 0 174 186 205
176 2 3 11 5 0 219 215 131
177 2 3 11 5 0 174 215 219
178 2 3 11 5 0 185 206 114
179 2 3 11 5 0 185 175 206
180 2 3 11 5 0 214 220 132
181 2 3 11 5 0 214 175 220
182 2 3 11 5 0 227 226 129
183 2 3 11 5 0 201 225 136
184 2 3 11 5 0 201 183 225
185 2 3 11 5 0 211 234 92
186 2 3 11 5 0 211 191 234
187 2 3 11 5 0 191 203 235
188 2 3 11 5 0 239 210 91
189 2 3 11 5 0 192 210 239
190 2 3 11 5 0 204 236 130
191 2 3 11 5 0 204 192 236
192 2 3 11 5 0 222 210 137
193 2 3 11 5 0 194 210 222
194 2 3 11 5 0 218 208 115
195 2 3 11 5 0 194 208 218
196 2 3 11 5 0 211 221 138
197 2 3 11 5 0 211 195 221
198 2 3 11 5 0 209 217 114
199 2 3 11 5 0 209 195 217
200 2 3 11 5 0 234 212 92
201 2 3 11 5 0 199 212 234
202 2 3 11 5 0 263 242 98
203 2 3 11 5 0 200 242 263
204 2 3 11 5 0 213 239 91
205 2 3 11 5 0 213 201 239
206 2 3 11 5 0 238 208 133
207 2 3 11 5 0 205 208 238
208 2 3 11 5 0 209 237 134
209 2 3 11 5 0 209 206 237
210 2 3 11 5 0 241 224 124
211 2 3 11 5 0 212 224 241
212 2 3 11 5 0 223 240 123
213 2 3 11 5 0 223 213 240
214 2 3 11 5 0 260 241 124
215 2 3 11 5 0 217 241 260
216 2 3 11 5 0 240 259 123
217 2 3 11 5 0 240 218 259
218 2 3 11 5 0 243 273 96
219 2 3 11 5 0 243 225 273
220 2 3 11 5 0 255 243 96
221 2 3 11 5 0 236 243 255
222 2 3 11 5 0 259 249 123
223 2 3 11 5 0 247 249 259
224 2 3 11 5 0 250 260 124
225 2 3 11 5 0 250 248 260
226 2 3 11 5 0 258 256 87
227 2 3 11 5 0 250 256 258
228 2 3 11 5 0 284 296 140
229 2 3 11 5 0 295 285 139
230 2 3 11 5 0 99 296 269
231 2 3 11 5 0 284 132 269
232 2 3 11 5 0 284 269 296
233 2 3 11 5 0 295 101 268
234 2 3 11 5 0 131 285 268
235 2 3 11 5 0 268 285 295
236 2 3 11 5 0 100 278 272
237 2 3 11 5 0 294 127 272
238 2 3 11 5 0 272 278 294
239 2 3 11 5 0 269 257 97
240 2 3 11 5 0 269 132 220
241 2 3 11 5 0 269 220 257
242 2 3 11 5 0 131 268 219
243 2 3 11 5 0 289 128 245
244 2 3 11 5 0 242 254 98
245 2 3 11 5 0 242 235 254
246 2 3 11 5 0 272 263 98
247 2 3 11 5 0 270 130 255
248 2 3 11 5 0 230 8 9
249 2 3 11 5 0 127 294 230
250 2 3 11 5 0 31 266 32
251 2 3 11 5 0 267 264 128
252 2 3 11 5 0 267 47 46
253 2 3 11 5 0 128 289 267
254 2 3 11 5 0 233 34 33
255 2 3 11 5 0 34 233 193
256 2 3 11 5 0 34 193 35
257 2 3 11 5 0 44 232 45
258 2 3 11 5 0 232 44 196
259 2 3 11 5 0 196 44 43
260 2 3 11 5 0 281 20 21
261 2 3 11 5 0 12 275 11
262 2 3 11 5 0 81 261 80
263 2 3 11 5 0 262 63 62
264 2 3 11 5 0 72 279 71
265 2 3 11 5 0 276 83 84
266 2 3 11 5 0 65 277 66
267 2 3 11 5 0 83 228 82
268 2 3 11 5 0 83 276 228
269 2 3 11 5 0 285 131 228
270 2 3 11 5 0 139 285 228
271 2 3 11 5 0 276 139 228
272 2 3 11 5 0 229 65 64
273 2 3 11 5 0 277 65 229
274 2 3 11 5 0 132 284 229
275 2 3 11 5 0 284 140 229
276 2 3 11 5 0 140 277 229
277 2 3 11 5 0 7 283 6
278 2 3 11 5 0 269 97 99
279 2 3 11 5 0 246 99 97
280 2 3 11 5 0 99 292 147
281 2 3 11 5 0 292 99 246
282 2 3 11 5 0 292 246 290
283 2 3 11 5 0 291 101 149
284 2 3 11 5 0 101 291 245
285 2 3 11 5 0 245 291 289
286 2 3 11 5 0 156 304 300
287 2 3 11 5 0 306 231 110
288 2 3 11 5 0 312 154 306
289 2 3 11 5 0 110 312 306
290 2 3 11 5 0 315 179 304
291 2 3 11 5 0 315 154 312
292 2 3 11 5 0 156 316 304
293 2 3 11 5 0 111 317 313
294 2 3 11 5 0 151 319 313
295 2 3 11 5 0 320 152 170
296 2 3 11 5 0 150 322 309
297 2 3 11 5 0 323 107 314
298 2 3 11 5 0 153 325 301
299 2 3 11 5 0 154 325 306
300 2 3 11 5 0 274 326 107
301 2 3 11 5 0 262 327 63
302 2 3 11 5 0 328 261 81
303 2 3 11 5 0 330 172 322
304 2 3 11 5 0 331 252 90
305 2 3 11 5 0 163 332 330
306 2 3 11 5 0 333 252 331
307 2 3 11 5 0 151 335 318
308 2 3 11 5 0 336 231 306
309 2 3 11 5 0 337 152 320
310 2 3 11 5 0 169 339 178
311 2 3 11 5 0 107 340 314
312 2 3 11 5 0 342 161 303
313 2 3 11 5 0 345 160 321
314 2 3 11 5 0 346 207 343
315 2 3 11 5 0 146 348 331
316 2 3 11 5 0 349 159 305
317 2 3 11 5 0 352 156 300
318 2 3 11 5 0 251 353 109
319 2 3 11 5 0 179 353 347
320 2 3 11 5 0 151 354 319
321 2 3 11 5 0 274 355 326
322 2 3 11 5 0 356 184 224
323 2 3 11 5 0 356 117 332
324 2 3 11 5 0 357 176 190
325 2 3 11 5 0 207 358 343
326 2 3 11 5 0 358 207 326
327 2 3 11 5 0 164 359 333
328 2 3 11 5 0 360 90 321
329 2 3 11 5 0 252 362 90
330 2 3 11 5 0 362 252 141
331 2 3 11 5 0 188 364 341
332 2 3 11 5 0 150 365 322
333 2 3 11 5 0 365 150 324
334 2 3 11 5 0 176 366 190
335 2 3 11 5 0 105 366 244
336 2 3 11 5 0 108 368 106
337 2 3 11 5 0 370 120 198
338 2 3 11 5 0 160 371 321
339 2 3 11 5 0 372 293 144
340 2 3 11 5 0 293 372 148
341 2 3 11 5 0 287 372 144
342 2 3 11 5 0 373 183 201
343 2 3 11 5 0 374 152 337
344 2 3 11 5 0 162 375 311
345 2 3 11 5 0 376 203 138
346 2 3 11 5 0 173 378 199
347 2 3 11 5 0 204 379 137
348 2 3 11 5 0 231 380 110
349 2 3 11 5 0 122 381 113
350 2 3 11 5 0 381 275 113
351 2 3 11 5 0 382 226 121
352 2 3 11 5 0 226 382 334
353 2 3 11 5 0 111 383 317
354 2 3 11 5 0 383 251 317
355 2 3 11 5 0 383 111 347
356 2 3 11 5 0 385 150 309
357 2 3 11 5 0 157 385 309
358 2 3 11 5 0 116 386 320
359 2 3 11 5 0 387 215 125
360 2 3 11 5 0 387 261 328
361 2 3 11 5 0 261 387 125
362 2 3 11 5 0 214 388 126
363 2 3 11 5 0 262 388 327
364 2 3 11 5 0 388 262 126
365 2 3 11 5 0 182 390 253
366 2 3 11 5 0 390 89 253
367 2 3 11 5 0 90 392 321
368 2 3 11 5 0 392 90 362
369 2 3 11 5 0 173 394 378
370 2 3 11 5 0 395 190 366
371 2 3 11 5 0 105 395 366
372 2 3 11 5 0 396 119 232
373 2 3 11 5 0 396 196 363
374 2 3 11 5 0 196 396 232
375 2 3 11 5 0 397 155 393
376 2 3 11 5 0 155 397 363
377 2 3 11 5 0 201 399 373
378 2 3 11 5 0 399 201 213
379 2 3 11 5 0 399 116 373
380 2 3 11 5 0 401 107 326
381 2 3 11 5 0 207 401 326
382 2 3 11 5 0 402 151 318
383 2 3 11 5 0 168 402 318
384 2 3 11 5 0 404 176 357
385 2 3 11 5 0 176 404 158
386 2 3 11 5 0 405 161 342
387 2 3 11 5 0 406 172 330
388 2 3 11 5 0 406 117 378
389 2 3 11 5 0 407 111 313
390 2 3 11 5 0 408 164 348
391 2 3 11 5 0 164 408 344
392 2 3 11 5 0 410 168 318
393 2 3 11 5 0 89 410 318
394 2 3 11 5 0 411 160 317
395 2 3 11 5 0 251 411 317
396 2 3 11 5 0 412 221 134
397 2 3 11 5 0 222 413 133
398 2 3 11 5 0 163 414 332
399 2 3 11 5 0 113 415 122
400 2 3 11 5 0 180 417 337
401 2 3 11 5 0 418 151 313
402 2 3 11 5 0 151 418 335
403 2 3 11 5 0 180 419 253
404 2 3 11 5 0 419 182 253
405 2 3 11 5 0 105 420 309
406 2 3 11 5 0 420 157 309
407 2 3 11 5 0 230 421 8
408 2 3 11 5 0 255 422 270
409 2 3 11 5 0 215 423 131
410 2 3 11 5 0 228 423 328
411 2 3 11 5 0 423 228 131
412 2 3 11 5 0 424 214 132
413 2 3 11 5 0 424 229 327
414 2 3 11 5 0 229 424 132
415 2 3 11 5 0 425 146 331
416 2 3 11 5 0 90 425 331
417 2 3 11 5 0 176 427 366
418 2 3 11 5 0 427 244 366
419 2 3 11 5 0 428 238 133
420 2 3 11 5 0 238 428 350
421 2 3 11 5 0 237 429 134
422 2 3 11 5 0 429 237 351
423 2 3 11 5 0 431 167 344
424 2 3 11 5 0 31 433 266
425 2 3 11 5 0 433 290 266
426 2 3 11 5 0 434 47 267
427 2 3 11 5 0 289 434 267
428 2 3 11 5 0 110 435 312
429 2 3 11 5 0 226 436 129
430 2 3 11 5 0 436 226 334
431 2 3 11 5 0 221 437 138
432 2 3 11 5 0 438 222 137
433 2 3 11 5 0 183 441 93
434 2 3 11 5 0 441 202 93
435 2 3 11 5 0 441 183 170
436 2 3 11 5 0 283 442 6
437 2 3 11 5 0 442 283 148
438 2 3 11 5 0 444 79 80
439 2 3 11 5 0 261 444 80
440 2 3 11 5 0 79 444 350
441 2 3 11 5 0 61 445 62
442 2 3 11 5 0 445 262 62
443 2 3 11 5 0 445 61 351
444 2 3 11 5 0 263 446 95
445 2 3 11 5 0 447 204 130
446 2 3 11 5 0 257 448 97
447 2 3 11 5 0 212 449 224
448 2 3 11 5 0 451 122 127
449 2 3 11 5 0 230 451 127
450 2 3 11 5 0 452 105 309
451 2 3 11 5 0 453 143 103
452 2 3 11 5 0 286 453 103
453 2 3 11 5 0 145 454 102
454 2 3 11 5 0 454 288 102
455 2 3 11 5 0 146 455 348
456 2 3 11 5 0 456 93 202
457 2 3 11 5 0 93 456 227
458 2 3 11 5 0 286 457 149
459 2 3 11 5 0 457 291 149
460 2 3 11 5 0 458 288 147
461 2 3 11 5 0 292 458 147
462 2 3 11 5 0 460 252 333
463 2 3 11 5 0 464 188 319
464 2 3 11 5 0 465 94 257
465 2 3 11 5 0 220 465 257
466 2 3 11 5 0 356 449 117
467 2 3 11 5 0 356 224 449
468 2 3 11 5 0 440 104 142
469 2 3 11 5 0 293 100 443
470 2 3 11 5 0 421 7 8
471 2 3 11 5 0 283 7 421
472 2 3 11 5 0 230 294 421
473 2 3 11 5 0 30 433 31
474 2 3 11 5 0 434 48 47
475 2 3 11 5 0 372 442 148
476 2 3 11 5 0 372 287 442
477 2 3 11 5 0 368 157 106
478 2 3 11 5 0 167 157 368
479 2 3 11 5 0 300 307 352
480 2 3 11 5 0 347 304 179
481 2 3 11 5 0 300 304 347
482 2 3 11 5 0 315 316 154
483 2 3 11 5 0 315 304 316
484 2 3 11 5 0 336 325 153
485 2 3 11 5 0 306 325 336
486 2 3 11 5 0 341 407 188
487 2 3 11 5 0 341 307 407
488 2 3 11 5 0 452 322 172
489 2 3 11 5 0 309 322 452
490 2 3 11 5 0 355 369 159
491 2 3 11 5 0 355 310 369
492 2 3 11 5 0 315 435 179
493 2 3 11 5 0 315 312 435
494 2 3 11 5 0 418 317 160
495 2 3 11 5 0 313 317 418
496 2 3 11 5 0 407 319 188
497 2 3 11 5 0 313 319 407
498 2 3 11 5 0 374 340 152
499 2 3 11 5 0 314 340 374
500 2 3 11 5 0 323 359 164
501 2 3 11 5 0 323 314 359
502 2 3 11 5 0 375 339 169
503 2 3 11 5 0 319 354 464
504 2 3 11 5 0 337 386 180
505 2 3 11 5 0 337 320 386
506 2 3 11 5 0 364 393 155
507 2 3 11 5 0 360 371 165
508 2 3 11 5 0 360 321 371
509 2 3 11 5 0 345 321 392
510 2 3 11 5 0 330 365 163
511 2 3 11 5 0 330 322 365
512 2 3 11 5 0 358 355 159
513 2 3 11 5 0 326 355 358
514 2 3 11 5 0 360 425 90
515 2 3 11 5 0 424 388 214
516 2 3 11 5 0 327 388 424
517 2 3 11 5 0 387 423 215
518 2 3 11 5 0 387 328 423
519 2 3 11 5 0 406 332 117
520 2 3 11 5 0 330 332 406
521 2 3 11 5 0 333 348 164
522 2 3 11 5 0 333 331 348
523 2 3 11 5 0 356 414 184
524 2 3 11 5 0 356 332 414
525 2 3 11 5 0 401 340 107
526 2 3 11 5 0 333 359 460
527 2 3 11 5 0 345 418 160
528 2 3 11 5 0 345 335 418
529 2 3 11 5 0 374 337 417
530 2 3 11 5 0 403 364 155
531 2 3 11 5 0 341 364 403
532 2 3 11 5 0 349 358 159
533 2 3 11 5 0 349 343 358
534 2 3 11 5 0 344 408 431
535 2 3 11 5 0 383 353 251
536 2 3 11 5 0 347 353 383
537 2 3 11 5 0 408 348 455
538 2 3 11 5 0 402 354 151
539 2 3 11 5 0 386 419 180
540 2 3 11 5 0 404 415 113
541 2 3 11 5 0 404 357 415
542 2 3 11 5 0 411 371 160
543 2 3 11 5 0 452 395 105
544 2 3 11 5 0 396 397 119
545 2 3 11 5 0 396 363 397
546 2 3 11 5 0 406 394 172
547 2 3 11 5 0 378 394 406
548 2 3 11 5 0 397 439 119
549 2 3 11 5 0 397 393 439
550 2 3 11 5 0 365 377 163
551 2 3 11 5 0 432 141 253
552 2 3 11 5 0 141 432 362
553 2 3 11 5 0 414 163 377
554 2 3 11 5 0 286 463 457
555 2 3 11 5 0 462 288 458
556 2 3 11 5 0 28 462 29
557 2 3 11 5 0 462 28 297
558 2 3 11 5 0 462 102 288
559 2 3 11 5 0 297 102 462
560 2 3 11 5 0 463 50 49
561 2 3 11 5 0 50 463 298
562 2 3 11 5 0 103 463 286
563 2 3 11 5 0 103 298 463
564 2 3 11 5 0 20 329 19
565 2 3 11 5 0 159 369 305
566 2 3 11 5 0 275 381 11
567 2 3 11 5 0 10 11 381
568 2 3 11 5 0 430 116 399
569 2 3 11 5 0 213 430 399
570 2 3 11 5 0 430 213 223
571 2 3 11 5 0 122 426 127
572 2 3 11 5 0 426 122 415
573 2 3 11 5 0 179 435 353
574 2 3 11 5 0 460 141 252
575 2 3 11 5 0 141 460 180
576 2 3 11 5 0 417 180 460
577 2 3 11 5 0 165 371 367
578 2 3 11 5 0 293 271 144
579 2 3 11 5 0 271 293 443
580 2 3 11 5 0 400 150 385
581 2 3 11 5 0 167 385 157
582 2 3 11 5 0 167 431 385
583 2 3 11 5 0 400 385 431
584 2 3 11 5 0 422 279 270
585 2 3 11 5 0 279 440 142
586 2 3 11 5 0 152 340 361
587 2 3 11 5 0 401 207 361
588 2 3 11 5 0 361 340 401
589 2 3 11 5 0 140 454 145
590 2 3 11 5 0 147 454 296
591 2 3 11 5 0 454 147 288
592 2 3 11 5 0 140 296 454
593 2 3 11 5 0 453 139 143
594 2 3 11 5 0 453 149 295
595 2 3 11 5 0 149 453 286
596 2 3 11 5 0 295 139 453
597 2 3 11 5 0 299 455 146
598 2 3 11 5 0 373 116 320
599 2 3 11 5 0 170 373 320
600 2 3 11 5 0 373 170 183
601 2 3 11 5 0 112 459 339
602 2 3 11 5 0 459 178 339
603 2 3 11 5 0 94 448 257
604 2 3 11 5 0 272 426 263
605 2 3 11 5 0 426 272 127
606 2 3 11 5 0 446 263 426
607 2 3 11 5 0 94 465 216
608 2 3 11 5 0 175 465 220
609 2 3 11 5 0 185 465 175
610 2 3 11 5 0 461 174 219
611 2 3 11 5 0 461 186 174
612 2 3 11 5 0 283 278 148
613 2 3 11 5 0 283 421 278
614 2 3 11 5 0 421 294 278
615 2 3 11 5 0 150 400 324
616 2 3 11 5 0 324 299 88
617 2 3 11 5 0 455 299 324
618 2 3 11 5 0 324 400 455
619 2 3 11 5 0 61 60 351
620 2 3 11 5 0 351 60 429
621 2 3 11 5 0 78 79 350
622 2 3 11 5 0 78 350 428
623 2 3 11 5 0 59 58 412
624 2 3 11 5 0 437 221 412
625 2 3 11 5 0 412 58 437
626 2 3 11 5 0 76 77 413
627 2 3 11 5 0 222 438 413
628 2 3 11 5 0 76 413 438
629 2 3 11 5 0 368 108 302
630 2 3 11 5 0 344 167 302
631 2 3 11 5 0 167 368 302
632 2 3 11 5 0 98 254 100
633 2 3 11 5 0 272 98 100
634 2 3 11 5 0 254 443 100
635 2 3 11 5 0 386 116 430
636 2 3 11 5 0 182 430 223
637 2 3 11 5 0 182 419 430
638 2 3 11 5 0 386 430 419
639 2 3 11 5 0 158 427 176
640 2 3 11 5 0 405 427 158
641 2 3 11 5 0 244 427 342
642 2 3 11 5 0 342 427 405
643 2 3 11 5 0 452 172 394
644 2 3 11 5 0 190 394 173
645 2 3 11 5 0 190 395 394
646 2 3 11 5 0 394 395 452
647 2 3 11 5 0 22 23 334
648 2 3 11 5 0 334 23 436
649 2 3 11 5 0 89 432 253
650 2 3 11 5 0 432 89 318
651 2 3 11 5 0 318 335 432
652 2 3 11 5 0 391 112 231
653 2 3 11 5 0 336 153 391
654 2 3 11 5 0 231 336 391
655 2 3 11 5 0 112 380 231
656 2 3 11 5 0 112 339 380
657 2 3 11 5 0 375 162 380
658 2 3 11 5 0 380 339 375
659 2 3 11 5 0 64 63 327
660 2 3 11 5 0 229 64 327
661 2 3 11 5 0 81 82 328
662 2 3 11 5 0 82 228 328
663 2 3 11 5 0 117 449 378
664 2 3 11 5 0 449 199 378
665 2 3 11 5 0 199 449 212
666 2 3 11 5 0 379 204 447
667 2 3 11 5 0 189 202 346
668 2 3 11 5 0 361 207 346
669 2 3 11 5 0 416 165 166
670 2 3 11 5 0 360 165 416
671 2 3 11 5 0 146 416 299
672 2 3 11 5 0 146 425 416
673 2 3 11 5 0 360 416 425
674 2 3 11 5 0 367 166 165
675 2 3 11 5 0 57 56 450
676 2 3 11 5 0 203 376 450
677 2 3 11 5 0 450 376 57
678 2 3 11 5 0 119 439 197
679 2 3 11 5 0 439 171 197
680 2 3 11 5 0 457 49 48
681 2 3 11 5 0 463 49 457
682 2 3 11 5 0 29 458 30
683 2 3 11 5 0 29 462 458
684 2 3 11 5 0 281 468 20
685 2 3 11 5 0 468 329 20
686 2 3 11 5 0 470 316 156
687 2 3 11 5 0 472 305 369
688 2 3 11 5 0 72 473 279
689 2 3 11 5 0 473 270 279
690 2 3 11 5 0 305 474 349
691 2 3 11 5 0 475 32 266
692 2 3 11 5 0 17 476 16
693 2 3 11 5 0 352 477 156
694 2 3 11 5 0 478 13 14
695 2 3 11 5 0 178 480 169
696 2 3 11 5 0 281 481 468
697 2 3 11 5 0 482 324 88
698 2 3 11 5 0 482 377 365
699 2 3 11 5 0 324 482 365
700 2 3 11 5 0 484 178 459
701 2 3 11 5 0 181 484 459
702 2 3 11 5 0 46 485 267
703 2 3 11 5 0 485 264 267
704 2 3 11 5 0 15 486 14
705 2 3 11 5 0 487 168 177
706 2 3 11 5 0 398 487 177
707 2 3 11 5 0 168 487 402
708 2 3 11 5 0 488 338 161
709 2 3 11 5 0 490 88 299
710 2 3 11 5 0 416 490 299
711 2 3 11 5 0 491 329 468
712 2 3 11 5 0 492 15 16
713 2 3 11 5 0 493 409 398
714 2 3 11 5 0 391 494 187
715 2 3 11 5 0 495 303 161
716 2 3 11 5 0 338 495 161
717 2 3 11 5 0 496 17 18
718 2 3 11 5 0 496 305 472
719 2 3 11 5 0 497 170 152
720 2 3 11 5 0 361 497 152
721 2 3 11 5 0 280 498 129
722 2 3 11 5 0 499 108 106
723 2 3 11 5 0 22 500 21
724 2 3 11 5 0 500 281 21
725 2 3 11 5 0 500 22 334
726 2 3 11 5 0 502 300 347
727 2 3 11 5 0 300 502 307
728 2 3 11 5 0 111 502 347
729 2 3 11 5 0 503 107 323
730 2 3 11 5 0 112 504 459
731 2 3 11 5 0 187 504 391
732 2 3 11 5 0 504 112 391
733 2 3 11 5 0 216 505 178
734 2 3 11 5 0 158 506 405
735 2 3 11 5 0 509 35 193
736 2 3 11 5 0 301 509 193
737 2 3 11 5 0 164 511 323
738 2 3 11 5 0 302 511 344
739 2 3 11 5 0 511 164 344
740 2 3 11 5 0 346 512 189
741 2 3 11 5 0 512 346 343
742 2 3 11 5 0 513 247 186
743 2 3 11 5 0 247 513 118
744 2 3 11 5 0 514 251 109
745 2 3 11 5 0 367 514 109
746 2 3 11 5 0 251 514 411
747 2 3 11 5 0 516 12 13
748 2 3 11 5 0 12 516 275
749 2 3 11 5 0 517 227 129
750 2 3 11 5 0 227 517 273
751 2 3 11 5 0 480 178 505
752 2 3 11 5 0 370 494 120
753 2 3 11 5 0 370 187 494
754 2 3 11 5 0 498 517 129
755 2 3 11 5 0 498 265 517
756 2 3 11 5 0 481 382 121
757 2 3 11 5 0 281 382 481
758 2 3 11 5 0 96 517 265
759 2 3 11 5 0 96 273 517
760 2 3 11 5 0 501 499 106
761 2 3 11 5 0 303 499 501
762 2 3 11 5 0 478 516 13
763 2 3 11 5 0 407 502 111
764 2 3 11 5 0 407 307 502
765 2 3 11 5 0 486 478 14
766 2 3 11 5 0 503 511 302
767 2 3 11 5 0 503 323 511
768 2 3 11 5 0 500 382 281
769 2 3 11 5 0 334 382 500
770 2 3 11 5 0 476 492 16
771 2 3 11 5 0 477 470 156
772 2 3 11 5 0 181 504 187
773 2 3 11 5 0 181 459 504
774 2 3 11 5 0 371 514 367
775 2 3 11 5 0 371 411 514
776 2 3 11 5 0 354 487 398
777 2 3 11 5 0 354 402 487
778 2 3 11 5 0 484 216 178
779 2 3 11 5 0 488 510 338
780 2 3 11 5 0 468 481 491
781 2 3 11 5 0 496 476 17
782 2 3 11 5 0 472 476 496
783 2 3 11 5 0 496 474 305
784 2 3 11 5 0 478 483 516
785 2 3 11 5 0 464 354 409
786 2 3 11 5 0 409 354 398
787 2 3 11 5 0 501 244 342
788 2 3 11 5 0 303 501 342
789 2 3 11 5 0 475 33 32
790 2 3 11 5 0 33 475 233
791 2 3 11 5 0 45 485 46
792 2 3 11 5 0 485 45 232
793 2 3 11 5 0 264 485 232
794 2 3 11 5 0 43 467 196
795 2 3 11 5 0 467 43 42
796 2 3 11 5 0 467 363 196
797 2 3 11 5 0 509 36 35
798 2 3 11 5 0 73 473 72
799 2 3 11 5 0 130 270 473
800 2 3 11 5 0 490 389 88
801 2 3 11 5 0 389 490 166
802 2 3 11 5 0 490 416 166
803 2 3 11 5 0 248 505 185
804 2 3 11 5 0 308 471 479
805 2 3 11 5 0 479 325 154
806 2 3 11 5 0 400 431 408
807 2 3 11 5 0 455 400 408
808 2 3 11 5 0 491 474 329
809 2 3 11 5 0 349 491 343
810 2 3 11 5 0 491 349 474
811 2 3 11 5 0 345 392 335
812 2 3 11 5 0 432 335 392
813 2 3 11 5 0 432 392 362
814 2 3 11 5 0 503 274 107
815 2 3 11 5 0 274 503 108
816 2 3 11 5 0 503 302 108
817 2 3 11 5 0 446 190 95
818 2 3 11 5 0 190 446 357
819 2 3 11 5 0 287 52 51
820 2 3 11 5 0 144 52 287
821 2 3 11 5 0 384 435 110
822 2 3 11 5 0 451 9 10
823 2 3 11 5 0 451 10 381
824 2 3 11 5 0 451 381 122
825 2 3 11 5 0 9 451 230
826 2 3 11 5 0 428 77 78
827 2 3 11 5 0 413 428 133
828 2 3 11 5 0 413 77 428
829 2 3 11 5 0 59 429 60
830 2 3 11 5 0 429 412 134
831 2 3 11 5 0 59 412 429
832 2 3 11 5 0 433 30 458
833 2 3 11 5 0 292 290 433
834 2 3 11 5 0 433 458 292
835 2 3 11 5 0 48 434 457
836 2 3 11 5 0 289 291 434
837 2 3 11 5 0 457 434 291
838 2 3 11 5 0 153 494 391
839 2 3 11 5 0 280 129 436
840 2 3 11 5 0 446 415 357
841 2 3 11 5 0 446 426 415
842 2 3 11 5 0 494 489 120
843 2 3 11 5 0 489 193 233
844 2 3 11 5 0 494 153 489
845 2 3 11 5 0 364 188 409
846 2 3 11 5 0 188 464 409
847 2 3 11 5 0 364 409 393
848 2 3 11 5 0 417 359 314
849 2 3 11 5 0 374 417 314
850 2 3 11 5 0 460 359 417
851 2 3 11 5 0 506 158 404
852 2 3 11 5 0 275 506 113
853 2 3 11 5 0 506 404 113
854 2 3 11 5 0 76 438 75
855 2 3 11 5 0 379 75 438
856 2 3 11 5 0 379 438 137
857 2 3 11 5 0 118 410 249
858 2 3 11 5 0 410 118 168
859 2 3 11 5 0 445 237 126
860 2 3 11 5 0 237 445 351
861 2 3 11 5 0 262 445 126
862 2 3 11 5 0 405 483 161
863 2 3 11 5 0 483 405 506
864 2 3 11 5 0 483 488 161
865 2 3 11 5 0 238 444 125
866 2 3 11 5 0 444 238 350
867 2 3 11 5 0 444 261 125
868 2 3 11 5 0 437 58 57
869 2 3 11 5 0 57 376 437
870 2 3 11 5 0 437 376 138
871 2 3 11 5 0 203 450 469
872 2 3 11 5 0 510 369 310
873 2 3 11 5 0 310 338 510
874 2 3 11 5 0 369 510 472
875 2 3 11 5 0 499 303 495
876 2 3 11 5 0 310 495 338
877 2 3 11 5 0 189 121 456
878 2 3 11 5 0 121 226 456
879 2 3 11 5 0 189 456 202
880 2 3 11 5 0 456 226 227
881 2 3 11 5 0 370 181 187
882 2 3 11 5 0 370 448 181
883 2 3 11 5 0 450 56 55
884 2 3 11 5 0 469 450 55
885 2 3 11 5 0 171 439 493
886 2 3 11 5 0 493 439 393
887 2 3 11 5 0 493 393 409
888 2 3 11 5 0 74 447 73
889 2 3 11 5 0 473 73 447
890 2 3 11 5 0 130 473 447
891 2 3 11 5 0 515 280 282
892 2 3 11 5 0 265 498 515
893 2 3 11 5 0 498 280 515
894 2 3 11 5 0 38 466 39
895 2 3 11 5 0 470 518 316
896 2 3 11 5 0 518 470 466
897 2 3 11 5 0 325 519 301
898 2 3 11 5 0 471 519 479
899 2 3 11 5 0 519 325 479
900 2 3 11 5 0 520 301 193
901 2 3 11 5 0 520 489 153
902 2 3 11 5 0 489 520 193
903 2 3 11 5 0 301 520 153
904 2 3 11 5 0 521 469 271
905 2 3 11 5 0 310 522 495
906 2 3 11 5 0 523 489 233
907 2 3 11 5 0 489 523 120
908 2 3 11 5 0 185 525 465
909 2 3 11 5 0 216 525 505
910 2 3 11 5 0 525 216 465
911 2 3 11 5 0 525 185 505
912 2 3 11 5 0 97 526 198
913 2 3 11 5 0 370 526 448
914 2 3 11 5 0 526 370 198
915 2 3 11 5 0 526 97 448
916 2 3 11 5 0 521 443 254
917 2 3 11 5 0 271 443 521
918 2 3 11 5 0 308 518 466
919 2 3 11 5 0 308 479 518
920 2 3 11 5 0 518 154 316
921 2 3 11 5 0 479 154 518
922 2 3 11 5 0 499 522 108
923 2 3 11 5 0 499 495 522
924 2 3 11 5 0 524 398 177
925 2 3 11 5 0 524 171 493
926 2 3 11 5 0 524 493 398
927 2 3 11 5 0 198 290 246
928 2 3 11 5 0 290 198 266
929 2 3 11 5 0 390 410 89
930 2 3 11 5 0 390 123 249
931 2 3 11 5 0 123 390 182
932 2 3 11 5 0 390 249 410
933 2 3 11 5 0 506 275 516
934 2 3 11 5 0 483 506 516
935 2 3 11 5 0 38 308 466
936 2 3 11 5 0 157 420 106
937 2 3 11 5 0 420 501 106
938 2 3 11 5 0 244 420 105
939 2 3 11 5 0 244 501 420
940 2 3 11 5 0 274 522 355
941 2 3 11 5 0 522 274 108
942 2 3 11 5 0 522 310 355
943 2 3 11 5 0 486 483 478
944 2 3 11 5 0 483 486 488
945 2 3 11 5 0 250 258 248
946 2 3 11 5 0 505 248 258
947 2 3 11 5 0 480 505 258
948 2 3 11 5 0 492 476 472
949 2 3 11 5 0 472 510 492
950 2 3 11 5 0 480 508 169
951 2 3 11 5 0 87 508 258
952 2 3 11 5 0 508 480 258
953 2 3 11 5 0 521 235 203
954 2 3 11 5 0 235 521 254
955 2 3 11 5 0 469 521 203
956 2 3 11 5 0 189 512 121
957 2 3 11 5 0 512 481 121
958 2 3 11 5 0 491 512 343
959 2 3 11 5 0 491 481 512
960 2 3 11 5 0 94 484 448
961 2 3 11 5 0 216 484 94
962 2 3 11 5 0 484 181 448
963 2 3 11 5 0 36 471 37
964 2 3 11 5 0 36 509 471
965 2 3 11 5 0 497 441 170
966 2 3 11 5 0 497 202 441
967 2 3 11 5 0 497 346 202
968 2 3 11 5 0 346 497 361
969 2 3 11 5 0 265 255 96
970 2 3 11 5 0 422 255 265
971 2 3 11 5 0 329 18 19
972 2 3 11 5 0 329 474 18
973 2 3 11 5 0 18 474 496
974 2 3 11 5 0 155 363 403
975 2 3 11 5 0 403 363 467
976 2 3 11 5 0 519 509 301
977 2 3 11 5 0 471 509 519
978 2 3 11 5 0 37 308 38
979 2 3 11 5 0 471 308 37
980 2 3 11 5 0 311 527 389
981 2 3 11 5 0 184 528 87
982 2 3 11 5 0 528 184 414
983 2 3 11 5 0 311 529 527
984 2 3 11 5 0 530 508 87
985 2 3 11 5 0 530 507 527
986 2 3 11 5 0 532 507 377
987 2 3 11 5 0 466 533 39
988 2 3 11 5 0 533 466 470
989 2 3 11 5 0 311 534 162
990 2 3 11 5 0 532 482 88
991 2 3 11 5 0 377 482 532
992 2 3 11 5 0 533 40 39
993 2 3 11 5 0 477 533 470
994 2 3 11 5 0 528 530 87
995 2 3 11 5 0 528 507 530
996 2 3 11 5 0 377 528 414
997 2 3 11 5 0 377 507 528
998 2 3 11 5 0 530 529 508
999 2 3 11 5 0 527 529 530
1000 2 3 11 5 0 529 375 169
1001 2 3 11 5 0 529 169 508
1002 2 3 11 5 0 529 311 375
1003 2 3 11 5 0 469 54 271
1004 2 3 11 5 0 54 469 55
1005 2 3 11 5 0 389 532 88
1006 2 3 11 5 0 532 389 527
1007 2 3 11 5 0 507 532 527
1008 2 3 11 5 0 74 379 447
1009 2 3 11 5 0 379 74 75
1010 2 3 11 5 0 118 513 177
1011 2 3 11 5 0 186 461 513
1012 2 3 11 5 0 461 531 513
1013 2 3 11 5 0 279 422 440
1014 2 3 11 5 0 515 440 422
1015 2 3 11 5 0 515 422 265
1016 2 3 11 5 0 120 523 198
1017 2 3 11 5 0 523 266 198
1018 2 3 11 5 0 475 523 233
1019 2 3 11 5 0 523 475 266
1020 2 3 11 5 0 488 486 492
1021 2 3 11 5 0 15 492 486
1022 2 3 11 5 0 488 492 510
1023 2 3 11 5 0 524 537 171
1024 2 3 11 5 0 537 524 531
1025 2 3 11 5 0 513 539 177
1026 2 3 11 5 0 524 539 531
1027 2 3 11 5 0 539 524 177
1028 2 3 11 5 0 539 513 531
1029 2 3 11 5 0 536 101 245
1030 2 3 11 5 0 536 197 171
1031 2 3 11 5 0 197 536 245
1032 2 3 11 5 0 461 538 531
1033 2 3 11 5 0 538 461 219
1034 2 3 11 5 0 531 538 537
1035 2 3 11 5 0 367 534 166
1036 2 3 11 5 0 271 53 144
1037 2 3 11 5 0 53 271 54
1038 2 3 11 5 0 40 540 41
1039 2 3 11 5 0 540 40 533
1040 2 3 11 5 0 541 389 166
1041 2 3 11 5 0 541 534 311
1042 2 3 11 5 0 534 541 166
1043 2 3 11 5 0 389 541 311
1044 2 3 11 5 0 109 543 367
1045 2 3 11 5 0 543 534 367
1046 2 3 11 5 0 543 109 384
1047 2 3 11 5 0 544 27 2
1048 2 3 11 5 0 69 544 2
1049 2 3 11 5 0 545 109 353
1050 2 3 11 5 0 545 435 384
1051 2 3 11 5 0 435 545 353
1052 2 3 11 5 0 109 545 384
1053 2 3 11 5 0 440 546 104
1054 2 3 11 5 0 101 542 268
1055 2 3 11 5 0 101 536 542
1056 2 3 11 5 0 542 219 268
1057 2 3 11 5 0 538 219 542
1058 2 3 11 5 0 477 540 533
1059 2 3 11 5 0 171 537 536
1060 2 3 11 5 0 537 542 536
1061 2 3 11 5 0 542 537 538
1062 2 3 11 5 0 104 544 69
1063 2 3 11 5 0 546 544 104
1064 2 3 11 5 0 535 42 41
1065 2 3 11 5 0 540 535 41
1066 2 3 11 5 0 467 42 535
1067 2 3 11 5 0 515 546 440
1068 2 3 11 5 0 546 515 282
1069 2 3 11 5 0 26 27 544
1070 2 3 11 5 0 548 380 162
1071 2 3 11 5 0 548 384 110
1072 2 3 11 5 0 384 548 162
1073 2 3 11 5 0 380 548 110
1074 2 3 11 5 0 25 26 282
1075 2 3 11 5 0 26 546 282
1076 2 3 11 5 0 26 544 546
1077 2 3 11 5 0 24 549 23
1078 2 3 11 5 0 549 436 23
1079 2 3 11 5 0 25 549 24
1080 2 3 11 5 0 280 549 282
1081 2 3 11 5 0 549 280 436
1082 2 3 11 5 0 25 282 549
1083 2 3 11 5 0 341 547 307
1084 2 3 11 5 0 352 307 547
1085 2 3 11 5 0 403 547 341
1086 2 3 11 5 0 547 477 352
1087 2 3 11 5 0 477 547 540
1088 2 3 11 5 0 547 535 540
1089 2 3 11 5 0 162 543 384
1090 2 3 11 5 0 162 534 543
1091 2 3 11 5 0 550 403 467
1092 2 3 11 5 0 550 535 547
1093 2 3 11 5 0 535 550 467
1094 2 3 11 5 0 403 550 547
1095 2 3 11 5 0 551 5 6
1096 2 3 11 5 0 442 551 6
1097 2 3 11 5 0 5 552 1
1098 2 3 11 5 0 552 51 1
1099 2 3 11 5 0 552 5 551
1100 2 3 11 5 0 287 551 442
1101 2 3 11 5 0 551 287 51
1102 2 3 11 5 0 51 552 551
$EndElements
| {'repo_name': 'FluidityProject/fluidity', 'stars': '213', 'repo_language': 'Fortran', 'file_name': 'test_fluxes_reader_wrapper.F90', 'mime_type': 'text/plain', 'hash': -868360816582880198, 'source_dataset': 'data'} |
//***********************************************************************//
// //
// - "Talk to me like I'm a 3 year old!" Programming Lessons - //
// //
// $Author: DigiBen [email protected] //
// //
// $Program: MotionBlur //
// //
// $Description: Demonstrates fast motion blurring in OpenGL //
// //
//***********************************************************************//
// This is a compiler directive that includes libraries (For Visual Studio)
// You can manually include the libraries in the "Project->settings" menu under
// the "Link" tab. You need these libraries to compile this program.
#pragma comment(lib, "opengl32.lib")
#pragma comment(lib, "glu32.lib")
#include "main.h" // This includes our header file
bool g_bFullScreen = true; // Set full screen as default
HWND g_hWnd; // This is the handle for the window
RECT g_rRect; // This holds the window dimensions
HDC g_hDC; // General HDC - (handle to device context)
HGLRC g_hRC; // General OpenGL_DC - Our Rendering Context for OpenGL
HINSTANCE g_hInstance; // This holds the global hInstance for UnregisterClass() in DeInit()
UINT g_Texture[MAX_TEXTURES]; // This will reference to our texture data stored with OpenGL UINT is an unsigned int (only positive numbers)
/////// * /////////// * /////////// * NEW * /////// * /////////// * /////////// *
// This tutorial is taken from the Masking and Ortho tutorial, with a bunch also
// taken out from the Rendering To A Texture tutorial. In the masking tutorial
// we learned how to mask images for distinct transparencies, along with the
// glOrtho() mode. The glOrtho() mode allows us to pass vertices in as 2D
// coordinates. This is great for things that we want to have in front of the
// camera at all times, such as a scope or interfaces. In this tutorial we gutted
// out the masking stuff, but left the ortho code and added some functions for rendering
// to a texture which were taken from the RenderToTexture tutorial. Before looking at
// this tutorial, it is assumed you have gone through the referenced tutorials, or are
// prepared to suffer an overload of new information :)
//
// The technique shown in this application is how to render motion blurring in an
// incredibly fast way. Usually you hear that you want to use the accumulation buffer
// for motion blurring, but this is ridiculously slow for real time rendering. A more
// practical way to do it is to render the current screen to a texture, then go into
// ortho mode and blend that texture over the entire screen. This could be done every
// frame or intermittently. I used our AnimateNextFrame() function from our 2D sprite
// tutorial to restrict the blending to a certain frame rate. This is stored in g_BlurRate.
// We can change the current rate by using the LEFT and RIGHT arrow keys. The faster the
// rate the more realistic it looks, where as the slower it is, it appears more like a
// slow motion video game blur.
//
// To create the blur effect, we actually render the texture when rendering to the texture.
// This is a bit confusing. Basically, when we go to render the screen to the texture,
// we go into ortho mode and blend the current texture of the screen over the object that
// is being blurred. This acts as a recursive blending. This makes it so we don't do
// tons of passes to create the blur trail.
//
// The fading happens when we blend the current rendered texture with the blackness of
// the background. When blending, we need to blend the texture with a small decrease
// in alpha. Basically, we don't render the texture over the screen at full alpha,
// otherwise it would never blend away, or at least it would take forever to fade.
//
// Let's go over the controls for this app:
//
// LEFT / RIGHT Arrow Keys - Increase/Decrease the amount of passes per second
// '1' - This changes the texture size to 128 (LOW QUALITY)
// '2' - This changes the texture size to 256 (ACCEPTABLE QUALITY)
// '3' - This changes the texture size to 512 (HIGH QUALITY)
// SPACE BAR - Stops and starts the rotating box
// ESCAPE Key - This quits the program
//
//
// This holds how many times per second we render to the texture
int g_BlurRate = 50;
// This stores if rotating is on or off
bool g_bRotate = true;
/////// * /////////// * /////////// * NEW * /////// * /////////// * /////////// *
// This stores our current rotation
float g_RotateX = 0, g_RotateY = 0, g_RotateZ = 0;
// This will store the size of the viewport that we render the texture from.
int g_Viewport = 512;
// This is our prototype for the function that creates the empty texture to render to
void CreateRenderTexture(UINT textureArray[], int size, int channels, int type, int textureID);
///////////////////////////////// INIT GAME WINDOW \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*
/////
///// This function initializes the game window.
/////
///////////////////////////////// INIT GAME WINDOW \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*
void Init(HWND hWnd)
{
g_hWnd = hWnd; // Assign the window handle to a global window handle
GetClientRect(g_hWnd, &g_rRect); // Assign the windows rectangle to a global RECT
InitializeOpenGL(g_rRect.right, g_rRect.bottom); // Init OpenGL with the global rect
glEnable(GL_DEPTH_TEST); // Turn depth testing on
glEnable(GL_TEXTURE_2D); // Enable Texture Mapping
// This is where we initialize our empty texture to be rendered too.
// We pass in the texture array to store it, the texture size,
// the channels (3 for R G B), the type of texture (RGB) and texture ID.
CreateRenderTexture(g_Texture, 512, 3, GL_RGB, 0);
// Create the texture map for the spinning cube and assign it to texture ID 1
CreateTexture(g_Texture[1], "Brick.bmp");
}
/////////////////////////////// ANIMATE NEXT FRAME \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*
/////
///// This function clamps a specified frame rate for consistency
/////
/////////////////////////////// ANIMATE NEXT FRAME \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*
bool AnimateNextFrame(int desiredFrameRate)
{
static float lastTime = GetTickCount() * 0.001f;
static float elapsedTime = 0.0f;
float currentTime = GetTickCount() * 0.001f; // Get the time (milliseconds = seconds * .001)
float deltaTime = currentTime - lastTime; // Get the slice of time
float desiredFPS = 1.0f / desiredFrameRate; // Store 1 / desiredFrameRate
elapsedTime += deltaTime; // Add to the elapsed time
lastTime = currentTime; // Update lastTime
// Check if the time since we last checked is greater than our desiredFPS
if( elapsedTime > desiredFPS )
{
elapsedTime -= desiredFPS; // Adjust our elapsed time
// Return true, to animate the next frame of animation
return true;
}
// We don't animate right now.
return false;
}
///////////////////////////////// MAIN LOOP \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*
/////
///// This function handles the main loop
/////
///////////////////////////////// MAIN LOOP \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*
WPARAM MainLoop()
{
MSG msg;
while(1) // Do our infinite loop
{ // Check if there was a message
if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
if(msg.message == WM_QUIT) // If the message wasn't to quit
break;
TranslateMessage(&msg); // Find out what the message does
DispatchMessage(&msg); // Execute the message
}
else // if there wasn't a message
{
RenderScene(); // Render the scene every frame
}
}
DeInit(); // Clean up and free all allocated memory
return(msg.wParam); // Return from the program
}
///////////////////////////////// ORTHO MODE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*
/////
///// This function changes our projection mode from 3D to 2D
/////
///////////////////////////////// ORTHO MODE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*
void OrthoMode(int left, int top, int right, int bottom)
{
// Switch to our projection matrix so that we can change it to ortho mode, not perspective.
glMatrixMode(GL_PROJECTION);
// Push on a new matrix so that we can just pop it off to go back to perspective mode
glPushMatrix();
// Reset the current matrix to our identify matrix
glLoadIdentity();
//Pass in our 2D ortho screen coordinates like so (left, right, bottom, top). The last
// 2 parameters are the near and far planes.
glOrtho( left, right, bottom, top, 0, 1 );
// Switch to model view so that we can render the scope image
glMatrixMode(GL_MODELVIEW);
// Initialize the current model view matrix with the identity matrix
glLoadIdentity();
}
///////////////////////////////// PERSPECTIVE MODE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*
/////
///// This function changes our returns our projection mode from 2D to 3D
/////
///////////////////////////////// PERSPECTIVE MODE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*
void PerspectiveMode() // Set Up A Perspective View
{
// Enter into our projection matrix mode
glMatrixMode( GL_PROJECTION );
// Pop off the last matrix pushed on when in projection mode (Get rid of ortho mode)
glPopMatrix();
// Go back to our model view matrix like normal
glMatrixMode( GL_MODELVIEW );
// We should be in the normal 3D perspective mode now
}
///////////////////////////////////// CREATE BOX \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*
/////
///// This function creates a textured box (if textureID >= 0) with a center and dimension
/////
///////////////////////////////////// CREATE BOX \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*
void CreateBox(int textureID, float x, float y, float z, float width,
float height, float length, float uscale, float vscale)
{
// Check if we have a valid texture ID, then bind that texture to our box
if(textureID >= 0) glBindTexture(GL_TEXTURE_2D, g_Texture[textureID]);
// This centers the box around (x, y, z)
x = x - width / 2;
y = y - height / 2;
z = z - length / 2;
// Start drawing the side as a QUAD
glBegin(GL_QUADS);
// Assign the texture coordinates and vertices for the BACK Side
glTexCoord2f(0.0f, 0.0f); glVertex3f(x, y, z);
glTexCoord2f(0.0f, vscale); glVertex3f(x, y + height, z);
glTexCoord2f(uscale, vscale); glVertex3f(x + width, y + height, z);
glTexCoord2f(uscale, 0.0f); glVertex3f(x + width, y, z);
// Assign the texture coordinates and vertices for the FRONT Side
glTexCoord2f(uscale, 0.0f); glVertex3f(x, y, z + length);
glTexCoord2f(uscale, vscale); glVertex3f(x, y + height, z + length);
glTexCoord2f(0.0f, vscale); glVertex3f(x + width, y + height, z + length);
glTexCoord2f(0.0f, 0.0f); glVertex3f(x + width, y, z + length);
// Assign the texture coordinates and vertices for the BOTTOM Side
glTexCoord2f(uscale, 0.0f); glVertex3f(x, y, z);
glTexCoord2f(uscale, vscale); glVertex3f(x, y, z + length);
glTexCoord2f(0.0f, vscale); glVertex3f(x + width, y, z + length);
glTexCoord2f(0.0f, 0.0f); glVertex3f(x + width, y, z);
// Assign the texture coordinates and vertices for the TOP Side
glTexCoord2f(uscale, vscale); glVertex3f(x, y + height, z);
glTexCoord2f(uscale, 0.0f); glVertex3f(x, y + height, z + length);
glTexCoord2f(0.0f, 0.0f); glVertex3f(x + width, y + height, z + length);
glTexCoord2f(0.0f, vscale); glVertex3f(x + width, y + height, z);
// Assign the texture coordinates and vertices for the LEFT Side
glTexCoord2f(uscale, 0.0f); glVertex3f(x, y, z);
glTexCoord2f(0.0f, 0.0f); glVertex3f(x, y, z + length);
glTexCoord2f(0.0f, vscale); glVertex3f(x, y + height, z + length);
glTexCoord2f(uscale, vscale); glVertex3f(x, y + height, z);
// Assign the texture coordinates and vertices for the RIGHT Side
glTexCoord2f(0.0f, 0.0f); glVertex3f(x + width, y, z);
glTexCoord2f(uscale, 0.0f); glVertex3f(x + width, y, z + length);
glTexCoord2f(uscale, vscale); glVertex3f(x + width, y + height, z + length);
glTexCoord2f(0.0f, vscale); glVertex3f(x + width, y + height, z);
// Stop drawing quads
glEnd();
}
///////////////////////////////// CREATE RENDER TEXTURE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*
/////
///// This function creates a blank texture to render too
/////
///////////////////////////////// CREATE RENDER TEXTURE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*
void CreateRenderTexture(UINT textureArray[], int size, int channels, int type, int textureID)
{
// Create a pointer to store the blank image data
unsigned int *pTexture = NULL;
// Allocate and init memory for the image array and point to it from pTexture
pTexture = new unsigned int [size * size * channels];
memset(pTexture, 0, size * size * channels * sizeof(unsigned int));
// Register the texture with OpenGL and bind it to the texture ID
glGenTextures(1, &textureArray[textureID]);
glBindTexture(GL_TEXTURE_2D, textureArray[textureID]);
// Create the texture and store it on the video card
glTexImage2D(GL_TEXTURE_2D, 0, channels, size, size, 0, type, GL_UNSIGNED_INT, pTexture);
// Set the texture quality
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
// Since we stored the texture space with OpenGL, we can delete the image data
delete [] pTexture;
}
/////// * /////////// * /////////// * NEW * /////// * /////////// * /////////// *
///////////////////////////////// RENDER MOTION BLUR \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*
/////
///// This function takes a texture ID to blend over the screen for motion blur
/////
///////////////////////////////// RENDER MOTION BLUR \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*
void RenderMotionBlur(int textureID)
{
// This function was created to blend the rendered texture over top of the screen
// to create the recursive blur effect. What happens is we start out by turning
// off depth testing, setting our blending mode, then binding the texture of our
// rendered textured over the QUAD that is about to be created. Next, we set our
// alpha level to %90 of full strength. This makes it so it will slowly disappear.
// Before rendering the QUAD, we want to go into ortho mode. This makes it easier
// to render a QUAD over the full screen without having to deal with vertices, but
// 2D coordinates. Once we render the QUAD, we want to go back to perspective mode.
// We can then turn depth testing back on and turn off texturing.
// Push on a new stack so that we do not interfere with the current matrix
glPushMatrix();
// Turn off depth testing so that we can blend over the screen
glDisable(GL_DEPTH_TEST);
// Set our blend method and enable blending
glBlendFunc(GL_SRC_ALPHA,GL_ONE);
glEnable(GL_BLEND);
// Bind the rendered texture to our QUAD
glBindTexture(GL_TEXTURE_2D, g_Texture[textureID]);
// Decrease the alpha value of the blend by %10 so it will fade nicely
glColor4f(1, 1, 1, 0.9f);
// Switch to 2D mode (Ortho mode)
OrthoMode(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
// Display a 2D quad with our blended texture
glBegin(GL_QUADS);
// Display the top left point of the 2D image
glTexCoord2f(0.0f, 1.0f); glVertex2f(0, 0);
// Display the bottom left point of the 2D image
glTexCoord2f(0.0f, 0.0f); glVertex2f(0, SCREEN_HEIGHT);
// Display the bottom right point of the 2D image
glTexCoord2f(1.0f, 0.0f); glVertex2f(SCREEN_WIDTH, SCREEN_HEIGHT);
// Display the top right point of the 2D image
glTexCoord2f(1.0f, 1.0f); glVertex2f(SCREEN_WIDTH, 0);
// Stop drawing
glEnd();
// Let's set our mode back to perspective 3D mode.
PerspectiveMode();
// Turn depth testing back on and texturing off. If you do NOT do these 2 lines of
// code it produces a cool flash effect that might come in handy somewhere down the road.
glEnable(GL_DEPTH_TEST);
glDisable(GL_BLEND);
// Go back to our original matrix
glPopMatrix();
}
/////// * /////////// * /////////// * NEW * /////// * /////////// * /////////// *
///////////////////////////////// RENDER SCENE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*
/////
///// This function renders the entire scene.
/////
///////////////////////////////// RENDER SCENE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*
void RenderScene()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear The Screen And The Depth Buffer
glLoadIdentity(); // Reset The matrix
/////// * /////////// * /////////// * NEW * /////// * /////////// * /////////// *
// Position View Up Vector
gluLookAt(0, 0, 10, 0, 0, 0, 0, 1, 0); // Move the camera back by 10 units
// We want to have the cube rotating along all axis's so we can better see the motion
// blur at different rotations. You can press the space bar to stop/start the rotation.
glRotatef(g_RotateX, 1.0f, 0.0f, 0.0f); // Rotate the cubes around the X-axis
glRotatef(g_RotateY, 0.0f, 1.0f, 0.0f); // Rotate the cubes around the Y-axis
glRotatef(g_RotateZ, 0.0f, 0.0f, 1.0f); // Rotate the cubes around the Z-axis
// Below we render to the texture. We can control how much we render to the texture
// per second by the LEFT and RIGHT arrow keys. The more we render to the texture, the
// smoother the blur is.
// Render to the texture only a controlled amount of frames per second
if( AnimateNextFrame(g_BlurRate) )
{
// Shrink the viewport by the current viewport size. Hit 1, 2, or 3 to change the size.
glViewport(0, 0, g_Viewport, g_Viewport);
// This is where we redraw the current rendered texture before we draw the spinning box.
// This creates the recursive fading of the motion blur. We pass in the texture ID
// we are using for the rendered texture.
RenderMotionBlur(0);
// Now we get to render the spinning box to the texture. We just
// need to create the box and it will be effected by the current rotation.
// The parameters are the texture ID, the center (x,y,z), dimensions and uv scale.
CreateBox(1, 0, 0, 0, 1, 6, 1, 1, 3);
// Before we copy the screen to a texture, we need to specify the current
// texture to draw to by calling glBindTexture() with the appropriate texture
glBindTexture(GL_TEXTURE_2D,g_Texture[0]);
// Render the current screen to our texture
glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 0, 0, g_Viewport, g_Viewport, 0);
// Here we clear the screen and depth bits of the small viewport
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Set our viewport back to it's normal size
glViewport(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
}
// Now that we have updated our rendered texture, let us display it to the screen
// by blending it once again. This should have all the blur trails rendered to it.
RenderMotionBlur(0);
// Redraw the box at the same position as it was drawn into the rendered texture
CreateBox(1, 0, 0, 0, 1, 6, 1, 1, 3);
// If we want rotation, increase the current rotations along each axises
if(g_bRotate)
{
g_RotateX += 2; g_RotateY += 3; g_RotateZ += 2;
}
/////// * /////////// * /////////// * NEW * /////// * /////////// * /////////// *
// Swap the backbuffers to the foreground
SwapBuffers(g_hDC);
}
///////////////////////////////// WIN PROC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*
/////
///// This function handles the window messages.
/////
///////////////////////////////// WIN PROC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*
LRESULT CALLBACK WinProc(HWND hWnd,UINT uMsg, WPARAM wParam, LPARAM lParam)
{
LONG lRet = 0;
PAINTSTRUCT ps;
bool bUpdate = false;
switch (uMsg)
{
case WM_SIZE: // If the window is resized
if(!g_bFullScreen) // Do this only if we are NOT in full screen
{
SizeOpenGLScreen(LOWORD(lParam),HIWORD(lParam));// LoWord=Width, HiWord=Height
GetClientRect(hWnd, &g_rRect); // Get the window rectangle
}
break;
case WM_PAINT: // If we need to repaint the scene
BeginPaint(hWnd, &ps); // Init the paint struct
EndPaint(hWnd, &ps); // EndPaint, Clean up
break;
case WM_KEYDOWN:
switch(wParam) { // Check if we hit a key
case VK_ESCAPE: // If we hit the escape key
PostQuitMessage(0); // Send a QUIT message to the window
break;
/////// * /////////// * /////////// * NEW * /////// * /////////// * /////////// *
// We are able to control the amount of motion blur that happens
// by using the left and right arrow keys. We can also start and stop
// the rotation of the box by using the space bar. Like in the
// tutorial about rendering to a texture, we can also use 1, 2, of 3
// to specify texture quality. 128 is atrocious though.
case VK_LEFT: // If we hit the LEFT arrow key
g_BlurRate -= 10; // Decrease the current blurs per second
if(g_BlurRate < 10) g_BlurRate = 10; // Make sure we don't go below 10
bUpdate = true; // Update the title information
break;
case VK_RIGHT: // If we hit the RIGHT arrow key
g_BlurRate += 10; // Increase the current blurs per second
if(g_BlurRate > 100) g_BlurRate = 100; // Make sure we don't go above 100
bUpdate = true; // Update the title information
break;
case VK_SPACE: g_bRotate = !g_bRotate; // Turn on/off rotation
break;
case '1': g_Viewport = 128; // Change viewport size to 128
bUpdate = true; // Update the title information
break;
case '2': g_Viewport = 256; // Change viewport size to 256
bUpdate = true; // Update the title information
break;
case '3': g_Viewport = 512; // Change viewport size to 512
bUpdate = true; // Update the title information
break;
/////// * /////////// * /////////// * NEW * /////// * /////////// * /////////// *
}
break;
case WM_CLOSE: // If the window is being closes
PostQuitMessage(0); // Send a QUIT Message to the window
break;
default: // Return by default
lRet = DefWindowProc (hWnd, uMsg, wParam, lParam);
break;
}
/////// * /////////// * /////////// * NEW * /////// * /////////// * /////////// *
if(bUpdate)
{
static char strTitle[255] = {0};
sprintf(strTitle, "Current Texture Renders Per Second: %d Current Texture Size: %d",
g_BlurRate, g_Viewport);
SetWindowText(g_hWnd, strTitle); // Update the title information
}
/////// * /////////// * /////////// * NEW * /////// * /////////// * /////////// *
return lRet; // Return by default
}
/////////////////////////////////////////////////////////////////////////////////
//
// * QUICK NOTES *
//
// Motion looks neat doesn't it? This is true, but be careful to not use it
// all the time. Though this technique is fast, everything that you blur has
// to be drawn twice. That means you wouldn't want to blur everything in your
// entire frustum unless you are at like a cut scene or something, and the slow
// down is part of the drama and effect. Obviously, the better your video card,
// the more detailed your blurred textures can be. If you go to a 128 x 128 texture
// you will notice that it looks like crap. It only gets worse the higher your
// screen resolution goes. I recommend using at LEAST 256. You could possibly
// get by with using 128 if the motion was really quick and far away. I have
// found that 512 seems to be the best. It isn't too massive, so you don't get
// a huge memory footprint, and yet it isn't too small where you lose all the
// detail when the image is scaled at a higher resolution.
//
// I hope this helps someone out!
//
//
// © 2000-2006 GameTutorials
//
| {'repo_name': 'gametutorials/tutorials', 'stars': '265', 'repo_language': 'C++', 'file_name': 'Frustum.cpp', 'mime_type': 'text/x-c', 'hash': -4622018997398451986, 'source_dataset': 'data'} |
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
function getDecimals(n) {
n = n + '';
var i = n.indexOf('.');
return (i == -1) ? 0 : n.length - i - 1;
}
function getVF(n, opt_precision) {
var v = opt_precision;
if (undefined === v) {
v = Math.min(getDecimals(n), 3);
}
var base = Math.pow(10, v);
var f = ((n * base) | 0) % base;
return {v: v, f: f};
}
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"\u092b\u0941\u0902",
"\u092c\u0947\u0932\u093e\u0938\u0947"
],
"DAY": [
"\u0930\u092c\u093f\u092c\u093e\u0930",
"\u0938\u092e\u092c\u093e\u0930",
"\u092e\u0902\u0917\u0932\u092c\u093e\u0930",
"\u092c\u0941\u0926\u092c\u093e\u0930",
"\u092c\u093f\u0938\u0925\u093f\u092c\u093e\u0930",
"\u0938\u0941\u0916\u0941\u0930\u092c\u093e\u0930",
"\u0938\u0941\u0928\u093f\u092c\u093e\u0930"
],
"ERANAMES": [
"\u0908\u0938\u093e.\u092a\u0942\u0930\u094d\u0935",
"\u0938\u0928"
],
"ERAS": [
"\u0908\u0938\u093e.\u092a\u0942\u0930\u094d\u0935",
"\u0938\u0928"
],
"FIRSTDAYOFWEEK": 0,
"MONTH": [
"\u091c\u093e\u0928\u0941\u0935\u093e\u0930\u0940",
"\u092b\u0947\u092c\u094d\u0930\u0941\u0935\u093e\u0930\u0940",
"\u092e\u093e\u0930\u094d\u0938",
"\u090f\u092b\u094d\u0930\u093f\u0932",
"\u092e\u0947",
"\u091c\u0941\u0928",
"\u091c\u0941\u0932\u093e\u0907",
"\u0906\u0917\u0938\u094d\u0925",
"\u0938\u0947\u092c\u0925\u0947\u091c\u094d\u092c\u093c\u0930",
"\u0905\u0916\u0925\u092c\u0930",
"\u0928\u092c\u0947\u091c\u094d\u092c\u093c\u0930",
"\u0926\u093f\u0938\u0947\u091c\u094d\u092c\u093c\u0930"
],
"SHORTDAY": [
"\u0930\u092c\u093f",
"\u0938\u092e",
"\u092e\u0902\u0917\u0932",
"\u092c\u0941\u0926",
"\u092c\u093f\u0938\u0925\u093f",
"\u0938\u0941\u0916\u0941\u0930",
"\u0938\u0941\u0928\u093f"
],
"SHORTMONTH": [
"\u091c\u093e\u0928\u0941\u0935\u093e\u0930\u0940",
"\u092b\u0947\u092c\u094d\u0930\u0941\u0935\u093e\u0930\u0940",
"\u092e\u093e\u0930\u094d\u0938",
"\u090f\u092b\u094d\u0930\u093f\u0932",
"\u092e\u0947",
"\u091c\u0941\u0928",
"\u091c\u0941\u0932\u093e\u0907",
"\u0906\u0917\u0938\u094d\u0925",
"\u0938\u0947\u092c\u0925\u0947\u091c\u094d\u092c\u093c\u0930",
"\u0905\u0916\u0925\u092c\u0930",
"\u0928\u092c\u0947\u091c\u094d\u092c\u093c\u0930",
"\u0926\u093f\u0938\u0947\u091c\u094d\u092c\u093c\u0930"
],
"WEEKENDRANGE": [
5,
6
],
"fullDate": "EEEE, MMMM d, y",
"longDate": "MMMM d, y",
"medium": "MMM d, y h:mm:ss a",
"mediumDate": "MMM d, y",
"mediumTime": "h:mm:ss a",
"short": "M/d/yy h:mm a",
"shortDate": "M/d/yy",
"shortTime": "h:mm a"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "\u20b9",
"DECIMAL_SEP": ".",
"GROUP_SEP": ",",
"PATTERNS": [
{
"gSize": 2,
"lgSize": 3,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 2,
"lgSize": 3,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "\u00a4\u00a0-",
"negSuf": "",
"posPre": "\u00a4\u00a0",
"posSuf": ""
}
]
},
"id": "brx-in",
"pluralCat": function(n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]);
| {'repo_name': 'aspnetboilerplate/aspnetboilerplate-samples', 'stars': '649', 'repo_language': 'JavaScript', 'file_name': 'ui-utils-ieshiv.js', 'mime_type': 'text/html', 'hash': 5039128649249068565, 'source_dataset': 'data'} |
/* 7zCrc.h -- CRC32 calculation
2009-11-21 : Igor Pavlov : Public domain */
#ifndef __7Z_CRC_H
#define __7Z_CRC_H
#include "Types.h"
EXTERN_C_BEGIN
extern const UInt32 g_CrcTable[];
#define CRC_INIT_VAL 0xFFFFFFFF
#define CRC_GET_DIGEST(crc) ((crc) ^ CRC_INIT_VAL)
#define CRC_UPDATE_BYTE(crc, b) (g_CrcTable[((crc) ^ (b)) & 0xFF] ^ ((crc) >> 8))
UInt32 MY_FAST_CALL CrcUpdate(UInt32 crc, const void *data, size_t size);
UInt32 MY_FAST_CALL CrcCalc(const void *data, size_t size);
EXTERN_C_END
#endif
| {'repo_name': 'Cisco-Talos/clamav-devel', 'stars': '1103', 'repo_language': 'C++', 'file_name': 'Makefile.am', 'mime_type': 'text/plain', 'hash': -2420051466061913392, 'source_dataset': 'data'} |
/****************************************************************************
* arch/mips/src/mips32/mips_blocktask.c
*
* Copyright (C) 2011, 2013-2015 Gregory Nutt. All rights reserved.
* Author: Gregory Nutt <[email protected]>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name NuttX nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#include <stdbool.h>
#include <sched.h>
#include <syscall.h>
#include <debug.h>
#include <nuttx/arch.h>
#include <nuttx/sched.h>
#include "sched/sched.h"
#include "group/group.h"
#include "mips_internal.h"
/****************************************************************************
* Public Functions
****************************************************************************/
/****************************************************************************
* Name: up_block_task
*
* Description:
* The currently executing task at the head of the ready to run list must
* be stopped. Save its context and move it to the inactive list
* specified by task_state.
*
* Input Parameters:
* tcb: Refers to a task in the ready-to-run list (normally the task at
* the head of the list). It must be stopped, its context saved and
* moved into one of the waiting task lists. If it was the task at the
* head of the ready-to-run list, then a context switch to the new
* ready to run task must be performed.
* task_state: Specifies which waiting task list should hold the blocked
* task TCB.
*
****************************************************************************/
void up_block_task(struct tcb_s *tcb, tstate_t task_state)
{
struct tcb_s *rtcb = this_task();
bool switch_needed;
/* Verify that the context switch can be performed */
DEBUGASSERT((tcb->task_state >= FIRST_READY_TO_RUN_STATE) &&
(tcb->task_state <= LAST_READY_TO_RUN_STATE));
/* Remove the tcb task from the ready-to-run list. If we are blocking the
* task at the head of the task list (the most likely case), then a
* context switch to the next ready-to-run task is needed. In this case,
* it should also be true that rtcb == tcb.
*/
switch_needed = nxsched_remove_readytorun(tcb);
/* Add the task to the specified blocked task list */
nxsched_add_blocked(tcb, (tstate_t)task_state);
/* If there are any pending tasks, then add them to the ready-to-run
* task list now
*/
if (g_pendingtasks.head)
{
switch_needed |= nxsched_merge_pending();
}
/* Now, perform the context switch if one is needed */
if (switch_needed)
{
/* Update scheduler parameters */
nxsched_suspend_scheduler(rtcb);
/* Are we in an interrupt handler? */
if (CURRENT_REGS)
{
/* Yes, then we have to do things differently.
* Just copy the g_current_regs into the OLD rtcb.
*/
up_savestate(rtcb->xcp.regs);
/* Restore the exception context of the rtcb at the (new) head
* of the ready-to-run task list.
*/
rtcb = this_task();
/* Reset scheduler parameters */
nxsched_resume_scheduler(rtcb);
/* Then switch contexts. Any necessary address environment
* changes will be made when the interrupt returns.
*/
up_restorestate(rtcb->xcp.regs);
}
/* No, then we will need to perform the user context switch */
else
{
/* Get the context of the task at the head of the ready to
* run list.
*/
struct tcb_s *nexttcb = this_task();
#ifdef CONFIG_ARCH_ADDRENV
/* Make sure that the address environment for the previously
* running task is closed down gracefully (data caches dump,
* MMU flushed) and set up the address environment for the new
* thread at the head of the ready-to-run list.
*/
group_addrenv(nexttcb);
#endif
/* Reset scheduler parameters */
nxsched_resume_scheduler(nexttcb);
/* Then switch contexts */
up_switchcontext(rtcb->xcp.regs, nexttcb->xcp.regs);
/* up_switchcontext forces a context switch to the task at the
* head of the ready-to-run list. It does not 'return' in the
* normal sense. When it does return, it is because the blocked
* task is again ready to run and has execution priority.
*/
}
}
}
| {'repo_name': 'apache/incubator-nuttx', 'stars': '181', 'repo_language': 'C', 'file_name': 'nrf52_uid.c', 'mime_type': 'text/x-c', 'hash': -6009482159773205554, 'source_dataset': 'data'} |
/*
Copyright 2015 The Kubernetes Authors All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package cm
import (
"k8s.io/kubernetes/pkg/api"
)
// Manages the containers running on a machine.
type ContainerManager interface {
// Runs the container manager's housekeeping.
// - Ensures that the Docker daemon is in a container.
// - Creates the system container where all non-containerized processes run.
Start() error
// Returns resources allocated to system cgroups in the machine.
// These cgroups include the system and Kubernetes services.
SystemCgroupsLimit() api.ResourceList
// Returns a NodeConfig that is being used by the container manager.
GetNodeConfig() NodeConfig
// Returns internal Status.
Status() Status
}
type NodeConfig struct {
RuntimeCgroupsName string
SystemCgroupsName string
KubeletCgroupsName string
ContainerRuntime string
}
type Status struct {
// Any soft requirements that were unsatisfied.
SoftRequirements error
}
| {'repo_name': 'redspread/localkube', 'stars': '179', 'repo_language': 'Go', 'file_name': 'main.go', 'mime_type': 'text/x-c', 'hash': -366990411608723591, 'source_dataset': 'data'} |
// +build !ignore_autogenerated
/*
Copyright 2017 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// This file was autogenerated by deepcopy-gen. Do not edit it manually!
package apps
import (
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
conversion "k8s.io/apimachinery/pkg/conversion"
runtime "k8s.io/apimachinery/pkg/runtime"
api "k8s.io/client-go/pkg/api"
reflect "reflect"
)
func init() {
SchemeBuilder.Register(RegisterDeepCopies)
}
// RegisterDeepCopies adds deep-copy functions to the given scheme. Public
// to allow building arbitrary schemes.
func RegisterDeepCopies(scheme *runtime.Scheme) error {
return scheme.AddGeneratedDeepCopyFuncs(
conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_apps_StatefulSet, InType: reflect.TypeOf(&StatefulSet{})},
conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_apps_StatefulSetList, InType: reflect.TypeOf(&StatefulSetList{})},
conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_apps_StatefulSetSpec, InType: reflect.TypeOf(&StatefulSetSpec{})},
conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_apps_StatefulSetStatus, InType: reflect.TypeOf(&StatefulSetStatus{})},
)
}
func DeepCopy_apps_StatefulSet(in interface{}, out interface{}, c *conversion.Cloner) error {
{
in := in.(*StatefulSet)
out := out.(*StatefulSet)
*out = *in
if newVal, err := c.DeepCopy(&in.ObjectMeta); err != nil {
return err
} else {
out.ObjectMeta = *newVal.(*v1.ObjectMeta)
}
if err := DeepCopy_apps_StatefulSetSpec(&in.Spec, &out.Spec, c); err != nil {
return err
}
if err := DeepCopy_apps_StatefulSetStatus(&in.Status, &out.Status, c); err != nil {
return err
}
return nil
}
}
func DeepCopy_apps_StatefulSetList(in interface{}, out interface{}, c *conversion.Cloner) error {
{
in := in.(*StatefulSetList)
out := out.(*StatefulSetList)
*out = *in
if in.Items != nil {
in, out := &in.Items, &out.Items
*out = make([]StatefulSet, len(*in))
for i := range *in {
if err := DeepCopy_apps_StatefulSet(&(*in)[i], &(*out)[i], c); err != nil {
return err
}
}
}
return nil
}
}
func DeepCopy_apps_StatefulSetSpec(in interface{}, out interface{}, c *conversion.Cloner) error {
{
in := in.(*StatefulSetSpec)
out := out.(*StatefulSetSpec)
*out = *in
if in.Selector != nil {
in, out := &in.Selector, &out.Selector
if newVal, err := c.DeepCopy(*in); err != nil {
return err
} else {
*out = newVal.(*v1.LabelSelector)
}
}
if err := api.DeepCopy_api_PodTemplateSpec(&in.Template, &out.Template, c); err != nil {
return err
}
if in.VolumeClaimTemplates != nil {
in, out := &in.VolumeClaimTemplates, &out.VolumeClaimTemplates
*out = make([]api.PersistentVolumeClaim, len(*in))
for i := range *in {
if err := api.DeepCopy_api_PersistentVolumeClaim(&(*in)[i], &(*out)[i], c); err != nil {
return err
}
}
}
return nil
}
}
func DeepCopy_apps_StatefulSetStatus(in interface{}, out interface{}, c *conversion.Cloner) error {
{
in := in.(*StatefulSetStatus)
out := out.(*StatefulSetStatus)
*out = *in
if in.ObservedGeneration != nil {
in, out := &in.ObservedGeneration, &out.ObservedGeneration
*out = new(int64)
**out = **in
}
return nil
}
}
| {'repo_name': 'elastos/Elastos', 'stars': '101', 'repo_language': 'Go', 'file_name': 'codereview.cfg', 'mime_type': 'text/plain', 'hash': 1608487334118733717, 'source_dataset': 'data'} |
/* Helloworld module -- A few examples of the Redis Modules API in the form
* of commands showing how to accomplish common tasks.
*
* This module does not do anything useful, if not for a few commands. The
* examples are designed in order to show the API.
*
* -----------------------------------------------------------------------------
*
* Copyright (c) 2016, Salvatore Sanfilippo <antirez at gmail dot com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Redis nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "../redismodule.h"
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
/* HELLO.SIMPLE is among the simplest commands you can implement.
* It just returns the currently selected DB id, a functionality which is
* missing in Redis. The command uses two important API calls: one to
* fetch the currently selected DB, the other in order to send the client
* an integer reply as response. */
int HelloSimple_RedisCommand(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) {
REDISMODULE_NOT_USED(argv);
REDISMODULE_NOT_USED(argc);
RedisModule_ReplyWithLongLong(ctx,RedisModule_GetSelectedDb(ctx));
return REDISMODULE_OK;
}
/* HELLO.PUSH.NATIVE re-implements RPUSH, and shows the low level modules API
* where you can "open" keys, make low level operations, create new keys by
* pushing elements into non-existing keys, and so forth.
*
* You'll find this command to be roughly as fast as the actual RPUSH
* command. */
int HelloPushNative_RedisCommand(RedisModuleCtx *ctx, RedisModuleString **argv, int argc)
{
if (argc != 3) return RedisModule_WrongArity(ctx);
RedisModuleKey *key = RedisModule_OpenKey(ctx,argv[1],
REDISMODULE_READ|REDISMODULE_WRITE);
RedisModule_ListPush(key,REDISMODULE_LIST_TAIL,argv[2]);
size_t newlen = RedisModule_ValueLength(key);
RedisModule_CloseKey(key);
RedisModule_ReplyWithLongLong(ctx,newlen);
return REDISMODULE_OK;
}
/* HELLO.PUSH.CALL implements RPUSH using an higher level approach, calling
* a Redis command instead of working with the key in a low level way. This
* approach is useful when you need to call Redis commands that are not
* available as low level APIs, or when you don't need the maximum speed
* possible but instead prefer implementation simplicity. */
int HelloPushCall_RedisCommand(RedisModuleCtx *ctx, RedisModuleString **argv, int argc)
{
if (argc != 3) return RedisModule_WrongArity(ctx);
RedisModuleCallReply *reply;
reply = RedisModule_Call(ctx,"RPUSH","ss",argv[1],argv[2]);
long long len = RedisModule_CallReplyInteger(reply);
RedisModule_FreeCallReply(reply);
RedisModule_ReplyWithLongLong(ctx,len);
return REDISMODULE_OK;
}
/* HELLO.PUSH.CALL2
* This is exaxctly as HELLO.PUSH.CALL, but shows how we can reply to the
* client using directly a reply object that Call() returned. */
int HelloPushCall2_RedisCommand(RedisModuleCtx *ctx, RedisModuleString **argv, int argc)
{
if (argc != 3) return RedisModule_WrongArity(ctx);
RedisModuleCallReply *reply;
reply = RedisModule_Call(ctx,"RPUSH","ss",argv[1],argv[2]);
RedisModule_ReplyWithCallReply(ctx,reply);
RedisModule_FreeCallReply(reply);
return REDISMODULE_OK;
}
/* HELLO.LIST.SUM.LEN returns the total length of all the items inside
* a Redis list, by using the high level Call() API.
* This command is an example of the array reply access. */
int HelloListSumLen_RedisCommand(RedisModuleCtx *ctx, RedisModuleString **argv, int argc)
{
if (argc != 2) return RedisModule_WrongArity(ctx);
RedisModuleCallReply *reply;
reply = RedisModule_Call(ctx,"LRANGE","sll",argv[1],(long long)0,(long long)-1);
size_t strlen = 0;
size_t items = RedisModule_CallReplyLength(reply);
size_t j;
for (j = 0; j < items; j++) {
RedisModuleCallReply *ele = RedisModule_CallReplyArrayElement(reply,j);
strlen += RedisModule_CallReplyLength(ele);
}
RedisModule_FreeCallReply(reply);
RedisModule_ReplyWithLongLong(ctx,strlen);
return REDISMODULE_OK;
}
/* HELLO.LIST.SPLICE srclist dstlist count
* Moves 'count' elements from the tail of 'srclist' to the head of
* 'dstlist'. If less than count elements are available, it moves as much
* elements as possible. */
int HelloListSplice_RedisCommand(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) {
if (argc != 4) return RedisModule_WrongArity(ctx);
RedisModuleKey *srckey = RedisModule_OpenKey(ctx,argv[1],
REDISMODULE_READ|REDISMODULE_WRITE);
RedisModuleKey *dstkey = RedisModule_OpenKey(ctx,argv[2],
REDISMODULE_READ|REDISMODULE_WRITE);
/* Src and dst key must be empty or lists. */
if ((RedisModule_KeyType(srckey) != REDISMODULE_KEYTYPE_LIST &&
RedisModule_KeyType(srckey) != REDISMODULE_KEYTYPE_EMPTY) ||
(RedisModule_KeyType(dstkey) != REDISMODULE_KEYTYPE_LIST &&
RedisModule_KeyType(dstkey) != REDISMODULE_KEYTYPE_EMPTY))
{
RedisModule_CloseKey(srckey);
RedisModule_CloseKey(dstkey);
return RedisModule_ReplyWithError(ctx,REDISMODULE_ERRORMSG_WRONGTYPE);
}
long long count;
if ((RedisModule_StringToLongLong(argv[3],&count) != REDISMODULE_OK) ||
(count < 0)) {
RedisModule_CloseKey(srckey);
RedisModule_CloseKey(dstkey);
return RedisModule_ReplyWithError(ctx,"ERR invalid count");
}
while(count-- > 0) {
RedisModuleString *ele;
ele = RedisModule_ListPop(srckey,REDISMODULE_LIST_TAIL);
if (ele == NULL) break;
RedisModule_ListPush(dstkey,REDISMODULE_LIST_HEAD,ele);
RedisModule_FreeString(ctx,ele);
}
size_t len = RedisModule_ValueLength(srckey);
RedisModule_CloseKey(srckey);
RedisModule_CloseKey(dstkey);
RedisModule_ReplyWithLongLong(ctx,len);
return REDISMODULE_OK;
}
/* Like the HELLO.LIST.SPLICE above, but uses automatic memory management
* in order to avoid freeing stuff. */
int HelloListSpliceAuto_RedisCommand(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) {
if (argc != 4) return RedisModule_WrongArity(ctx);
RedisModule_AutoMemory(ctx);
RedisModuleKey *srckey = RedisModule_OpenKey(ctx,argv[1],
REDISMODULE_READ|REDISMODULE_WRITE);
RedisModuleKey *dstkey = RedisModule_OpenKey(ctx,argv[2],
REDISMODULE_READ|REDISMODULE_WRITE);
/* Src and dst key must be empty or lists. */
if ((RedisModule_KeyType(srckey) != REDISMODULE_KEYTYPE_LIST &&
RedisModule_KeyType(srckey) != REDISMODULE_KEYTYPE_EMPTY) ||
(RedisModule_KeyType(dstkey) != REDISMODULE_KEYTYPE_LIST &&
RedisModule_KeyType(dstkey) != REDISMODULE_KEYTYPE_EMPTY))
{
return RedisModule_ReplyWithError(ctx,REDISMODULE_ERRORMSG_WRONGTYPE);
}
long long count;
if ((RedisModule_StringToLongLong(argv[3],&count) != REDISMODULE_OK) ||
(count < 0))
{
return RedisModule_ReplyWithError(ctx,"ERR invalid count");
}
while(count-- > 0) {
RedisModuleString *ele;
ele = RedisModule_ListPop(srckey,REDISMODULE_LIST_TAIL);
if (ele == NULL) break;
RedisModule_ListPush(dstkey,REDISMODULE_LIST_HEAD,ele);
}
size_t len = RedisModule_ValueLength(srckey);
RedisModule_ReplyWithLongLong(ctx,len);
return REDISMODULE_OK;
}
/* HELLO.RAND.ARRAY <count>
* Shows how to generate arrays as commands replies.
* It just outputs <count> random numbers. */
int HelloRandArray_RedisCommand(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) {
if (argc != 2) return RedisModule_WrongArity(ctx);
long long count;
if (RedisModule_StringToLongLong(argv[1],&count) != REDISMODULE_OK ||
count < 0)
return RedisModule_ReplyWithError(ctx,"ERR invalid count");
/* To reply with an array, we call RedisModule_ReplyWithArray() followed
* by other "count" calls to other reply functions in order to generate
* the elements of the array. */
RedisModule_ReplyWithArray(ctx,count);
while(count--) RedisModule_ReplyWithLongLong(ctx,rand());
return REDISMODULE_OK;
}
/* This is a simple command to test replication. Because of the "!" modified
* in the RedisModule_Call() call, the two INCRs get replicated.
* Also note how the ECHO is replicated in an unexpected position (check
* comments the function implementation). */
int HelloRepl1_RedisCommand(RedisModuleCtx *ctx, RedisModuleString **argv, int argc)
{
REDISMODULE_NOT_USED(argv);
REDISMODULE_NOT_USED(argc);
RedisModule_AutoMemory(ctx);
/* This will be replicated *after* the two INCR statements, since
* the Call() replication has precedence, so the actual replication
* stream will be:
*
* MULTI
* INCR foo
* INCR bar
* ECHO c foo
* EXEC
*/
RedisModule_Replicate(ctx,"ECHO","c","foo");
/* Using the "!" modifier we replicate the command if it
* modified the dataset in some way. */
RedisModule_Call(ctx,"INCR","c!","foo");
RedisModule_Call(ctx,"INCR","c!","bar");
RedisModule_ReplyWithLongLong(ctx,0);
return REDISMODULE_OK;
}
/* Another command to show replication. In this case, we call
* RedisModule_ReplicateVerbatim() to mean we want just the command to be
* propagated to slaves / AOF exactly as it was called by the user.
*
* This command also shows how to work with string objects.
* It takes a list, and increments all the elements (that must have
* a numerical value) by 1, returning the sum of all the elements
* as reply.
*
* Usage: HELLO.REPL2 <list-key> */
int HelloRepl2_RedisCommand(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) {
if (argc != 2) return RedisModule_WrongArity(ctx);
RedisModule_AutoMemory(ctx); /* Use automatic memory management. */
RedisModuleKey *key = RedisModule_OpenKey(ctx,argv[1],
REDISMODULE_READ|REDISMODULE_WRITE);
if (RedisModule_KeyType(key) != REDISMODULE_KEYTYPE_LIST)
return RedisModule_ReplyWithError(ctx,REDISMODULE_ERRORMSG_WRONGTYPE);
size_t listlen = RedisModule_ValueLength(key);
long long sum = 0;
/* Rotate and increment. */
while(listlen--) {
RedisModuleString *ele = RedisModule_ListPop(key,REDISMODULE_LIST_TAIL);
long long val;
if (RedisModule_StringToLongLong(ele,&val) != REDISMODULE_OK) val = 0;
val++;
sum += val;
RedisModuleString *newele = RedisModule_CreateStringFromLongLong(ctx,val);
RedisModule_ListPush(key,REDISMODULE_LIST_HEAD,newele);
}
RedisModule_ReplyWithLongLong(ctx,sum);
RedisModule_ReplicateVerbatim(ctx);
return REDISMODULE_OK;
}
/* This is an example of strings DMA access. Given a key containing a string
* it toggles the case of each character from lower to upper case or the
* other way around.
*
* No automatic memory management is used in this example (for the sake
* of variety).
*
* HELLO.TOGGLE.CASE key */
int HelloToggleCase_RedisCommand(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) {
if (argc != 2) return RedisModule_WrongArity(ctx);
RedisModuleKey *key = RedisModule_OpenKey(ctx,argv[1],
REDISMODULE_READ|REDISMODULE_WRITE);
int keytype = RedisModule_KeyType(key);
if (keytype != REDISMODULE_KEYTYPE_STRING &&
keytype != REDISMODULE_KEYTYPE_EMPTY)
{
RedisModule_CloseKey(key);
return RedisModule_ReplyWithError(ctx,REDISMODULE_ERRORMSG_WRONGTYPE);
}
if (keytype == REDISMODULE_KEYTYPE_STRING) {
size_t len, j;
char *s = RedisModule_StringDMA(key,&len,REDISMODULE_WRITE);
for (j = 0; j < len; j++) {
if (isupper(s[j])) {
s[j] = tolower(s[j]);
} else {
s[j] = toupper(s[j]);
}
}
}
RedisModule_CloseKey(key);
RedisModule_ReplyWithSimpleString(ctx,"OK");
RedisModule_ReplicateVerbatim(ctx);
return REDISMODULE_OK;
}
/* HELLO.MORE.EXPIRE key milliseconds.
*
* If they key has already an associated TTL, extends it by "milliseconds"
* milliseconds. Otherwise no operation is performed. */
int HelloMoreExpire_RedisCommand(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) {
RedisModule_AutoMemory(ctx); /* Use automatic memory management. */
if (argc != 3) return RedisModule_WrongArity(ctx);
mstime_t addms, expire;
if (RedisModule_StringToLongLong(argv[2],&addms) != REDISMODULE_OK)
return RedisModule_ReplyWithError(ctx,"ERR invalid expire time");
RedisModuleKey *key = RedisModule_OpenKey(ctx,argv[1],
REDISMODULE_READ|REDISMODULE_WRITE);
expire = RedisModule_GetExpire(key);
if (expire != REDISMODULE_NO_EXPIRE) {
expire += addms;
RedisModule_SetExpire(key,expire);
}
return RedisModule_ReplyWithSimpleString(ctx,"OK");
}
/* HELLO.ZSUMRANGE key startscore endscore
* Return the sum of all the scores elements between startscore and endscore.
*
* The computation is performed two times, one time from start to end and
* another time backward. The two scores, returned as a two element array,
* should match.*/
int HelloZsumRange_RedisCommand(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) {
double score_start, score_end;
if (argc != 4) return RedisModule_WrongArity(ctx);
if (RedisModule_StringToDouble(argv[2],&score_start) != REDISMODULE_OK ||
RedisModule_StringToDouble(argv[3],&score_end) != REDISMODULE_OK)
{
return RedisModule_ReplyWithError(ctx,"ERR invalid range");
}
RedisModuleKey *key = RedisModule_OpenKey(ctx,argv[1],
REDISMODULE_READ|REDISMODULE_WRITE);
if (RedisModule_KeyType(key) != REDISMODULE_KEYTYPE_ZSET) {
return RedisModule_ReplyWithError(ctx,REDISMODULE_ERRORMSG_WRONGTYPE);
}
double scoresum_a = 0;
double scoresum_b = 0;
RedisModule_ZsetFirstInScoreRange(key,score_start,score_end,0,0);
while(!RedisModule_ZsetRangeEndReached(key)) {
double score;
RedisModuleString *ele = RedisModule_ZsetRangeCurrentElement(key,&score);
RedisModule_FreeString(ctx,ele);
scoresum_a += score;
RedisModule_ZsetRangeNext(key);
}
RedisModule_ZsetRangeStop(key);
RedisModule_ZsetLastInScoreRange(key,score_start,score_end,0,0);
while(!RedisModule_ZsetRangeEndReached(key)) {
double score;
RedisModuleString *ele = RedisModule_ZsetRangeCurrentElement(key,&score);
RedisModule_FreeString(ctx,ele);
scoresum_b += score;
RedisModule_ZsetRangePrev(key);
}
RedisModule_ZsetRangeStop(key);
RedisModule_CloseKey(key);
RedisModule_ReplyWithArray(ctx,2);
RedisModule_ReplyWithDouble(ctx,scoresum_a);
RedisModule_ReplyWithDouble(ctx,scoresum_b);
return REDISMODULE_OK;
}
/* HELLO.LEXRANGE key min_lex max_lex min_age max_age
* This command expects a sorted set stored at key in the following form:
* - All the elements have score 0.
* - Elements are pairs of "<name>:<age>", for example "Anna:52".
* The command will return all the sorted set items that are lexicographically
* between the specified range (using the same format as ZRANGEBYLEX)
* and having an age between min_age and max_age. */
int HelloLexRange_RedisCommand(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) {
RedisModule_AutoMemory(ctx); /* Use automatic memory management. */
if (argc != 6) return RedisModule_WrongArity(ctx);
RedisModuleKey *key = RedisModule_OpenKey(ctx,argv[1],
REDISMODULE_READ|REDISMODULE_WRITE);
if (RedisModule_KeyType(key) != REDISMODULE_KEYTYPE_ZSET) {
return RedisModule_ReplyWithError(ctx,REDISMODULE_ERRORMSG_WRONGTYPE);
}
if (RedisModule_ZsetFirstInLexRange(key,argv[2],argv[3]) != REDISMODULE_OK) {
return RedisModule_ReplyWithError(ctx,"invalid range");
}
int arraylen = 0;
RedisModule_ReplyWithArray(ctx,REDISMODULE_POSTPONED_ARRAY_LEN);
while(!RedisModule_ZsetRangeEndReached(key)) {
double score;
RedisModuleString *ele = RedisModule_ZsetRangeCurrentElement(key,&score);
RedisModule_ReplyWithString(ctx,ele);
RedisModule_FreeString(ctx,ele);
RedisModule_ZsetRangeNext(key);
arraylen++;
}
RedisModule_ZsetRangeStop(key);
RedisModule_ReplySetArrayLength(ctx,arraylen);
RedisModule_CloseKey(key);
return REDISMODULE_OK;
}
/* HELLO.HCOPY key srcfield dstfield
* This is just an example command that sets the hash field dstfield to the
* same value of srcfield. If srcfield does not exist no operation is
* performed.
*
* The command returns 1 if the copy is performed (srcfield exists) otherwise
* 0 is returned. */
int HelloHCopy_RedisCommand(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) {
RedisModule_AutoMemory(ctx); /* Use automatic memory management. */
if (argc != 4) return RedisModule_WrongArity(ctx);
RedisModuleKey *key = RedisModule_OpenKey(ctx,argv[1],
REDISMODULE_READ|REDISMODULE_WRITE);
int type = RedisModule_KeyType(key);
if (type != REDISMODULE_KEYTYPE_HASH &&
type != REDISMODULE_KEYTYPE_EMPTY)
{
return RedisModule_ReplyWithError(ctx,REDISMODULE_ERRORMSG_WRONGTYPE);
}
/* Get the old field value. */
RedisModuleString *oldval;
RedisModule_HashGet(key,REDISMODULE_HASH_NONE,argv[2],&oldval,NULL);
if (oldval) {
RedisModule_HashSet(key,REDISMODULE_HASH_NONE,argv[3],oldval,NULL);
}
RedisModule_ReplyWithLongLong(ctx,oldval != NULL);
return REDISMODULE_OK;
}
/* HELLO.LEFTPAD str len ch
* This is an implementation of the infamous LEFTPAD function, that
* was at the center of an issue with the npm modules system in March 2016.
*
* LEFTPAD is a good example of using a Redis Modules API called
* "pool allocator", that was a famous way to allocate memory in yet another
* open source project, the Apache web server.
*
* The concept is very simple: there is memory that is useful to allocate
* only in the context of serving a request, and must be freed anyway when
* the callback implementing the command returns. So in that case the module
* does not need to retain a reference to these allocations, it is just
* required to free the memory before returning. When this is the case the
* module can call RedisModule_PoolAlloc() instead, that works like malloc()
* but will automatically free the memory when the module callback returns.
*
* Note that PoolAlloc() does not necessarily require AutoMemory to be
* active. */
int HelloLeftPad_RedisCommand(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) {
RedisModule_AutoMemory(ctx); /* Use automatic memory management. */
long long padlen;
if (argc != 4) return RedisModule_WrongArity(ctx);
if ((RedisModule_StringToLongLong(argv[2],&padlen) != REDISMODULE_OK) ||
(padlen< 0)) {
return RedisModule_ReplyWithError(ctx,"ERR invalid padding length");
}
size_t strlen, chlen;
const char *str = RedisModule_StringPtrLen(argv[1], &strlen);
const char *ch = RedisModule_StringPtrLen(argv[3], &chlen);
/* If the string is already larger than the target len, just return
* the string itself. */
if (strlen >= (size_t)padlen)
return RedisModule_ReplyWithString(ctx,argv[1]);
/* Padding must be a single character in this simple implementation. */
if (chlen != 1)
return RedisModule_ReplyWithError(ctx,
"ERR padding must be a single char");
/* Here we use our pool allocator, for our throw-away allocation. */
padlen -= strlen;
char *buf = RedisModule_PoolAlloc(ctx,padlen+strlen);
for (long long j = 0; j < padlen; j++) buf[j] = *ch;
memcpy(buf+padlen,str,strlen);
RedisModule_ReplyWithStringBuffer(ctx,buf,padlen+strlen);
return REDISMODULE_OK;
}
/* This function must be present on each Redis module. It is used in order to
* register the commands into the Redis server. */
int RedisModule_OnLoad(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) {
if (RedisModule_Init(ctx,"helloworld",1,REDISMODULE_APIVER_1)
== REDISMODULE_ERR) return REDISMODULE_ERR;
/* Log the list of parameters passing loading the module. */
for (int j = 0; j < argc; j++) {
const char *s = RedisModule_StringPtrLen(argv[j],NULL);
printf("Module loaded with ARGV[%d] = %s\n", j, s);
}
if (RedisModule_CreateCommand(ctx,"hello.simple",
HelloSimple_RedisCommand,"readonly",0,0,0) == REDISMODULE_ERR)
return REDISMODULE_ERR;
if (RedisModule_CreateCommand(ctx,"hello.push.native",
HelloPushNative_RedisCommand,"write deny-oom",1,1,1) == REDISMODULE_ERR)
return REDISMODULE_ERR;
if (RedisModule_CreateCommand(ctx,"hello.push.call",
HelloPushCall_RedisCommand,"write deny-oom",1,1,1) == REDISMODULE_ERR)
return REDISMODULE_ERR;
if (RedisModule_CreateCommand(ctx,"hello.push.call2",
HelloPushCall2_RedisCommand,"write deny-oom",1,1,1) == REDISMODULE_ERR)
return REDISMODULE_ERR;
if (RedisModule_CreateCommand(ctx,"hello.list.sum.len",
HelloListSumLen_RedisCommand,"readonly",1,1,1) == REDISMODULE_ERR)
return REDISMODULE_ERR;
if (RedisModule_CreateCommand(ctx,"hello.list.splice",
HelloListSplice_RedisCommand,"write deny-oom",1,2,1) == REDISMODULE_ERR)
return REDISMODULE_ERR;
if (RedisModule_CreateCommand(ctx,"hello.list.splice.auto",
HelloListSpliceAuto_RedisCommand,
"write deny-oom",1,2,1) == REDISMODULE_ERR)
return REDISMODULE_ERR;
if (RedisModule_CreateCommand(ctx,"hello.rand.array",
HelloRandArray_RedisCommand,"readonly",0,0,0) == REDISMODULE_ERR)
return REDISMODULE_ERR;
if (RedisModule_CreateCommand(ctx,"hello.repl1",
HelloRepl1_RedisCommand,"write",0,0,0) == REDISMODULE_ERR)
return REDISMODULE_ERR;
if (RedisModule_CreateCommand(ctx,"hello.repl2",
HelloRepl2_RedisCommand,"write",1,1,1) == REDISMODULE_ERR)
return REDISMODULE_ERR;
if (RedisModule_CreateCommand(ctx,"hello.toggle.case",
HelloToggleCase_RedisCommand,"write",1,1,1) == REDISMODULE_ERR)
return REDISMODULE_ERR;
if (RedisModule_CreateCommand(ctx,"hello.more.expire",
HelloMoreExpire_RedisCommand,"write",1,1,1) == REDISMODULE_ERR)
return REDISMODULE_ERR;
if (RedisModule_CreateCommand(ctx,"hello.zsumrange",
HelloZsumRange_RedisCommand,"readonly",1,1,1) == REDISMODULE_ERR)
return REDISMODULE_ERR;
if (RedisModule_CreateCommand(ctx,"hello.lexrange",
HelloLexRange_RedisCommand,"readonly",1,1,1) == REDISMODULE_ERR)
return REDISMODULE_ERR;
if (RedisModule_CreateCommand(ctx,"hello.hcopy",
HelloHCopy_RedisCommand,"write deny-oom",1,1,1) == REDISMODULE_ERR)
return REDISMODULE_ERR;
if (RedisModule_CreateCommand(ctx,"hello.leftpad",
HelloLeftPad_RedisCommand,"",1,1,1) == REDISMODULE_ERR)
return REDISMODULE_ERR;
return REDISMODULE_OK;
}
| {'repo_name': 'chenyahui/AnnotatedCode', 'stars': '317', 'repo_language': 'C', 'file_name': 'BoundedBlockingQueue_test.cc', 'mime_type': 'text/x-c++', 'hash': -3987201554966416224, 'source_dataset': 'data'} |
<?xml version="1.0" encoding="UTF-8"?>
<debug-info version="2">
<concept fqn="c:f3061a53-9226-4cc5-a443-f952ceaf5816/1068580123140:jetbrains.mps.baseLanguage.structure.ConstructorDeclaration" />
<concept fqn="c:f3061a53-9226-4cc5-a443-f952ceaf5816/1068580123155:jetbrains.mps.baseLanguage.structure.ExpressionStatement" />
<concept fqn="c:f3061a53-9226-4cc5-a443-f952ceaf5816/1068390468200:jetbrains.mps.baseLanguage.structure.FieldDeclaration" />
<concept fqn="c:f3061a53-9226-4cc5-a443-f952ceaf5816/1068580123165:jetbrains.mps.baseLanguage.structure.InstanceMethodDeclaration" />
<concept fqn="c:f3061a53-9226-4cc5-a443-f952ceaf5816/1068581242864:jetbrains.mps.baseLanguage.structure.LocalVariableDeclarationStatement" />
<concept fqn="c:f3061a53-9226-4cc5-a443-f952ceaf5816/1068581242878:jetbrains.mps.baseLanguage.structure.ReturnStatement" />
<concept fqn="c:f3061a53-9226-4cc5-a443-f952ceaf5816/1081236700938:jetbrains.mps.baseLanguage.structure.StaticMethodDeclaration" />
<root nodeRef="r:19bf018c-b5e7-418d-8415-b23921421325(sandboxModel)/1751004816843423273">
<file name="fixpoint.java">
<node id="1751004816843423273" at="12,42,13,33" concept="1" />
<node id="1751004816843423273" at="15,31,16,46" concept="5" />
<node id="1751004816843424603" at="19,0,20,0" concept="2" trace="myOuterVars" />
<node id="1751004816843424603" at="20,43,21,47" concept="1" />
<node id="1751004816843424603" at="23,57,24,47" concept="1" />
<node id="1751004816843424603" at="24,47,25,36" concept="1" />
<node id="1751004816843424603" at="27,26,28,16" concept="4" />
<node id="1751004816843424603" at="28,16,29,16" concept="4" />
<node id="1751004816843424605" at="29,16,30,46" concept="4" />
<node id="1751004816843424603" at="30,46,31,85" concept="5" />
<node id="1751004816843424603" at="33,33,34,15" concept="5" />
<node id="1751004816843424603" at="36,28,37,59" concept="5" />
<node id="1751004816843561803" at="40,0,41,0" concept="2" trace="myOuterVars" />
<node id="1751004816843561803" at="41,55,42,49" concept="1" />
<node id="1751004816843424605" at="42,49,43,27" concept="1" />
<node id="1751004816843561803" at="45,59,46,49" concept="1" />
<node id="1751004816843561803" at="46,49,47,38" concept="1" />
<node id="1751004816843561803" at="49,28,50,18" concept="4" />
<node id="1751004816843561803" at="50,18,51,18" concept="4" />
<node id="1751004816843424605" at="51,18,52,53" concept="4" />
<node id="1751004816843561804" at="52,53,53,48" concept="4" />
<node id="1751004816843561803" at="53,48,54,79" concept="5" />
<node id="1751004816843561803" at="56,35,57,17" concept="5" />
<node id="1751004816843561803" at="59,30,60,61" concept="5" />
<node id="1751004816843561372" at="63,82,64,77" concept="5" />
<node id="1751004816843423273" at="10,0,12,0" concept="0" trace="fixpoint#()V" />
<node id="1751004816843423273" at="12,0,15,0" concept="6" trace="main#([Ljava/lang/String;)V" />
<node id="1751004816843423273" at="15,0,18,0" concept="6" trace="eval#()Ljava/lang/Object;" />
<node id="1751004816843424603" at="20,0,23,0" concept="0" trace="Function_1751004816843424603#()V" />
<node id="1751004816843424603" at="33,0,36,0" concept="3" trace="getParamsCount#()I" />
<node id="1751004816843424603" at="36,0,39,0" concept="3" trace="copy#()Ljetbrains/mps/samples/lambdaCalculus/runtime/Function;" />
<node id="1751004816843561803" at="56,0,59,0" concept="3" trace="getParamsCount#()I" />
<node id="1751004816843561803" at="59,0,62,0" concept="3" trace="copy#()Ljetbrains/mps/samples/lambdaCalculus/runtime/Function;" />
<node id="1751004816843561372" at="63,0,66,0" concept="6" trace="lambdaAbstr_1751004816843424696#(Ljetbrains/mps/samples/lambdaCalculus/runtime/Function;Ljetbrains/mps/samples/lambdaCalculus/runtime/Function;)Ljava/lang/Object;" />
<node id="1751004816843424603" at="23,0,27,0" concept="0" trace="Function_1751004816843424603#(Ljava/util/List;)V" />
<node id="1751004816843561803" at="41,0,45,0" concept="0" trace="Function_1751004816843561803#(Ljetbrains/mps/samples/lambdaCalculus/runtime/Function;)V" />
<node id="1751004816843561803" at="45,0,49,0" concept="0" trace="Function_1751004816843561803#(Ljava/util/List;)V" />
<node id="1751004816843424603" at="27,0,33,0" concept="3" trace="eval#()Ljava/lang/Object;" />
<node id="1751004816843561803" at="49,0,56,0" concept="3" trace="eval#()Ljava/lang/Object;" />
<scope id="1751004816843423273" at="10,21,10,21" />
<scope id="1751004816843423273" at="12,42,13,33" />
<scope id="1751004816843423273" at="15,31,16,46" />
<scope id="1751004816843424603" at="20,43,21,47" />
<scope id="1751004816843424603" at="33,33,34,15" />
<scope id="1751004816843424603" at="36,28,37,59" />
<scope id="1751004816843561803" at="56,35,57,17" />
<scope id="1751004816843561803" at="59,30,60,61" />
<scope id="1751004816843561372" at="63,82,64,77" />
<scope id="1751004816843423273" at="10,0,12,0" />
<scope id="1751004816843424603" at="23,57,25,36" />
<scope id="1751004816843561803" at="41,55,43,27" />
<scope id="1751004816843561803" at="45,59,47,38" />
<scope id="1751004816843423273" at="12,0,15,0">
<var name="args" id="1751004816843423273" />
</scope>
<scope id="1751004816843423273" at="15,0,18,0" />
<scope id="1751004816843424603" at="20,0,23,0" />
<scope id="1751004816843424603" at="33,0,36,0" />
<scope id="1751004816843424603" at="36,0,39,0" />
<scope id="1751004816843561803" at="56,0,59,0" />
<scope id="1751004816843561803" at="59,0,62,0" />
<scope id="1751004816843561372" at="63,0,66,0">
<var name="f" id="1751004816843424605" />
<var name="x" id="1751004816843424698" />
</scope>
<scope id="1751004816843424603" at="23,0,27,0">
<var name="outerVars" id="1751004816843424603" />
</scope>
<scope id="1751004816843424603" at="27,26,31,85">
<var name="f" id="1751004816843424605" />
<var name="i" id="1751004816843424603" />
<var name="j" id="1751004816843424603" />
</scope>
<scope id="1751004816843561803" at="41,0,45,0">
<var name="f" id="1751004816843424605" />
</scope>
<scope id="1751004816843561803" at="45,0,49,0">
<var name="outerVars" id="1751004816843561803" />
</scope>
<scope id="1751004816843561803" at="49,28,54,79">
<var name="f" id="1751004816843424605" />
<var name="i" id="1751004816843561803" />
<var name="j" id="1751004816843561803" />
<var name="x" id="1751004816843561804" />
</scope>
<scope id="1751004816843424603" at="27,0,33,0" />
<scope id="1751004816843561803" at="49,0,56,0" />
<unit id="1751004816843561803" at="39,0,63,0" name="sandboxModel.fixpoint$Function_1751004816843424603$Function_1751004816843561803" />
<unit id="1751004816843424603" at="18,0,67,0" name="sandboxModel.fixpoint$Function_1751004816843424603" />
<unit id="1751004816843423273" at="9,0,68,0" name="sandboxModel.fixpoint" />
</file>
</root>
<root nodeRef="r:19bf018c-b5e7-418d-8415-b23921421325(sandboxModel)/1751004816843565387">
<file name="minimalTypeTest.java">
<node id="1751004816843565387" at="12,42,13,33" concept="1" />
<node id="1751004816843565387" at="15,31,16,46" concept="5" />
<node id="1751004816843568058" at="19,0,20,0" concept="2" trace="myOuterVars" />
<node id="1751004816843568058" at="20,43,21,47" concept="1" />
<node id="1751004816843568058" at="23,57,24,47" concept="1" />
<node id="1751004816843568058" at="24,47,25,36" concept="1" />
<node id="1751004816843568058" at="27,26,28,16" concept="4" />
<node id="1751004816843568058" at="28,16,29,16" concept="4" />
<node id="1751004816843568060" at="29,16,30,46" concept="4" />
<node id="1751004816843568058" at="30,46,31,46" concept="5" />
<node id="1751004816843568058" at="33,33,34,15" concept="5" />
<node id="1751004816843568058" at="36,28,37,59" concept="5" />
<node id="1751004816843565387" at="10,0,12,0" concept="0" trace="minimalTypeTest#()V" />
<node id="1751004816843565387" at="12,0,15,0" concept="6" trace="main#([Ljava/lang/String;)V" />
<node id="1751004816843565387" at="15,0,18,0" concept="6" trace="eval#()Ljava/lang/Object;" />
<node id="1751004816843568058" at="20,0,23,0" concept="0" trace="Function_1751004816843568058#()V" />
<node id="1751004816843568058" at="33,0,36,0" concept="3" trace="getParamsCount#()I" />
<node id="1751004816843568058" at="36,0,39,0" concept="3" trace="copy#()Ljetbrains/mps/samples/lambdaCalculus/runtime/Function;" />
<node id="1751004816843568058" at="23,0,27,0" concept="0" trace="Function_1751004816843568058#(Ljava/util/List;)V" />
<node id="1751004816843568058" at="27,0,33,0" concept="3" trace="eval#()Ljava/lang/Object;" />
<scope id="1751004816843565387" at="10,28,10,28" />
<scope id="1751004816843565387" at="12,42,13,33" />
<scope id="1751004816843565387" at="15,31,16,46" />
<scope id="1751004816843568058" at="20,43,21,47" />
<scope id="1751004816843568058" at="33,33,34,15" />
<scope id="1751004816843568058" at="36,28,37,59" />
<scope id="1751004816843565387" at="10,0,12,0" />
<scope id="1751004816843568058" at="23,57,25,36" />
<scope id="1751004816843565387" at="12,0,15,0">
<var name="args" id="1751004816843565387" />
</scope>
<scope id="1751004816843565387" at="15,0,18,0" />
<scope id="1751004816843568058" at="20,0,23,0" />
<scope id="1751004816843568058" at="33,0,36,0" />
<scope id="1751004816843568058" at="36,0,39,0" />
<scope id="1751004816843568058" at="23,0,27,0">
<var name="outerVars" id="1751004816843568058" />
</scope>
<scope id="1751004816843568058" at="27,26,31,46">
<var name="i" id="1751004816843568058" />
<var name="j" id="1751004816843568058" />
<var name="x" id="1751004816843568060" />
</scope>
<scope id="1751004816843568058" at="27,0,33,0" />
<unit id="1751004816843568058" at="18,0,40,0" name="sandboxModel.minimalTypeTest$Function_1751004816843568058" />
<unit id="1751004816843565387" at="9,0,41,0" name="sandboxModel.minimalTypeTest" />
</file>
</root>
<root nodeRef="r:19bf018c-b5e7-418d-8415-b23921421325(sandboxModel)/1751004816843669401">
<file name="biggerTypeTest1.java">
<node id="1751004816843669401" at="12,42,13,33" concept="1" />
<node id="1751004816843669401" at="15,31,16,46" concept="5" />
<node id="1751004816843669402" at="19,0,20,0" concept="2" trace="myOuterVars" />
<node id="1751004816843669402" at="20,43,21,80" concept="1" />
<node id="1751004816843669402" at="23,57,24,80" concept="1" />
<node id="1751004816843669402" at="24,80,25,36" concept="1" />
<node id="1751004816843669402" at="27,26,28,16" concept="4" />
<node id="1751004816843669402" at="28,16,29,16" concept="4" />
<node id="1751004816843669403" at="29,16,30,46" concept="4" />
<node id="1751004816843897735" at="30,46,31,46" concept="4" />
<node id="1751004816843669402" at="31,46,32,77" concept="5" />
<node id="1751004816843669402" at="34,33,35,15" concept="5" />
<node id="1751004816843669402" at="37,28,38,59" concept="5" />
<node id="1751004816843669401" at="10,0,12,0" concept="0" trace="biggerTypeTest1#()V" />
<node id="1751004816843669401" at="12,0,15,0" concept="6" trace="main#([Ljava/lang/String;)V" />
<node id="1751004816843669401" at="15,0,18,0" concept="6" trace="eval#()Ljava/lang/Object;" />
<node id="1751004816843669402" at="20,0,23,0" concept="0" trace="Function_1751004816843669402#()V" />
<node id="1751004816843669402" at="34,0,37,0" concept="3" trace="getParamsCount#()I" />
<node id="1751004816843669402" at="37,0,40,0" concept="3" trace="copy#()Ljetbrains/mps/samples/lambdaCalculus/runtime/Function;" />
<node id="1751004816843669402" at="23,0,27,0" concept="0" trace="Function_1751004816843669402#(Ljava/util/List;)V" />
<node id="1751004816843669402" at="27,0,34,0" concept="3" trace="eval#()Ljava/lang/Object;" />
<scope id="1751004816843669401" at="10,28,10,28" />
<scope id="1751004816843669401" at="12,42,13,33" />
<scope id="1751004816843669401" at="15,31,16,46" />
<scope id="1751004816843669402" at="20,43,21,80" />
<scope id="1751004816843669402" at="34,33,35,15" />
<scope id="1751004816843669402" at="37,28,38,59" />
<scope id="1751004816843669401" at="10,0,12,0" />
<scope id="1751004816843669402" at="23,57,25,36" />
<scope id="1751004816843669401" at="12,0,15,0">
<var name="args" id="1751004816843669401" />
</scope>
<scope id="1751004816843669401" at="15,0,18,0" />
<scope id="1751004816843669402" at="20,0,23,0" />
<scope id="1751004816843669402" at="34,0,37,0" />
<scope id="1751004816843669402" at="37,0,40,0" />
<scope id="1751004816843669402" at="23,0,27,0">
<var name="outerVars" id="1751004816843669402" />
</scope>
<scope id="1751004816843669402" at="27,26,32,77">
<var name="i" id="1751004816843669402" />
<var name="j" id="1751004816843669402" />
<var name="x" id="1751004816843669403" />
<var name="y" id="1751004816843897735" />
</scope>
<scope id="1751004816843669402" at="27,0,34,0" />
<unit id="1751004816843669402" at="18,0,41,0" name="sandboxModel.biggerTypeTest1$Function_1751004816843669402" />
<unit id="1751004816843669401" at="9,0,42,0" name="sandboxModel.biggerTypeTest1" />
</file>
</root>
<root nodeRef="r:19bf018c-b5e7-418d-8415-b23921421325(sandboxModel)/1751004816844298779">
<file name="biggerTypeTest2.java">
<node id="1751004816844298779" at="12,42,13,33" concept="1" />
<node id="1751004816844298779" at="15,31,16,46" concept="5" />
<node id="1751004816844298780" at="19,0,20,0" concept="2" trace="myOuterVars" />
<node id="1751004816844298780" at="20,43,21,80" concept="1" />
<node id="1751004816844298780" at="23,57,24,80" concept="1" />
<node id="1751004816844298780" at="24,80,25,36" concept="1" />
<node id="1751004816844298780" at="27,26,28,16" concept="4" />
<node id="1751004816844298780" at="28,16,29,16" concept="4" />
<node id="1751004816844298781" at="29,16,30,46" concept="4" />
<node id="1751004816844299683" at="30,46,31,46" concept="4" />
<node id="1751004816844298780" at="31,46,32,77" concept="5" />
<node id="1751004816844298780" at="34,33,35,15" concept="5" />
<node id="1751004816844298780" at="37,28,38,59" concept="5" />
<node id="1751004816844298779" at="10,0,12,0" concept="0" trace="biggerTypeTest2#()V" />
<node id="1751004816844298779" at="12,0,15,0" concept="6" trace="main#([Ljava/lang/String;)V" />
<node id="1751004816844298779" at="15,0,18,0" concept="6" trace="eval#()Ljava/lang/Object;" />
<node id="1751004816844298780" at="20,0,23,0" concept="0" trace="Function_1751004816844298780#()V" />
<node id="1751004816844298780" at="34,0,37,0" concept="3" trace="getParamsCount#()I" />
<node id="1751004816844298780" at="37,0,40,0" concept="3" trace="copy#()Ljetbrains/mps/samples/lambdaCalculus/runtime/Function;" />
<node id="1751004816844298780" at="23,0,27,0" concept="0" trace="Function_1751004816844298780#(Ljava/util/List;)V" />
<node id="1751004816844298780" at="27,0,34,0" concept="3" trace="eval#()Ljava/lang/Object;" />
<scope id="1751004816844298779" at="10,28,10,28" />
<scope id="1751004816844298779" at="12,42,13,33" />
<scope id="1751004816844298779" at="15,31,16,46" />
<scope id="1751004816844298780" at="20,43,21,80" />
<scope id="1751004816844298780" at="34,33,35,15" />
<scope id="1751004816844298780" at="37,28,38,59" />
<scope id="1751004816844298779" at="10,0,12,0" />
<scope id="1751004816844298780" at="23,57,25,36" />
<scope id="1751004816844298779" at="12,0,15,0">
<var name="args" id="1751004816844298779" />
</scope>
<scope id="1751004816844298779" at="15,0,18,0" />
<scope id="1751004816844298780" at="20,0,23,0" />
<scope id="1751004816844298780" at="34,0,37,0" />
<scope id="1751004816844298780" at="37,0,40,0" />
<scope id="1751004816844298780" at="23,0,27,0">
<var name="outerVars" id="1751004816844298780" />
</scope>
<scope id="1751004816844298780" at="27,26,32,77">
<var name="i" id="1751004816844298780" />
<var name="j" id="1751004816844298780" />
<var name="x" id="1751004816844298781" />
<var name="y" id="1751004816844299683" />
</scope>
<scope id="1751004816844298780" at="27,0,34,0" />
<unit id="1751004816844298780" at="18,0,41,0" name="sandboxModel.biggerTypeTest2$Function_1751004816844298780" />
<unit id="1751004816844298779" at="9,0,42,0" name="sandboxModel.biggerTypeTest2" />
</file>
</root>
<root nodeRef="r:19bf018c-b5e7-418d-8415-b23921421325(sandboxModel)/2167053794906818090">
<file name="sim.java">
<node id="2167053794906818090" at="12,42,13,33" concept="1" />
<node id="2167053794906818090" at="15,31,16,81" concept="5" />
<node id="2167053794906818092" at="19,0,20,0" concept="2" trace="myOuterVars" />
<node id="2167053794906818092" at="20,43,21,34" concept="1" />
<node id="2167053794906818092" at="23,57,24,34" concept="1" />
<node id="2167053794906818092" at="24,34,25,36" concept="1" />
<node id="2167053794906818092" at="27,26,28,16" concept="4" />
<node id="2167053794906818092" at="28,16,29,16" concept="4" />
<node id="2167053794906818093" at="29,16,30,44" concept="4" />
<node id="2167053794906818092" at="30,44,31,19" concept="5" />
<node id="2167053794906818092" at="33,33,34,15" concept="5" />
<node id="2167053794906818092" at="36,28,37,59" concept="5" />
<node id="2167053794906818091" at="40,61,41,95" concept="5" />
<node id="2167053794906818090" at="10,0,12,0" concept="0" trace="sim#()V" />
<node id="2167053794906818090" at="12,0,15,0" concept="6" trace="main#([Ljava/lang/String;)V" />
<node id="2167053794906818090" at="15,0,18,0" concept="6" trace="eval#()Ljava/lang/Object;" />
<node id="2167053794906818092" at="20,0,23,0" concept="0" trace="Function_2167053794906818092#()V" />
<node id="2167053794906818092" at="33,0,36,0" concept="3" trace="getParamsCount#()I" />
<node id="2167053794906818092" at="36,0,39,0" concept="3" trace="copy#()Ljetbrains/mps/samples/lambdaCalculus/runtime/Function;" />
<node id="2167053794906818091" at="40,0,43,0" concept="6" trace="let_2167053794906818091#(Ljetbrains/mps/samples/lambdaCalculus/runtime/Function;)Ljava/lang/Object;" />
<node id="2167053794906818092" at="23,0,27,0" concept="0" trace="Function_2167053794906818092#(Ljava/util/List;)V" />
<node id="2167053794906818092" at="27,0,33,0" concept="3" trace="eval#()Ljava/lang/Object;" />
<scope id="2167053794906818090" at="10,16,10,16" />
<scope id="2167053794906818090" at="12,42,13,33" />
<scope id="2167053794906818090" at="15,31,16,81" />
<scope id="2167053794906818092" at="20,43,21,34" />
<scope id="2167053794906818092" at="33,33,34,15" />
<scope id="2167053794906818092" at="36,28,37,59" />
<scope id="2167053794906818091" at="40,61,41,95" />
<scope id="2167053794906818090" at="10,0,12,0" />
<scope id="2167053794906818092" at="23,57,25,36" />
<scope id="2167053794906818090" at="12,0,15,0">
<var name="args" id="2167053794906818090" />
</scope>
<scope id="2167053794906818090" at="15,0,18,0" />
<scope id="2167053794906818092" at="20,0,23,0" />
<scope id="2167053794906818092" at="33,0,36,0" />
<scope id="2167053794906818092" at="36,0,39,0" />
<scope id="2167053794906818091" at="40,0,43,0">
<var name="sq" id="2167053794906818091" />
</scope>
<scope id="2167053794906818092" at="23,0,27,0">
<var name="outerVars" id="2167053794906818092" />
</scope>
<scope id="2167053794906818092" at="27,26,31,19">
<var name="i" id="2167053794906818092" />
<var name="j" id="2167053794906818092" />
<var name="x" id="2167053794906818093" />
</scope>
<scope id="2167053794906818092" at="27,0,33,0" />
<unit id="2167053794906818092" at="18,0,40,0" name="sandboxModel.sim$Function_2167053794906818092" />
<unit id="2167053794906818090" at="9,0,44,0" name="sandboxModel.sim" />
</file>
</root>
<root nodeRef="r:19bf018c-b5e7-418d-8415-b23921421325(sandboxModel)/5277476162361142416">
<file name="test2.java">
<node id="5277476162361142416" at="9,42,10,33" concept="1" />
<node id="5277476162361142416" at="12,31,13,46" concept="5" />
<node id="5277476162361142445" at="15,68,16,13" concept="5" />
<node id="5277476162361142416" at="7,0,9,0" concept="0" trace="test2#()V" />
<node id="5277476162361142416" at="9,0,12,0" concept="6" trace="main#([Ljava/lang/String;)V" />
<node id="5277476162361142416" at="12,0,15,0" concept="6" trace="eval#()Ljava/lang/Object;" />
<node id="5277476162361142445" at="15,0,18,0" concept="6" trace="lambdaAbstr_5277476162361142418#(Ljava/lang/Integer;)Ljava/lang/Integer;" />
<scope id="5277476162361142416" at="7,18,7,18" />
<scope id="5277476162361142416" at="9,42,10,33" />
<scope id="5277476162361142416" at="12,31,13,46" />
<scope id="5277476162361142445" at="15,68,16,13" />
<scope id="5277476162361142416" at="7,0,9,0" />
<scope id="5277476162361142416" at="9,0,12,0">
<var name="args" id="5277476162361142416" />
</scope>
<scope id="5277476162361142416" at="12,0,15,0" />
<scope id="5277476162361142445" at="15,0,18,0">
<var name="x" id="5277476162361142419" />
</scope>
<unit id="5277476162361142416" at="6,0,19,0" name="sandboxModel.test2" />
</file>
</root>
<root nodeRef="r:19bf018c-b5e7-418d-8415-b23921421325(sandboxModel)/816130369292750457">
<file name="sumsq.java">
<node id="816130369292750457" at="9,42,10,33" concept="1" />
<node id="816130369292750457" at="12,31,13,48" concept="5" />
<node id="816130369292750664" at="15,78,16,57" concept="5" />
<node id="816130369292750468" at="18,82,19,62" concept="5" />
<node id="816130369292750496" at="21,96,22,58" concept="5" />
<node id="816130369292750539" at="24,94,25,28" concept="5" />
<node id="816130369292750457" at="7,0,9,0" concept="0" trace="sumsq#()V" />
<node id="816130369292750457" at="9,0,12,0" concept="6" trace="main#([Ljava/lang/String;)V" />
<node id="816130369292750457" at="12,0,15,0" concept="6" trace="eval#()Ljava/lang/Object;" />
<node id="816130369292750664" at="15,0,18,0" concept="6" trace="lambdaAbstr_816130369292750642#(Ljava/lang/Integer;Ljava/lang/Integer;)Ljava/lang/Integer;" />
<node id="816130369292750468" at="18,0,21,0" concept="6" trace="let_816130369292750468#(Ljava/lang/Integer;Ljava/lang/Integer;Ljava/lang/Integer;)Ljava/lang/Object;" />
<node id="816130369292750496" at="21,0,24,0" concept="6" trace="let_816130369292750496#(Ljava/lang/Integer;Ljava/lang/Integer;Ljava/lang/Integer;Ljava/lang/Integer;)Ljava/lang/Object;" />
<node id="816130369292750539" at="24,0,27,0" concept="6" trace="lambdaAbstr_816130369292750515#(Ljava/lang/Integer;Ljava/lang/Integer;Ljava/lang/Integer;)Ljava/lang/Integer;" />
<scope id="816130369292750457" at="7,18,7,18" />
<scope id="816130369292750457" at="9,42,10,33" />
<scope id="816130369292750457" at="12,31,13,48" />
<scope id="816130369292750664" at="15,78,16,57" />
<scope id="816130369292750468" at="18,82,19,62" />
<scope id="816130369292750496" at="21,96,22,58" />
<scope id="816130369292750539" at="24,94,25,28" />
<scope id="816130369292750457" at="7,0,9,0" />
<scope id="816130369292750457" at="9,0,12,0">
<var name="args" id="816130369292750457" />
</scope>
<scope id="816130369292750457" at="12,0,15,0" />
<scope id="816130369292750664" at="15,0,18,0">
<var name="x" id="816130369292750460" />
<var name="y" id="816130369292750464" />
</scope>
<scope id="816130369292750468" at="18,0,21,0">
<var name="sum" id="816130369292750468" />
<var name="x" id="816130369292750460" />
<var name="y" id="816130369292750464" />
</scope>
<scope id="816130369292750496" at="21,0,24,0">
<var name="mult" id="816130369292750496" />
<var name="sum" id="816130369292750478" />
<var name="x" id="816130369292750460" />
<var name="y" id="816130369292750464" />
</scope>
<scope id="816130369292750539" at="24,0,27,0">
<var name="mult" id="816130369292750499" />
<var name="sum" id="816130369292750478" />
<var name="z" id="816130369292750516" />
</scope>
<unit id="816130369292750457" at="6,0,28,0" name="sandboxModel.sumsq" />
</file>
</root>
<root nodeRef="r:19bf018c-b5e7-418d-8415-b23921421325(sandboxModel)/816130369292806252">
<file name="letlet.java">
<node id="816130369292806252" at="9,42,10,33" concept="1" />
<node id="816130369292806252" at="12,31,13,47" concept="5" />
<node id="816130369292806253" at="15,59,16,51" concept="5" />
<node id="816130369292806255" at="18,71,19,19" concept="5" />
<node id="816130369292806252" at="7,0,9,0" concept="0" trace="letlet#()V" />
<node id="816130369292806252" at="9,0,12,0" concept="6" trace="main#([Ljava/lang/String;)V" />
<node id="816130369292806252" at="12,0,15,0" concept="6" trace="eval#()Ljava/lang/Object;" />
<node id="816130369292806253" at="15,0,18,0" concept="6" trace="let_816130369292806253#(Ljava/lang/Integer;)Ljava/lang/Object;" />
<node id="816130369292806255" at="18,0,21,0" concept="6" trace="let_816130369292806255#(Ljava/lang/Integer;Ljava/lang/Integer;)Ljava/lang/Object;" />
<scope id="816130369292806252" at="7,19,7,19" />
<scope id="816130369292806252" at="9,42,10,33" />
<scope id="816130369292806252" at="12,31,13,47" />
<scope id="816130369292806253" at="15,59,16,51" />
<scope id="816130369292806255" at="18,71,19,19" />
<scope id="816130369292806252" at="7,0,9,0" />
<scope id="816130369292806252" at="9,0,12,0">
<var name="args" id="816130369292806252" />
</scope>
<scope id="816130369292806252" at="12,0,15,0" />
<scope id="816130369292806253" at="15,0,18,0">
<var name="q1" id="816130369292806253" />
</scope>
<scope id="816130369292806255" at="18,0,21,0">
<var name="q1" id="816130369292806261" />
<var name="q2" id="816130369292806255" />
</scope>
<unit id="816130369292806252" at="6,0,22,0" name="sandboxModel.letlet" />
</file>
</root>
</debug-info>
| {'repo_name': 'JetBrains/MPS', 'stars': '1070', 'repo_language': 'Java', 'file_name': 'LanguageAspectsEP_extension.java', 'mime_type': 'text/x-java', 'hash': -2157467870124693778, 'source_dataset': 'data'} |
package water
// PlatformSpecificParams defines parameters in Config that are specific to
// Windows. A zero-value of such type is valid.
type PlatformSpecificParams struct {
// ComponentID associates with the virtual adapter that exists in Windows.
// This is usually configured when driver for the adapter is installed. A
// zero-value of this field, i.e., an empty string, causes the interface to
// use the default ComponentId. The default ComponentId is set to tap0901,
// the one used by OpenVPN.
ComponentID string
// InterfaceName is a friendly name of the network adapter as set in Control Panel.
// Of course, you may have multiple tap0901 adapters on the system, in which
// case we need a friendlier way to identify them.
InterfaceName string
// Network is required when creating a TUN interface. The library will call
// net.ParseCIDR() to parse this string into LocalIP, RemoteNetaddr,
// RemoteNetmask. The underlying driver will need those to generate ARP
// response to Windows kernel, to emulate an TUN interface.
// Please note that it cannot perceive the IP changes caused by DHCP, user
// configuration to the adapter and etc,. If IP changed, please reconfigure
// the adapter using syscall, just like openDev().
// For detail, please refer
// https://github.com/OpenVPN/tap-windows6/blob/master/src/device.c#L431
// and https://github.com/songgao/water/pull/13#issuecomment-270341777
Network string
}
func defaultPlatformSpecificParams() PlatformSpecificParams {
return PlatformSpecificParams{
ComponentID: "tap0901",
Network: "192.168.1.10/24",
}
}
| {'repo_name': 'OpenIoTHub/gateway-go', 'stars': '118', 'repo_language': 'Go', 'file_name': 'gateway-go.service', 'mime_type': 'text/plain', 'hash': 164518666387019407, 'source_dataset': 'data'} |
/*
*
* Hardware accelerated Matrox Millennium I, II, Mystique, G100, G200, G400 and G450
*
* (c) 1998-2002 Petr Vandrovec <[email protected]>
*
*/
#ifndef __MATROXFB_H__
#define __MATROXFB_H__
/* general, but fairly heavy, debugging */
#undef MATROXFB_DEBUG
/* heavy debugging: */
/* -- logs putc[s], so every time a char is displayed, it's logged */
#undef MATROXFB_DEBUG_HEAVY
/* This one _could_ cause infinite loops */
/* It _does_ cause lots and lots of messages during idle loops */
#undef MATROXFB_DEBUG_LOOP
/* Debug register calls, too? */
#undef MATROXFB_DEBUG_REG
/* Guard accelerator accesses with spin_lock_irqsave... */
#undef MATROXFB_USE_SPINLOCKS
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/mm.h>
#include <linux/slab.h>
#include <linux/delay.h>
#include <linux/fb.h>
#include <linux/console.h>
#include <linux/selection.h>
#include <linux/ioport.h>
#include <linux/init.h>
#include <linux/timer.h>
#include <linux/pci.h>
#include <linux/spinlock.h>
#include <linux/kd.h>
#include <asm/io.h>
#include <asm/unaligned.h>
#ifdef CONFIG_MTRR
#include <asm/mtrr.h>
#endif
#if defined(CONFIG_PPC_PMAC)
#include <asm/prom.h>
#include <asm/pci-bridge.h>
#include "../macmodes.h"
#endif
#ifdef MATROXFB_DEBUG
#define DEBUG
#define DBG(x) printk(KERN_DEBUG "matroxfb: %s\n", (x));
#ifdef MATROXFB_DEBUG_HEAVY
#define DBG_HEAVY(x) DBG(x)
#else /* MATROXFB_DEBUG_HEAVY */
#define DBG_HEAVY(x) /* DBG_HEAVY */
#endif /* MATROXFB_DEBUG_HEAVY */
#ifdef MATROXFB_DEBUG_LOOP
#define DBG_LOOP(x) DBG(x)
#else /* MATROXFB_DEBUG_LOOP */
#define DBG_LOOP(x) /* DBG_LOOP */
#endif /* MATROXFB_DEBUG_LOOP */
#ifdef MATROXFB_DEBUG_REG
#define DBG_REG(x) DBG(x)
#else /* MATROXFB_DEBUG_REG */
#define DBG_REG(x) /* DBG_REG */
#endif /* MATROXFB_DEBUG_REG */
#else /* MATROXFB_DEBUG */
#define DBG(x) /* DBG */
#define DBG_HEAVY(x) /* DBG_HEAVY */
#define DBG_REG(x) /* DBG_REG */
#define DBG_LOOP(x) /* DBG_LOOP */
#endif /* MATROXFB_DEBUG */
#ifdef DEBUG
#define dprintk(X...) printk(X)
#else
#define dprintk(X...)
#endif
#ifndef PCI_SS_VENDOR_ID_SIEMENS_NIXDORF
#define PCI_SS_VENDOR_ID_SIEMENS_NIXDORF 0x110A
#endif
#ifndef PCI_SS_VENDOR_ID_MATROX
#define PCI_SS_VENDOR_ID_MATROX PCI_VENDOR_ID_MATROX
#endif
#ifndef PCI_SS_ID_MATROX_PRODUCTIVA_G100_AGP
#define PCI_SS_ID_MATROX_GENERIC 0xFF00
#define PCI_SS_ID_MATROX_PRODUCTIVA_G100_AGP 0xFF01
#define PCI_SS_ID_MATROX_MYSTIQUE_G200_AGP 0xFF02
#define PCI_SS_ID_MATROX_MILLENIUM_G200_AGP 0xFF03
#define PCI_SS_ID_MATROX_MARVEL_G200_AGP 0xFF04
#define PCI_SS_ID_MATROX_MGA_G100_PCI 0xFF05
#define PCI_SS_ID_MATROX_MGA_G100_AGP 0x1001
#define PCI_SS_ID_MATROX_MILLENNIUM_G400_MAX_AGP 0x2179
#define PCI_SS_ID_SIEMENS_MGA_G100_AGP 0x001E /* 30 */
#define PCI_SS_ID_SIEMENS_MGA_G200_AGP 0x0032 /* 50 */
#endif
#define MX_VISUAL_TRUECOLOR FB_VISUAL_DIRECTCOLOR
#define MX_VISUAL_DIRECTCOLOR FB_VISUAL_TRUECOLOR
#define MX_VISUAL_PSEUDOCOLOR FB_VISUAL_PSEUDOCOLOR
#define CNVT_TOHW(val,width) ((((val)<<(width))+0x7FFF-(val))>>16)
/* G-series and Mystique have (almost) same DAC */
#undef NEED_DAC1064
#if defined(CONFIG_FB_MATROX_MYSTIQUE) || defined(CONFIG_FB_MATROX_G)
#define NEED_DAC1064 1
#endif
typedef struct {
void __iomem* vaddr;
} vaddr_t;
static inline unsigned int mga_readb(vaddr_t va, unsigned int offs) {
return readb(va.vaddr + offs);
}
static inline void mga_writeb(vaddr_t va, unsigned int offs, u_int8_t value) {
writeb(value, va.vaddr + offs);
}
static inline void mga_writew(vaddr_t va, unsigned int offs, u_int16_t value) {
writew(value, va.vaddr + offs);
}
static inline u_int32_t mga_readl(vaddr_t va, unsigned int offs) {
return readl(va.vaddr + offs);
}
static inline void mga_writel(vaddr_t va, unsigned int offs, u_int32_t value) {
writel(value, va.vaddr + offs);
}
static inline void mga_memcpy_toio(vaddr_t va, const void* src, int len) {
#if defined(__alpha__) || defined(__i386__) || defined(__x86_64__)
/*
* iowrite32_rep works for us if:
* (1) Copies data as 32bit quantities, not byte after byte,
* (2) Performs LE ordered stores, and
* (3) It copes with unaligned source (destination is guaranteed to be page
* aligned and length is guaranteed to be multiple of 4).
*/
iowrite32_rep(va.vaddr, src, len >> 2);
#else
u_int32_t __iomem* addr = va.vaddr;
if ((unsigned long)src & 3) {
while (len >= 4) {
fb_writel(get_unaligned((u32 *)src), addr);
addr++;
len -= 4;
src += 4;
}
} else {
while (len >= 4) {
fb_writel(*(u32 *)src, addr);
addr++;
len -= 4;
src += 4;
}
}
#endif
}
static inline void vaddr_add(vaddr_t* va, unsigned long offs) {
va->vaddr += offs;
}
static inline void __iomem* vaddr_va(vaddr_t va) {
return va.vaddr;
}
#define MGA_IOREMAP_NORMAL 0
#define MGA_IOREMAP_NOCACHE 1
#define MGA_IOREMAP_FB MGA_IOREMAP_NOCACHE
#define MGA_IOREMAP_MMIO MGA_IOREMAP_NOCACHE
static inline int mga_ioremap(unsigned long phys, unsigned long size, int flags, vaddr_t* virt) {
if (flags & MGA_IOREMAP_NOCACHE)
virt->vaddr = ioremap_nocache(phys, size);
else
virt->vaddr = ioremap(phys, size);
return (virt->vaddr == NULL); /* 0, !0... 0, error_code in future */
}
static inline void mga_iounmap(vaddr_t va) {
iounmap(va.vaddr);
}
struct my_timming {
unsigned int pixclock;
int mnp;
unsigned int crtc;
unsigned int HDisplay;
unsigned int HSyncStart;
unsigned int HSyncEnd;
unsigned int HTotal;
unsigned int VDisplay;
unsigned int VSyncStart;
unsigned int VSyncEnd;
unsigned int VTotal;
unsigned int sync;
int dblscan;
int interlaced;
unsigned int delay; /* CRTC delay */
};
enum { M_SYSTEM_PLL, M_PIXEL_PLL_A, M_PIXEL_PLL_B, M_PIXEL_PLL_C, M_VIDEO_PLL };
struct matrox_pll_cache {
unsigned int valid;
struct {
unsigned int mnp_key;
unsigned int mnp_value;
} data[4];
};
struct matrox_pll_limits {
unsigned int vcomin;
unsigned int vcomax;
};
struct matrox_pll_features {
unsigned int vco_freq_min;
unsigned int ref_freq;
unsigned int feed_div_min;
unsigned int feed_div_max;
unsigned int in_div_min;
unsigned int in_div_max;
unsigned int post_shift_max;
};
struct matroxfb_par
{
unsigned int final_bppShift;
unsigned int cmap_len;
struct {
unsigned int bytes;
unsigned int pixels;
unsigned int chunks;
} ydstorg;
};
struct matrox_fb_info;
struct matrox_DAC1064_features {
u_int8_t xvrefctrl;
u_int8_t xmiscctrl;
};
/* current hardware status */
struct mavenregs {
u_int8_t regs[256];
int mode;
int vlines;
int xtal;
int fv;
u_int16_t htotal;
u_int16_t hcorr;
};
struct matrox_crtc2 {
u_int32_t ctl;
};
struct matrox_hw_state {
u_int32_t MXoptionReg;
unsigned char DACclk[6];
unsigned char DACreg[80];
unsigned char MiscOutReg;
unsigned char DACpal[768];
unsigned char CRTC[25];
unsigned char CRTCEXT[9];
unsigned char SEQ[5];
/* unused for MGA mode, but who knows... */
unsigned char GCTL[9];
/* unused for MGA mode, but who knows... */
unsigned char ATTR[21];
/* TVOut only */
struct mavenregs maven;
struct matrox_crtc2 crtc2;
};
struct matrox_accel_data {
#ifdef CONFIG_FB_MATROX_MILLENIUM
unsigned char ramdac_rev;
#endif
u_int32_t m_dwg_rect;
u_int32_t m_opmode;
};
struct v4l2_queryctrl;
struct v4l2_control;
struct matrox_altout {
const char *name;
int (*compute)(void* altout_dev, struct my_timming* input);
int (*program)(void* altout_dev);
int (*start)(void* altout_dev);
int (*verifymode)(void* altout_dev, u_int32_t mode);
int (*getqueryctrl)(void* altout_dev,
struct v4l2_queryctrl* ctrl);
int (*getctrl)(void* altout_dev,
struct v4l2_control* ctrl);
int (*setctrl)(void* altout_dev,
struct v4l2_control* ctrl);
};
#define MATROXFB_SRC_NONE 0
#define MATROXFB_SRC_CRTC1 1
#define MATROXFB_SRC_CRTC2 2
enum mga_chip { MGA_2064, MGA_2164, MGA_1064, MGA_1164, MGA_G100, MGA_G200, MGA_G400, MGA_G450, MGA_G550 };
struct matrox_bios {
unsigned int bios_valid : 1;
unsigned int pins_len;
unsigned char pins[128];
struct {
unsigned char vMaj, vMin, vRev;
} version;
struct {
unsigned char state, tvout;
} output;
};
struct matrox_switch;
struct matroxfb_driver;
struct matroxfb_dh_fb_info;
struct matrox_vsync {
wait_queue_head_t wait;
unsigned int cnt;
};
struct matrox_fb_info {
struct fb_info fbcon;
struct list_head next_fb;
int dead;
int initialized;
unsigned int usecount;
unsigned int userusecount;
unsigned long irq_flags;
struct matroxfb_par curr;
struct matrox_hw_state hw;
struct matrox_accel_data accel;
struct pci_dev* pcidev;
struct {
struct matrox_vsync vsync;
unsigned int pixclock;
int mnp;
int panpos;
} crtc1;
struct {
struct matrox_vsync vsync;
unsigned int pixclock;
int mnp;
struct matroxfb_dh_fb_info* info;
struct rw_semaphore lock;
} crtc2;
struct {
struct rw_semaphore lock;
struct {
int brightness, contrast, saturation, hue, gamma;
int testout, deflicker;
} tvo_params;
} altout;
#define MATROXFB_MAX_OUTPUTS 3
struct {
unsigned int src;
struct matrox_altout* output;
void* data;
unsigned int mode;
unsigned int default_src;
} outputs[MATROXFB_MAX_OUTPUTS];
#define MATROXFB_MAX_FB_DRIVERS 5
struct matroxfb_driver* (drivers[MATROXFB_MAX_FB_DRIVERS]);
void* (drivers_data[MATROXFB_MAX_FB_DRIVERS]);
unsigned int drivers_count;
struct {
unsigned long base; /* physical */
vaddr_t vbase; /* CPU view */
unsigned int len;
unsigned int len_usable;
unsigned int len_maximum;
} video;
struct {
unsigned long base; /* physical */
vaddr_t vbase; /* CPU view */
unsigned int len;
} mmio;
unsigned int max_pixel_clock;
unsigned int max_pixel_clock_panellink;
struct matrox_switch* hw_switch;
struct {
struct matrox_pll_features pll;
struct matrox_DAC1064_features DAC1064;
} features;
struct {
spinlock_t DAC;
spinlock_t accel;
} lock;
enum mga_chip chip;
int interleave;
int millenium;
int milleniumII;
struct {
int cfb4;
const int* vxres;
int cross4MB;
int text;
int plnwt;
int srcorg;
} capable;
#ifdef CONFIG_MTRR
struct {
int vram;
int vram_valid;
} mtrr;
#endif
struct {
int precise_width;
int mga_24bpp_fix;
int novga;
int nobios;
int nopciretry;
int noinit;
int sgram;
int support32MB;
int accelerator;
int text_type_aux;
int video64bits;
int crtc2;
int maven_capable;
unsigned int vgastep;
unsigned int textmode;
unsigned int textstep;
unsigned int textvram; /* character cells */
unsigned int ydstorg; /* offset in bytes from video start to usable memory */
/* 0 except for 6MB Millenium */
int memtype;
int g450dac;
int dfp_type;
int panellink; /* G400 DFP possible (not G450/G550) */
int dualhead;
unsigned int fbResource;
} devflags;
struct fb_ops fbops;
struct matrox_bios bios;
struct {
struct matrox_pll_limits pixel;
struct matrox_pll_limits system;
struct matrox_pll_limits video;
} limits;
struct {
struct matrox_pll_cache pixel;
struct matrox_pll_cache system;
struct matrox_pll_cache video;
} cache;
struct {
struct {
unsigned int video;
unsigned int system;
} pll;
struct {
u_int32_t opt;
u_int32_t opt2;
u_int32_t opt3;
u_int32_t mctlwtst;
u_int32_t mctlwtst_core;
u_int32_t memmisc;
u_int32_t memrdbk;
u_int32_t maccess;
} reg;
struct {
unsigned int ddr:1,
emrswen:1,
dll:1;
} memory;
} values;
u_int32_t cmap[16];
};
#define info2minfo(info) container_of(info, struct matrox_fb_info, fbcon)
struct matrox_switch {
int (*preinit)(struct matrox_fb_info *minfo);
void (*reset)(struct matrox_fb_info *minfo);
int (*init)(struct matrox_fb_info *minfo, struct my_timming*);
void (*restore)(struct matrox_fb_info *minfo);
};
struct matroxfb_driver {
struct list_head node;
char* name;
void* (*probe)(struct matrox_fb_info* info);
void (*remove)(struct matrox_fb_info* info, void* data);
};
int matroxfb_register_driver(struct matroxfb_driver* drv);
void matroxfb_unregister_driver(struct matroxfb_driver* drv);
#define PCI_OPTION_REG 0x40
#define PCI_OPTION_ENABLE_ROM 0x40000000
#define PCI_MGA_INDEX 0x44
#define PCI_MGA_DATA 0x48
#define PCI_OPTION2_REG 0x50
#define PCI_OPTION3_REG 0x54
#define PCI_MEMMISC_REG 0x58
#define M_DWGCTL 0x1C00
#define M_MACCESS 0x1C04
#define M_CTLWTST 0x1C08
#define M_PLNWT 0x1C1C
#define M_BCOL 0x1C20
#define M_FCOL 0x1C24
#define M_SGN 0x1C58
#define M_LEN 0x1C5C
#define M_AR0 0x1C60
#define M_AR1 0x1C64
#define M_AR2 0x1C68
#define M_AR3 0x1C6C
#define M_AR4 0x1C70
#define M_AR5 0x1C74
#define M_AR6 0x1C78
#define M_CXBNDRY 0x1C80
#define M_FXBNDRY 0x1C84
#define M_YDSTLEN 0x1C88
#define M_PITCH 0x1C8C
#define M_YDST 0x1C90
#define M_YDSTORG 0x1C94
#define M_YTOP 0x1C98
#define M_YBOT 0x1C9C
/* mystique only */
#define M_CACHEFLUSH 0x1FFF
#define M_EXEC 0x0100
#define M_DWG_TRAP 0x04
#define M_DWG_BITBLT 0x08
#define M_DWG_ILOAD 0x09
#define M_DWG_LINEAR 0x0080
#define M_DWG_SOLID 0x0800
#define M_DWG_ARZERO 0x1000
#define M_DWG_SGNZERO 0x2000
#define M_DWG_SHIFTZERO 0x4000
#define M_DWG_REPLACE 0x000C0000
#define M_DWG_REPLACE2 (M_DWG_REPLACE | 0x40)
#define M_DWG_XOR 0x00060010
#define M_DWG_BFCOL 0x04000000
#define M_DWG_BMONOWF 0x08000000
#define M_DWG_TRANSC 0x40000000
#define M_FIFOSTATUS 0x1E10
#define M_STATUS 0x1E14
#define M_ICLEAR 0x1E18
#define M_IEN 0x1E1C
#define M_VCOUNT 0x1E20
#define M_RESET 0x1E40
#define M_MEMRDBK 0x1E44
#define M_AGP2PLL 0x1E4C
#define M_OPMODE 0x1E54
#define M_OPMODE_DMA_GEN_WRITE 0x00
#define M_OPMODE_DMA_BLIT 0x04
#define M_OPMODE_DMA_VECTOR_WRITE 0x08
#define M_OPMODE_DMA_LE 0x0000 /* little endian - no transformation */
#define M_OPMODE_DMA_BE_8BPP 0x0000
#define M_OPMODE_DMA_BE_16BPP 0x0100
#define M_OPMODE_DMA_BE_32BPP 0x0200
#define M_OPMODE_DIR_LE 0x000000 /* little endian - no transformation */
#define M_OPMODE_DIR_BE_8BPP 0x000000
#define M_OPMODE_DIR_BE_16BPP 0x010000
#define M_OPMODE_DIR_BE_32BPP 0x020000
#define M_ATTR_INDEX 0x1FC0
#define M_ATTR_DATA 0x1FC1
#define M_MISC_REG 0x1FC2
#define M_3C2_RD 0x1FC2
#define M_SEQ_INDEX 0x1FC4
#define M_SEQ_DATA 0x1FC5
#define M_SEQ1 0x01
#define M_SEQ1_SCROFF 0x20
#define M_MISC_REG_READ 0x1FCC
#define M_GRAPHICS_INDEX 0x1FCE
#define M_GRAPHICS_DATA 0x1FCF
#define M_CRTC_INDEX 0x1FD4
#define M_ATTR_RESET 0x1FDA
#define M_3DA_WR 0x1FDA
#define M_INSTS1 0x1FDA
#define M_EXTVGA_INDEX 0x1FDE
#define M_EXTVGA_DATA 0x1FDF
/* G200 only */
#define M_SRCORG 0x2CB4
#define M_DSTORG 0x2CB8
#define M_RAMDAC_BASE 0x3C00
/* fortunately, same on TVP3026 and MGA1064 */
#define M_DAC_REG (M_RAMDAC_BASE+0)
#define M_DAC_VAL (M_RAMDAC_BASE+1)
#define M_PALETTE_MASK (M_RAMDAC_BASE+2)
#define M_X_INDEX 0x00
#define M_X_DATAREG 0x0A
#define DAC_XGENIOCTRL 0x2A
#define DAC_XGENIODATA 0x2B
#define M_C2CTL 0x3C10
#define MX_OPTION_BSWAP 0x00000000
#ifdef __LITTLE_ENDIAN
#define M_OPMODE_4BPP (M_OPMODE_DMA_LE | M_OPMODE_DIR_LE | M_OPMODE_DMA_BLIT)
#define M_OPMODE_8BPP (M_OPMODE_DMA_LE | M_OPMODE_DIR_LE | M_OPMODE_DMA_BLIT)
#define M_OPMODE_16BPP (M_OPMODE_DMA_LE | M_OPMODE_DIR_LE | M_OPMODE_DMA_BLIT)
#define M_OPMODE_24BPP (M_OPMODE_DMA_LE | M_OPMODE_DIR_LE | M_OPMODE_DMA_BLIT)
#define M_OPMODE_32BPP (M_OPMODE_DMA_LE | M_OPMODE_DIR_LE | M_OPMODE_DMA_BLIT)
#else
#ifdef __BIG_ENDIAN
#define M_OPMODE_4BPP (M_OPMODE_DMA_LE | M_OPMODE_DIR_LE | M_OPMODE_DMA_BLIT) /* TODO */
#define M_OPMODE_8BPP (M_OPMODE_DMA_LE | M_OPMODE_DIR_BE_8BPP | M_OPMODE_DMA_BLIT)
#define M_OPMODE_16BPP (M_OPMODE_DMA_LE | M_OPMODE_DIR_BE_16BPP | M_OPMODE_DMA_BLIT)
#define M_OPMODE_24BPP (M_OPMODE_DMA_LE | M_OPMODE_DIR_BE_8BPP | M_OPMODE_DMA_BLIT) /* TODO, ?32 */
#define M_OPMODE_32BPP (M_OPMODE_DMA_LE | M_OPMODE_DIR_BE_32BPP | M_OPMODE_DMA_BLIT)
#else
#error "Byte ordering have to be defined. Cannot continue."
#endif
#endif
#define mga_inb(addr) mga_readb(minfo->mmio.vbase, (addr))
#define mga_inl(addr) mga_readl(minfo->mmio.vbase, (addr))
#define mga_outb(addr,val) mga_writeb(minfo->mmio.vbase, (addr), (val))
#define mga_outw(addr,val) mga_writew(minfo->mmio.vbase, (addr), (val))
#define mga_outl(addr,val) mga_writel(minfo->mmio.vbase, (addr), (val))
#define mga_readr(port,idx) (mga_outb((port),(idx)), mga_inb((port)+1))
#define mga_setr(addr,port,val) mga_outw(addr, ((val)<<8) | (port))
#define mga_fifo(n) do {} while ((mga_inl(M_FIFOSTATUS) & 0xFF) < (n))
#define WaitTillIdle() do {} while (mga_inl(M_STATUS) & 0x10000)
/* code speedup */
#ifdef CONFIG_FB_MATROX_MILLENIUM
#define isInterleave(x) (x->interleave)
#define isMillenium(x) (x->millenium)
#define isMilleniumII(x) (x->milleniumII)
#else
#define isInterleave(x) (0)
#define isMillenium(x) (0)
#define isMilleniumII(x) (0)
#endif
#define matroxfb_DAC_lock() spin_lock(&minfo->lock.DAC)
#define matroxfb_DAC_unlock() spin_unlock(&minfo->lock.DAC)
#define matroxfb_DAC_lock_irqsave(flags) spin_lock_irqsave(&minfo->lock.DAC, flags)
#define matroxfb_DAC_unlock_irqrestore(flags) spin_unlock_irqrestore(&minfo->lock.DAC, flags)
extern void matroxfb_DAC_out(const struct matrox_fb_info *minfo, int reg,
int val);
extern int matroxfb_DAC_in(const struct matrox_fb_info *minfo, int reg);
extern void matroxfb_var2my(struct fb_var_screeninfo* fvsi, struct my_timming* mt);
extern int matroxfb_wait_for_sync(struct matrox_fb_info *minfo, u_int32_t crtc);
extern int matroxfb_enable_irq(struct matrox_fb_info *minfo, int reenable);
#ifdef MATROXFB_USE_SPINLOCKS
#define CRITBEGIN spin_lock_irqsave(&minfo->lock.accel, critflags);
#define CRITEND spin_unlock_irqrestore(&minfo->lock.accel, critflags);
#define CRITFLAGS unsigned long critflags;
#else
#define CRITBEGIN
#define CRITEND
#define CRITFLAGS
#endif
#endif /* __MATROXFB_H__ */
| {'repo_name': 'franciscofranco/hammerhead', 'stars': '122', 'repo_language': 'C', 'file_name': 'impa7.c', 'mime_type': 'text/x-c', 'hash': 9034542611466636032, 'source_dataset': 'data'} |
package ExtUtils::MM_Unix;
require 5.006;
use strict;
use Carp;
use ExtUtils::MakeMaker::Config;
use File::Basename qw(basename dirname);
our %Config_Override;
use ExtUtils::MakeMaker qw($Verbose neatvalue _sprintf562);
# If we make $VERSION an our variable parse_version() breaks
use vars qw($VERSION);
$VERSION = '8.35_08';
$VERSION =~ tr/_//d;
require ExtUtils::MM_Any;
our @ISA = qw(ExtUtils::MM_Any);
my %Is;
BEGIN {
$Is{OS2} = $^O eq 'os2';
$Is{Win32} = $^O eq 'MSWin32' || $Config{osname} eq 'NetWare';
$Is{Dos} = $^O eq 'dos';
$Is{VMS} = $^O eq 'VMS';
$Is{OSF} = $^O eq 'dec_osf';
$Is{IRIX} = $^O eq 'irix';
$Is{NetBSD} = $^O eq 'netbsd';
$Is{Interix} = $^O eq 'interix';
$Is{SunOS4} = $^O eq 'sunos';
$Is{Solaris} = $^O eq 'solaris';
$Is{SunOS} = $Is{SunOS4} || $Is{Solaris};
$Is{BSD} = ($^O =~ /^(?:free|net|open)bsd$/ or
grep( $^O eq $_, qw(bsdos interix dragonfly) )
);
$Is{Android} = $^O =~ /android/;
$Is{Darwin} = $^O eq 'darwin';
}
BEGIN {
if( $Is{VMS} ) {
# For things like vmsify()
require VMS::Filespec;
VMS::Filespec->import;
}
}
=head1 NAME
ExtUtils::MM_Unix - methods used by ExtUtils::MakeMaker
=head1 SYNOPSIS
require ExtUtils::MM_Unix;
=head1 DESCRIPTION
The methods provided by this package are designed to be used in
conjunction with ExtUtils::MakeMaker. When MakeMaker writes a
Makefile, it creates one or more objects that inherit their methods
from a package C<MM>. MM itself doesn't provide any methods, but it
ISA ExtUtils::MM_Unix class. The inheritance tree of MM lets operating
specific packages take the responsibility for all the methods provided
by MM_Unix. We are trying to reduce the number of the necessary
overrides by defining rather primitive operations within
ExtUtils::MM_Unix.
If you are going to write a platform specific MM package, please try
to limit the necessary overrides to primitive methods, and if it is not
possible to do so, let's work out how to achieve that gain.
If you are overriding any of these methods in your Makefile.PL (in the
MY class), please report that to the makemaker mailing list. We are
trying to minimize the necessary method overrides and switch to data
driven Makefile.PLs wherever possible. In the long run less methods
will be overridable via the MY class.
=head1 METHODS
The following description of methods is still under
development. Please refer to the code for not suitably documented
sections and complain loudly to the [email protected] mailing list.
Better yet, provide a patch.
Not all of the methods below are overridable in a
Makefile.PL. Overridable methods are marked as (o). All methods are
overridable by a platform specific MM_*.pm file.
Cross-platform methods are being moved into MM_Any. If you can't find
something that used to be in here, look in MM_Any.
=cut
# So we don't have to keep calling the methods over and over again,
# we have these globals to cache the values. Faster and shrtr.
my $Curdir = __PACKAGE__->curdir;
my $Updir = __PACKAGE__->updir;
=head2 Methods
=over 4
=item os_flavor
Simply says that we're Unix.
=cut
sub os_flavor {
return('Unix');
}
=item c_o (o)
Defines the suffix rules to compile different flavors of C files to
object files.
=cut
sub c_o {
# --- Translation Sections ---
my($self) = shift;
return '' unless $self->needs_linking();
my(@m);
my $command = '$(CCCMD)';
my $flags = '$(CCCDLFLAGS) "-I$(PERL_INC)" $(PASTHRU_DEFINE) $(DEFINE)';
if (my $cpp = $Config{cpprun}) {
my $cpp_cmd = $self->const_cccmd;
$cpp_cmd =~ s/^CCCMD\s*=\s*\$\(CC\)/$cpp/;
push @m, qq{
.c.i:
$cpp_cmd $flags \$*.c > \$*.i
};
}
my $m_o = $self->{XSMULTI} ? $self->xs_obj_opt('$*.s') : '';
push @m, sprintf <<'EOF', $command, $flags, $m_o;
.c.s :
%s -S %s $*.c %s
EOF
my @exts = qw(c cpp cxx cc);
push @exts, 'C' if !$Is{OS2} and !$Is{Win32} and !$Is{Dos}; #Case-specific
$m_o = $self->{XSMULTI} ? $self->xs_obj_opt('$*$(OBJ_EXT)') : '';
my $dbgout = $self->dbgoutflag;
for my $ext (@exts) {
push @m, "\n.$ext\$(OBJ_EXT) :\n\t$command $flags "
.($dbgout?"$dbgout ":'')
."\$*.$ext" . ( $m_o ? " $m_o" : '' ) . "\n";
}
return join "", @m;
}
=item xs_obj_opt
Takes the object file as an argument, and returns the portion of compile
command-line that will output to the specified object file.
=cut
sub xs_obj_opt {
my ($self, $output_file) = @_;
"-o $output_file";
}
=item dbgoutflag
Returns a CC flag that tells the CC to emit a separate debugging symbol file
when compiling an object file.
=cut
sub dbgoutflag {
'';
}
=item cflags (o)
Does very much the same as the cflags script in the perl
distribution. It doesn't return the whole compiler command line, but
initializes all of its parts. The const_cccmd method then actually
returns the definition of the CCCMD macro which uses these parts.
=cut
#'
sub cflags {
my($self,$libperl)=@_;
return $self->{CFLAGS} if $self->{CFLAGS};
return '' unless $self->needs_linking();
my($prog, $uc, $perltype, %cflags);
$libperl ||= $self->{LIBPERL_A} || "libperl$self->{LIB_EXT}" ;
$libperl =~ s/\.\$\(A\)$/$self->{LIB_EXT}/;
@cflags{qw(cc ccflags optimize shellflags)}
= @Config{qw(cc ccflags optimize shellflags)};
# Perl 5.21.4 adds the (gcc) warning (-Wall ...) and std (-std=c89)
# flags to the %Config, and the modules in the core should be built
# with the warning flags, but NOT the -std=c89 flags (the latter
# would break using any system header files that are strict C99).
my @ccextraflags = qw(ccwarnflags);
if ($ENV{PERL_CORE}) {
for my $x (@ccextraflags) {
if (exists $Config{$x}) {
$cflags{$x} = $Config{$x};
}
}
}
my($optdebug) = "";
$cflags{shellflags} ||= '';
my(%map) = (
D => '-DDEBUGGING',
E => '-DEMBED',
DE => '-DDEBUGGING -DEMBED',
M => '-DEMBED -DMULTIPLICITY',
DM => '-DDEBUGGING -DEMBED -DMULTIPLICITY',
);
if ($libperl =~ /libperl(\w*)\Q$self->{LIB_EXT}/){
$uc = uc($1);
} else {
$uc = ""; # avoid warning
}
$perltype = $map{$uc} ? $map{$uc} : "";
if ($uc =~ /^D/) {
$optdebug = "-g";
}
my($name);
( $name = $self->{NAME} . "_cflags" ) =~ s/:/_/g ;
if ($prog = $Config{$name}) {
# Expand hints for this extension via the shell
print "Processing $name hint:\n" if $Verbose;
my(@o)=`cc=\"$cflags{cc}\"
ccflags=\"$cflags{ccflags}\"
optimize=\"$cflags{optimize}\"
perltype=\"$cflags{perltype}\"
optdebug=\"$cflags{optdebug}\"
eval '$prog'
echo cc=\$cc
echo ccflags=\$ccflags
echo optimize=\$optimize
echo perltype=\$perltype
echo optdebug=\$optdebug
`;
foreach my $line (@o){
chomp $line;
if ($line =~ /(.*?)=\s*(.*)\s*$/){
$cflags{$1} = $2;
print " $1 = $2\n" if $Verbose;
} else {
print "Unrecognised result from hint: '$line'\n";
}
}
}
if ($optdebug) {
$cflags{optimize} = $optdebug;
}
for (qw(ccflags optimize perltype)) {
$cflags{$_} ||= '';
$cflags{$_} =~ s/^\s+//;
$cflags{$_} =~ s/\s+/ /g;
$cflags{$_} =~ s/\s+$//;
$self->{uc $_} ||= $cflags{$_};
}
if ($self->{POLLUTE}) {
$self->{CCFLAGS} .= ' -DPERL_POLLUTE ';
}
for my $x (@ccextraflags) {
next unless exists $cflags{$x};
$self->{CCFLAGS} .= $cflags{$x} =~ m!^\s! ? $cflags{$x} : ' ' . $cflags{$x};
}
my $pollute = '';
if ($Config{usemymalloc} and not $Config{bincompat5005}
and not $Config{ccflags} =~ /-DPERL_POLLUTE_MALLOC\b/
and $self->{PERL_MALLOC_OK}) {
$pollute = '$(PERL_MALLOC_DEF)';
}
return $self->{CFLAGS} = qq{
CCFLAGS = $self->{CCFLAGS}
OPTIMIZE = $self->{OPTIMIZE}
PERLTYPE = $self->{PERLTYPE}
MPOLLUTE = $pollute
};
}
=item const_cccmd (o)
Returns the full compiler call for C programs and stores the
definition in CONST_CCCMD.
=cut
sub const_cccmd {
my($self,$libperl)=@_;
return $self->{CONST_CCCMD} if $self->{CONST_CCCMD};
return '' unless $self->needs_linking();
return $self->{CONST_CCCMD} =
q{CCCMD = $(CC) -c $(PASTHRU_INC) $(INC) \\
$(CCFLAGS) $(OPTIMIZE) \\
$(PERLTYPE) $(MPOLLUTE) $(DEFINE_VERSION) \\
$(XS_DEFINE_VERSION)};
}
=item const_config (o)
Sets SHELL if needed, then defines a couple of constants in the Makefile
that are imported from %Config.
=cut
sub const_config {
# --- Constants Sections ---
my($self) = shift;
my @m = $self->specify_shell(); # Usually returns empty string
push @m, <<"END";
# These definitions are from config.sh (via $INC{'Config.pm'}).
# They may have been overridden via Makefile.PL or on the command line.
END
my(%once_only);
foreach my $key (@{$self->{CONFIG}}){
# SITE*EXP macros are defined in &constants; avoid duplicates here
next if $once_only{$key};
push @m, uc($key) , ' = ' , $self->{uc $key}, "\n";
$once_only{$key} = 1;
}
join('', @m);
}
=item const_loadlibs (o)
Defines EXTRALIBS, LDLOADLIBS, BSLOADLIBS, LD_RUN_PATH. See
L<ExtUtils::Liblist> for details.
=cut
sub const_loadlibs {
my($self) = shift;
return "" unless $self->needs_linking;
my @m;
push @m, qq{
# $self->{NAME} might depend on some other libraries:
# See ExtUtils::Liblist for details
#
};
for my $tmp (qw/
EXTRALIBS LDLOADLIBS BSLOADLIBS
/) {
next unless defined $self->{$tmp};
push @m, "$tmp = $self->{$tmp}\n";
}
# don't set LD_RUN_PATH if empty
for my $tmp (qw/
LD_RUN_PATH
/) {
next unless $self->{$tmp};
push @m, "$tmp = $self->{$tmp}\n";
}
return join "", @m;
}
=item constants (o)
my $make_frag = $mm->constants;
Prints out macros for lots of constants.
=cut
sub constants {
my($self) = @_;
my @m = ();
$self->{DFSEP} = '$(DIRFILESEP)'; # alias for internal use
for my $macro (qw(
AR_STATIC_ARGS ARFLAGS DIRFILESEP DFSEP
NAME NAME_SYM
VERSION VERSION_MACRO VERSION_SYM DEFINE_VERSION
XS_VERSION XS_VERSION_MACRO XS_DEFINE_VERSION
INST_ARCHLIB INST_SCRIPT INST_BIN INST_LIB
INST_MAN1DIR INST_MAN3DIR
MAN1EXT MAN3EXT
INSTALLDIRS INSTALL_BASE DESTDIR PREFIX
PERLPREFIX SITEPREFIX VENDORPREFIX
),
(map { ("INSTALL".$_,
"DESTINSTALL".$_)
} $self->installvars),
qw(
PERL_LIB
PERL_ARCHLIB PERL_ARCHLIBDEP
LIBPERL_A MYEXTLIB
FIRST_MAKEFILE MAKEFILE_OLD MAKE_APERL_FILE
PERLMAINCC PERL_SRC PERL_INC PERL_INCDEP
PERL FULLPERL ABSPERL
PERLRUN FULLPERLRUN ABSPERLRUN
PERLRUNINST FULLPERLRUNINST ABSPERLRUNINST
PERL_CORE
PERM_DIR PERM_RW PERM_RWX
) )
{
next unless defined $self->{$macro};
# pathnames can have sharp signs in them; escape them so
# make doesn't think it is a comment-start character.
$self->{$macro} =~ s/#/\\#/g;
$self->{$macro} = $self->quote_dep($self->{$macro})
if $ExtUtils::MakeMaker::macro_dep{$macro};
push @m, "$macro = $self->{$macro}\n";
}
push @m, qq{
MAKEMAKER = $self->{MAKEMAKER}
MM_VERSION = $self->{MM_VERSION}
MM_REVISION = $self->{MM_REVISION}
};
push @m, q{
# FULLEXT = Pathname for extension directory (eg Foo/Bar/Oracle).
# BASEEXT = Basename part of FULLEXT. May be just equal FULLEXT. (eg Oracle)
# PARENT_NAME = NAME without BASEEXT and no trailing :: (eg Foo::Bar)
# DLBASE = Basename part of dynamic library. May be just equal BASEEXT.
};
for my $macro (qw/
MAKE
FULLEXT BASEEXT PARENT_NAME DLBASE VERSION_FROM INC DEFINE OBJECT
LDFROM LINKTYPE BOOTDEP
/ )
{
next unless defined $self->{$macro};
push @m, "$macro = $self->{$macro}\n";
}
push @m, "
# Handy lists of source code files:
XS_FILES = ".$self->wraplist(sort keys %{$self->{XS}})."
C_FILES = ".$self->wraplist(sort @{$self->{C}})."
O_FILES = ".$self->wraplist(sort @{$self->{O_FILES}})."
H_FILES = ".$self->wraplist(sort @{$self->{H}})."
MAN1PODS = ".$self->wraplist(sort keys %{$self->{MAN1PODS}})."
MAN3PODS = ".$self->wraplist(sort keys %{$self->{MAN3PODS}})."
";
my $configdep = $Config{usecperl} ? 'Config_heavy.pl' : 'Config.pm';
push @m, q{
# Where is the Config information that we are using/depend on
CONFIGDEP = $(PERL_ARCHLIBDEP)}.$self->{DFSEP}.$configdep.
q{ $(PERL_INCDEP)}.$self->{DFSEP}."config.h"
if -e $self->catfile( $self->{PERL_INC}, 'config.h' );
push @m, qq{
# Where to build things
INST_LIBDIR = $self->{INST_LIBDIR}
INST_ARCHLIBDIR = $self->{INST_ARCHLIBDIR}
INST_AUTODIR = $self->{INST_AUTODIR}
INST_ARCHAUTODIR = $self->{INST_ARCHAUTODIR}
INST_STATIC = $self->{INST_STATIC}
INST_DYNAMIC = $self->{INST_DYNAMIC}
INST_BOOT = $self->{INST_BOOT}
};
push @m, qq{
# Extra linker info
EXPORT_LIST = $self->{EXPORT_LIST}
PERL_ARCHIVE = $self->{PERL_ARCHIVE}
PERL_ARCHIVEDEP = $self->{PERL_ARCHIVEDEP}
PERL_ARCHIVE_AFTER = $self->{PERL_ARCHIVE_AFTER}
};
push @m, "
TO_INST_PM = ".$self->wraplist(map $self->quote_dep($_), sort keys %{$self->{PM}})."\n";
join('',@m);
}
=item depend (o)
Same as macro for the depend attribute.
=cut
sub depend {
my($self,%attribs) = @_;
my(@m,$key,$val);
for my $key (sort keys %attribs){
my $val = $attribs{$key};
next unless defined $key and defined $val;
push @m, "$key : $val\n";
}
join "", @m;
}
=item init_DEST
$mm->init_DEST
Defines the DESTDIR and DEST* variables paralleling the INSTALL*.
=cut
sub init_DEST {
my $self = shift;
# Initialize DESTDIR
$self->{DESTDIR} ||= '';
# Make DEST variables.
foreach my $var ($self->installvars) {
my $destvar = 'DESTINSTALL'.$var;
$self->{$destvar} ||= '$(DESTDIR)$(INSTALL'.$var.')';
}
}
=item init_dist
$mm->init_dist;
Defines a lot of macros for distribution support.
macro description default
TAR tar command to use tar
TARFLAGS flags to pass to TAR cvf
ZIP zip command to use zip
ZIPFLAGS flags to pass to ZIP -r
COMPRESS compression command to gzip --best
use for tarfiles
SUFFIX suffix to put on .gz
compressed files
SHAR shar command to use shar
PREOP extra commands to run before
making the archive
POSTOP extra commands to run after
making the archive
TO_UNIX a command to convert linefeeds
to Unix style in your archive
CI command to checkin your ci -u
sources to version control
RCS_LABEL command to label your sources rcs -Nv$(VERSION_SYM): -q
just after CI is run
DIST_CP $how argument to manicopy() best
when the distdir is created
DIST_DEFAULT default target to use to tardist
create a distribution
DISTVNAME name of the resulting archive $(DISTNAME)-$(VERSION)
(minus suffixes)
=cut
sub init_dist {
my $self = shift;
$self->{TAR} ||= 'tar';
$self->{TARFLAGS} ||= 'cvf';
$self->{ZIP} ||= 'zip';
$self->{ZIPFLAGS} ||= '-r';
$self->{COMPRESS} ||= 'gzip --best';
$self->{SUFFIX} ||= '.gz';
$self->{SHAR} ||= 'shar';
$self->{PREOP} ||= '$(NOECHO) $(NOOP)'; # eg update MANIFEST
$self->{POSTOP} ||= '$(NOECHO) $(NOOP)'; # eg remove the distdir
$self->{TO_UNIX} ||= '$(NOECHO) $(NOOP)';
$self->{CI} ||= 'ci -u';
$self->{RCS_LABEL}||= 'rcs -Nv$(VERSION_SYM): -q';
$self->{DIST_CP} ||= 'best';
$self->{DIST_DEFAULT} ||= 'tardist';
($self->{DISTNAME} = $self->{NAME}) =~ s{::}{-}g unless $self->{DISTNAME};
$self->{DISTVNAME} ||= $self->{DISTNAME}.'-'.$self->{VERSION};
}
=item dist (o)
my $dist_macros = $mm->dist(%overrides);
Generates a make fragment defining all the macros initialized in
init_dist.
%overrides can be used to override any of the above.
=cut
sub dist {
my($self, %attribs) = @_;
my $make = '';
if ( $attribs{SUFFIX} && $attribs{SUFFIX} !~ m!^\.! ) {
$attribs{SUFFIX} = '.' . $attribs{SUFFIX};
}
foreach my $key (qw(
TAR TARFLAGS ZIP ZIPFLAGS COMPRESS SUFFIX SHAR
PREOP POSTOP TO_UNIX
CI RCS_LABEL DIST_CP DIST_DEFAULT
DISTNAME DISTVNAME
))
{
my $value = $attribs{$key} || $self->{$key};
$make .= "$key = $value\n";
}
return $make;
}
=item dist_basics (o)
Defines the targets distclean, distcheck, skipcheck, manifest, veryclean.
=cut
sub dist_basics {
my($self) = shift;
return <<'MAKE_FRAG';
distclean :: realclean distcheck
$(NOECHO) $(NOOP)
distcheck :
$(PERLRUN) "-MExtUtils::Manifest=fullcheck" -e fullcheck
skipcheck :
$(PERLRUN) "-MExtUtils::Manifest=skipcheck" -e skipcheck
manifest :
$(PERLRUN) "-MExtUtils::Manifest=mkmanifest" -e mkmanifest
veryclean : realclean
$(RM_F) *~ */*~ *.orig */*.orig *.bak */*.bak *.old */*.old
MAKE_FRAG
}
=item dist_ci (o)
Defines a check in target for RCS.
=cut
sub dist_ci {
my($self) = shift;
return sprintf "ci :\n\t%s\n", $self->oneliner(<<'EOF', [qw(-MExtUtils::Manifest=maniread)]);
@all = sort keys %{ maniread() };
print(qq{Executing $(CI) @all\n});
system(qq{$(CI) @all}) == 0 or die $!;
print(qq{Executing $(RCS_LABEL) ...\n});
system(qq{$(RCS_LABEL) @all}) == 0 or die $!;
EOF
}
=item dist_core (o)
my $dist_make_fragment = $MM->dist_core;
Puts the targets necessary for 'make dist' together into one make
fragment.
=cut
sub dist_core {
my($self) = shift;
my $make_frag = '';
foreach my $target (qw(dist tardist uutardist tarfile zipdist zipfile
shdist))
{
my $method = $target.'_target';
$make_frag .= "\n";
$make_frag .= $self->$method();
}
return $make_frag;
}
=item B<dist_target>
my $make_frag = $MM->dist_target;
Returns the 'dist' target to make an archive for distribution. This
target simply checks to make sure the Makefile is up-to-date and
depends on $(DIST_DEFAULT).
=cut
sub dist_target {
my($self) = shift;
my $date_check = $self->oneliner(<<'CODE', ['-l']);
print 'Warning: Makefile possibly out of date with $(VERSION_FROM)'
if -e '$(VERSION_FROM)' and -M '$(VERSION_FROM)' < -M '$(FIRST_MAKEFILE)';
CODE
return sprintf <<'MAKE_FRAG', $date_check;
dist : $(DIST_DEFAULT) $(FIRST_MAKEFILE)
$(NOECHO) %s
MAKE_FRAG
}
=item B<tardist_target>
my $make_frag = $MM->tardist_target;
Returns the 'tardist' target which is simply so 'make tardist' works.
The real work is done by the dynamically named tardistfile_target()
method, tardist should have that as a dependency.
=cut
sub tardist_target {
my($self) = shift;
return <<'MAKE_FRAG';
tardist : $(DISTVNAME).tar$(SUFFIX)
$(NOECHO) $(NOOP)
MAKE_FRAG
}
=item B<zipdist_target>
my $make_frag = $MM->zipdist_target;
Returns the 'zipdist' target which is simply so 'make zipdist' works.
The real work is done by the dynamically named zipdistfile_target()
method, zipdist should have that as a dependency.
=cut
sub zipdist_target {
my($self) = shift;
return <<'MAKE_FRAG';
zipdist : $(DISTVNAME).zip
$(NOECHO) $(NOOP)
MAKE_FRAG
}
=item B<tarfile_target>
my $make_frag = $MM->tarfile_target;
The name of this target is the name of the tarball generated by
tardist. This target does the actual work of turning the distdir into
a tarball.
=cut
sub tarfile_target {
my($self) = shift;
return <<'MAKE_FRAG';
$(DISTVNAME).tar$(SUFFIX) : distdir
$(PREOP)
$(TO_UNIX)
$(TAR) $(TARFLAGS) $(DISTVNAME).tar $(DISTVNAME)
$(RM_RF) $(DISTVNAME)
$(COMPRESS) $(DISTVNAME).tar
$(NOECHO) $(ECHO) 'Created $(DISTVNAME).tar$(SUFFIX)'
$(POSTOP)
MAKE_FRAG
}
=item zipfile_target
my $make_frag = $MM->zipfile_target;
The name of this target is the name of the zip file generated by
zipdist. This target does the actual work of turning the distdir into
a zip file.
=cut
sub zipfile_target {
my($self) = shift;
return <<'MAKE_FRAG';
$(DISTVNAME).zip : distdir
$(PREOP)
$(ZIP) $(ZIPFLAGS) $(DISTVNAME).zip $(DISTVNAME)
$(RM_RF) $(DISTVNAME)
$(NOECHO) $(ECHO) 'Created $(DISTVNAME).zip'
$(POSTOP)
MAKE_FRAG
}
=item uutardist_target
my $make_frag = $MM->uutardist_target;
Converts the tarfile into a uuencoded file
=cut
sub uutardist_target {
my($self) = shift;
return <<'MAKE_FRAG';
uutardist : $(DISTVNAME).tar$(SUFFIX)
uuencode $(DISTVNAME).tar$(SUFFIX) $(DISTVNAME).tar$(SUFFIX) > $(DISTVNAME).tar$(SUFFIX)_uu
$(NOECHO) $(ECHO) 'Created $(DISTVNAME).tar$(SUFFIX)_uu'
MAKE_FRAG
}
=item shdist_target
my $make_frag = $MM->shdist_target;
Converts the distdir into a shell archive.
=cut
sub shdist_target {
my($self) = shift;
return <<'MAKE_FRAG';
shdist : distdir
$(PREOP)
$(SHAR) $(DISTVNAME) > $(DISTVNAME).shar
$(RM_RF) $(DISTVNAME)
$(NOECHO) $(ECHO) 'Created $(DISTVNAME).shar'
$(POSTOP)
MAKE_FRAG
}
=item dlsyms (o)
Used by some OS' to define DL_FUNCS and DL_VARS and write the *.exp files.
Normally just returns an empty string.
=cut
sub dlsyms {
return '';
}
=item dynamic_bs (o)
Defines targets for bootstrap files.
=cut
sub dynamic_bs {
my($self, %attribs) = @_;
return "\nBOOTSTRAP =\n" unless $self->has_link_code();
my @exts;
if ($self->{XSMULTI}) {
@exts = $self->_xs_list_basenames;
} else {
@exts = '$(BASEEXT)';
}
return join "\n",
"BOOTSTRAP = @{[map { qq{$_.bs} } @exts]}\n",
map { $self->_xs_make_bs($_) } @exts;
}
sub _xs_make_bs {
my ($self, $basename) = @_;
my ($v, $d, $f) = File::Spec->splitpath($basename);
my @d = File::Spec->splitdir($d);
shift @d if $self->{XSMULTI} and $d[0] eq 'lib';
my $instdir = $self->catdir('$(INST_ARCHLIB)', 'auto', @d, $f);
$instdir = '$(INST_ARCHAUTODIR)' if $basename eq '$(BASEEXT)';
my $instfile = $self->catfile($instdir, "$f.bs");
my $exists = "$instdir\$(DFSEP).exists"; # match blibdirs_target
# 1 2 3
return _sprintf562 <<'MAKE_FRAG', $basename, $instfile, $exists;
# As Mkbootstrap might not write a file (if none is required)
# we use touch to prevent make continually trying to remake it.
# The DynaLoader only reads a non-empty file.
%1$s.bs : $(FIRST_MAKEFILE) $(BOOTDEP)
$(NOECHO) $(PERLRUN) \
"-MExtUtils::Mkbootstrap" \
-e "Mkbootstrap('%1$s','$(BSLOADLIBS)');"
$(NOECHO) $(TOUCH) "%1$s.bs"
$(CHMOD) $(PERM_RW) "%1$s.bs"
%2$s : %1$s.bs %3$s
$(NOECHO) $(RM_RF) %2$s
- $(CP_NONEMPTY) %1$s.bs %2$s $(PERM_RW)
MAKE_FRAG
}
=item dynamic_lib (o)
Defines how to produce the *.so (or equivalent) files.
=cut
sub dynamic_lib {
my($self, %attribs) = @_;
return '' unless $self->needs_linking(); #might be because of a subdir
return '' unless $self->has_link_code;
my @m = $self->xs_dynamic_lib_macros(\%attribs);
my @libs;
my $dlsyms_ext = eval { $self->xs_dlsyms_ext };
if ($self->{XSMULTI}) {
my @exts = $self->_xs_list_basenames;
for my $ext (@exts) {
my ($v, $d, $f) = File::Spec->splitpath($ext);
my @d = File::Spec->splitdir($d);
shift @d if $d[0] eq 'lib';
my $instdir = $self->catdir('$(INST_ARCHLIB)', 'auto', @d, $f);
# Dynamic library names may need special handling.
eval { require DynaLoader };
if (defined &DynaLoader::mod2fname) {
$f = &DynaLoader::mod2fname([@d, $f]);
}
my $instfile = $self->catfile($instdir, "$f.\$(DLEXT)");
my $objfile = $self->_xsbuild_value('xs', $ext, 'OBJECT');
$objfile = "$ext\$(OBJ_EXT)" unless defined $objfile;
my $ldfrom = $self->_xsbuild_value('xs', $ext, 'LDFROM');
$ldfrom = $objfile unless defined $ldfrom;
my $exportlist = "$ext.def";
my @libchunk = ($objfile, $instfile, $instdir, $ldfrom, $exportlist);
push @libchunk, $dlsyms_ext ? $ext.$dlsyms_ext : undef;
push @libs, \@libchunk;
}
} else {
my @libchunk = qw($(OBJECT) $(INST_DYNAMIC) $(INST_ARCHAUTODIR) $(LDFROM) $(EXPORT_LIST));
push @libchunk, $dlsyms_ext ? '$(BASEEXT)'.$dlsyms_ext : undef;
@libs = (\@libchunk);
}
push @m, map { $self->xs_make_dynamic_lib(\%attribs, @$_); } @libs;
return join("\n",@m);
}
=item xs_dynamic_lib_macros
Defines the macros for the C<dynamic_lib> section.
=cut
sub xs_dynamic_lib_macros {
my ($self, $attribs) = @_;
my $otherldflags = $attribs->{OTHERLDFLAGS} || "";
my $inst_dynamic_dep = $attribs->{INST_DYNAMIC_DEP} || "";
my $armaybe = $self->_xs_armaybe($attribs);
my $ld_opt = $Is{OS2} ? '$(OPTIMIZE) ' : ''; # Useful on other systems too?
my $ld_fix = $Is{OS2} ? '|| ( $(RM_F) $@ && sh -c false )' : '';
$ld_fix = '&& dsymutil "$@"' if $Is{Darwin} and $Config{ccflags} =~ /-DDEBUGGING/;
sprintf <<'EOF', $armaybe, $ld_opt.$otherldflags, $inst_dynamic_dep, $ld_fix;
# This section creates the dynamically loadable objects from relevant
# objects and possibly $(MYEXTLIB).
ARMAYBE = %s
OTHERLDFLAGS = %s
INST_DYNAMIC_DEP = %s
INST_DYNAMIC_FIX = %s
EOF
}
sub _xs_armaybe {
my ($self, $attribs) = @_;
my $armaybe = $attribs->{ARMAYBE} || $self->{ARMAYBE} || ":";
$armaybe = 'ar' if ($Is{OSF} and $armaybe eq ':');
$armaybe;
}
=item xs_make_dynamic_lib
Defines the recipes for the C<dynamic_lib> section.
=cut
sub xs_make_dynamic_lib {
my ($self, $attribs, $object, $to, $todir, $ldfrom, $exportlist, $dlsyms) = @_;
$exportlist = '' if $exportlist ne '$(EXPORT_LIST)';
my $armaybe = $self->_xs_armaybe($attribs);
my @m = sprintf '%s : %s $(MYEXTLIB) %s$(DFSEP).exists %s $(PERL_ARCHIVEDEP) $(PERL_ARCHIVE_AFTER) $(INST_DYNAMIC_DEP) %s'."\n", $to, $object, $todir, $exportlist, ($dlsyms || '');
my $dlsyms_arg = $self->xs_dlsyms_arg($dlsyms);
if ($armaybe ne ':'){
$ldfrom = 'tmp$(LIB_EXT)';
push(@m," \$(ARMAYBE) cr $ldfrom $object\n");
push(@m," \$(RANLIB) $ldfrom\n");
}
$ldfrom = "-all $ldfrom -none" if $Is{OSF};
# The IRIX linker doesn't use LD_RUN_PATH
my $ldrun = $Is{IRIX} && $self->{LD_RUN_PATH} ?
qq{-rpath "$self->{LD_RUN_PATH}"} : '';
# For example in AIX the shared objects/libraries from previous builds
# linger quite a while in the shared dynalinker cache even when nobody
# is using them. This is painful if one for instance tries to restart
# a failed build because the link command will fail unnecessarily 'cos
# the shared object/library is 'busy'.
push(@m," \$(RM_F) \$\@\n");
my $libs = '$(LDLOADLIBS)';
if (($Is{NetBSD} || $Is{Interix} || $Is{Android}) && $Config{'useshrplib'} eq 'true') {
# Use nothing on static perl platforms, and to the flags needed
# to link against the shared libperl library on shared perl
# platforms. We peek at lddlflags to see if we need -Wl,-R
# or -R to add paths to the run-time library search path.
if ($Config{'lddlflags'} =~ /-Wl,-R/) {
$libs .= ' "-L$(PERL_INC)" "-Wl,-R$(INSTALLARCHLIB)/CORE" "-Wl,-R$(PERL_ARCHLIB)/CORE" -lperl';
} elsif ($Config{'lddlflags'} =~ /-R/) {
$libs .= ' "-L$(PERL_INC)" "-R$(INSTALLARCHLIB)/CORE" "-R$(PERL_ARCHLIB)/CORE" -lperl';
} elsif ( $Is{Android} ) {
# The Android linker will not recognize symbols from
# libperl unless the module explicitly depends on it.
$libs .= ' "-L$(PERL_INC)" -lperl';
}
}
my $ld_run_path_shell = "";
if ($self->{LD_RUN_PATH} ne "") {
$ld_run_path_shell = 'LD_RUN_PATH="$(LD_RUN_PATH)" ';
}
push @m, sprintf <<'MAKE', $ld_run_path_shell, $ldrun, $dlsyms_arg, $ldfrom, $self->xs_obj_opt('$@'), $libs, $exportlist;
%s$(LD) %s $(LDDLFLAGS) %s %s $(OTHERLDFLAGS) %s $(MYEXTLIB) \
$(PERL_ARCHIVE) %s $(PERL_ARCHIVE_AFTER) %s \
$(INST_DYNAMIC_FIX)
$(CHMOD) $(PERM_RWX) $@
MAKE
join '', @m;
}
=item exescan
Deprecated method. Use libscan instead.
=cut
sub exescan {
my($self,$path) = @_;
$path;
}
=item extliblist
Called by init_others, and calls ext ExtUtils::Liblist. See
L<ExtUtils::Liblist> for details.
=cut
sub extliblist {
my($self,$libs) = @_;
require ExtUtils::Liblist;
$self->ext($libs, $Verbose);
}
=item find_perl
Finds the executables PERL and FULLPERL
=cut
sub find_perl {
my($self, $ver, $names, $dirs, $trace) = @_;
if ($trace >= 2){
print "Looking for perl $ver by these names:
@$names
in these dirs:
@$dirs
";
}
my $stderr_duped = 0;
local *STDERR_COPY;
unless ($Is{BSD}) {
# >& and lexical filehandles together give 5.6.2 indigestion
if( open(STDERR_COPY, '>&STDERR') ) { ## no critic
$stderr_duped = 1;
}
else {
warn <<WARNING;
find_perl() can't dup STDERR: $!
You might see some garbage while we search for Perl
WARNING
}
}
foreach my $name (@$names){
my ($abs, $use_dir);
if ($self->file_name_is_absolute($name)) { # /foo/bar
$abs = $name;
} elsif ($self->canonpath($name) eq
$self->canonpath(basename($name))) { # foo
$use_dir = 1;
} else { # foo/bar
$abs = $self->catfile($Curdir, $name);
}
foreach my $dir ($use_dir ? @$dirs : 1){
next unless defined $dir; # $self->{PERL_SRC} may be undefined
$abs = $self->catfile($dir, $name)
if $use_dir;
print "Checking $abs\n" if ($trace >= 2);
next unless $self->maybe_command($abs);
print "Executing $abs\n" if ($trace >= 2);
my $val;
my $version_check = qq{"$abs" -le "require $ver; print qq{VER_OK}"};
# To avoid using the unportable 2>&1 to suppress STDERR,
# we close it before running the command.
# However, thanks to a thread library bug in many BSDs
# ( http://www.freebsd.org/cgi/query-pr.cgi?pr=51535 )
# we cannot use the fancier more portable way in here
# but instead need to use the traditional 2>&1 construct.
if ($Is{BSD}) {
$val = `$version_check 2>&1`;
} else {
close STDERR if $stderr_duped;
$val = `$version_check`;
# 5.6.2's 3-arg open doesn't work with >&
open STDERR, ">&STDERR_COPY" ## no critic
if $stderr_duped;
}
if ($val =~ /^VER_OK/m) {
print "Using PERL=$abs\n" if $trace;
return $abs;
} elsif ($trace >= 2) {
print "Result: '$val' ".($? >> 8)."\n";
}
}
}
print "Unable to find a perl $ver (by these names: @$names, in these dirs: @$dirs)\n";
0; # false and not empty
}
=item fixin
$mm->fixin(@files);
Inserts the sharpbang or equivalent magic number to a set of @files.
=cut
sub fixin { # stolen from the pink Camel book, more or less
my ( $self, @files ) = @_;
for my $file (@files) {
my $file_new = "$file.new";
my $file_bak = "$file.bak";
open( my $fixin, '<', $file ) or croak "Can't process '$file': $!";
local $/ = "\n";
chomp( my $line = <$fixin> );
next unless $line =~ s/^\s*\#!\s*//; # Not a shebang file.
my $shb = $self->_fixin_replace_shebang( $file, $line );
next unless defined $shb;
open( my $fixout, ">", "$file_new" ) or do {
warn "Can't create new $file: $!\n";
next;
};
# Print out the new #! line (or equivalent).
local $\;
local $/;
print $fixout $shb, <$fixin>;
close $fixin;
close $fixout;
chmod 0666, $file_bak;
unlink $file_bak;
unless ( _rename( $file, $file_bak ) ) {
warn "Can't rename $file to $file_bak: $!";
next;
}
unless ( _rename( $file_new, $file ) ) {
warn "Can't rename $file_new to $file: $!";
unless ( _rename( $file_bak, $file ) ) {
warn "Can't rename $file_bak back to $file either: $!";
warn "Leaving $file renamed as $file_bak\n";
}
next;
}
unlink $file_bak;
}
continue {
system("$Config{'eunicefix'} $file") if $Config{'eunicefix'} ne ':';
}
}
sub _rename {
my($old, $new) = @_;
foreach my $file ($old, $new) {
if( $Is{VMS} and basename($file) !~ /\./ ) {
# rename() in 5.8.0 on VMS will not rename a file if it
# does not contain a dot yet it returns success.
$file = "$file.";
}
}
return rename($old, $new);
}
sub _fixin_replace_shebang {
my ( $self, $file, $line ) = @_;
# Now figure out the interpreter name.
my ( $cmd, $arg ) = split ' ', $line, 2;
$cmd =~ s!^.*/!!;
# Now look (in reverse) for interpreter in absolute PATH (unless perl).
my $interpreter;
if ( defined $ENV{PERL_MM_SHEBANG} && $ENV{PERL_MM_SHEBANG} eq "relocatable" ) {
$interpreter = "/usr/bin/env perl";
}
elsif ( $cmd =~ m{^perl(?:\z|[^a-z])} ) {
if ( $Config{startperl} =~ m,^\#!.*/perl, ) {
$interpreter = $Config{startperl};
$interpreter =~ s,^\#!,,;
}
else {
$interpreter = $Config{perlpath};
}
}
else {
my (@absdirs)
= reverse grep { $self->file_name_is_absolute($_) } $self->path;
$interpreter = '';
foreach my $dir (@absdirs) {
my $maybefile = $self->catfile($dir,$cmd);
if ( $self->maybe_command($maybefile) ) {
warn "Ignoring $interpreter in $file\n"
if $Verbose && $interpreter;
$interpreter = $maybefile;
}
}
}
# Figure out how to invoke interpreter on this machine.
my ($does_shbang) = $Config{'sharpbang'} =~ /^\s*\#\!/;
my ($shb) = "";
if ($interpreter) {
print "Changing sharpbang in $file to $interpreter"
if $Verbose;
# this is probably value-free on DOSISH platforms
if ($does_shbang) {
$shb .= "$Config{'sharpbang'}$interpreter";
$shb .= ' ' . $arg if defined $arg;
$shb .= "\n";
}
}
else {
warn "Can't find $cmd in PATH, $file unchanged"
if $Verbose;
return;
}
return $shb
}
=item force (o)
Writes an empty FORCE: target.
=cut
sub force {
my($self) = shift;
'# Phony target to force checking subdirectories.
FORCE :
$(NOECHO) $(NOOP)
';
}
=item guess_name
Guess the name of this package by examining the working directory's
name. MakeMaker calls this only if the developer has not supplied a
NAME attribute.
=cut
# ';
sub guess_name {
my($self) = @_;
use Cwd 'cwd';
my $name = basename(cwd());
$name =~ s|[\-_][\d\.\-]+\z||; # this is new with MM 5.00, we
# strip minus or underline
# followed by a float or some such
print "Warning: Guessing NAME [$name] from current directory name.\n";
$name;
}
=item has_link_code
Returns true if C, XS, MYEXTLIB or similar objects exist within this
object that need a compiler. Does not descend into subdirectories as
needs_linking() does.
=cut
sub has_link_code {
my($self) = shift;
return $self->{HAS_LINK_CODE} if defined $self->{HAS_LINK_CODE};
if ($self->{OBJECT} or @{$self->{C} || []} or $self->{MYEXTLIB}){
$self->{HAS_LINK_CODE} = 1;
return 1;
}
return $self->{HAS_LINK_CODE} = 0;
}
=item init_dirscan
Scans the directory structure and initializes DIR, XS, XS_FILES,
C, C_FILES, O_FILES, H, H_FILES, PL_FILES, EXE_FILES.
Called by init_main.
=cut
sub init_dirscan { # --- File and Directory Lists (.xs .pm .pod etc)
my($self) = @_;
my(%dir, %xs, %c, %o, %h, %pl_files, %pm);
my %ignore = map {( $_ => 1 )} qw(Makefile.PL Build.PL test.pl t);
# ignore the distdir
$Is{VMS} ? $ignore{"$self->{DISTVNAME}.dir"} = 1
: $ignore{$self->{DISTVNAME}} = 1;
my $distprefix = $Is{VMS} ? qr/^\Q$self->{DISTNAME}\E-v?[\d\.]+\.dir$/i
: qr/^\Q$self->{DISTNAME}\E-v?[\d\.]+$/;
@ignore{map lc, keys %ignore} = values %ignore if $Is{VMS};
if ( defined $self->{XS} and !defined $self->{C} ) {
my @c_files = grep { m/\.c(pp|xx)?\z/i } values %{$self->{XS}};
my @o_files = grep { m/(?:.(?:o(?:bj)?)|\$\(OBJ_EXT\))\z/i } values %{$self->{XS}};
%c = map { $_ => 1 } @c_files;
%o = map { $_ => 1 } @o_files;
}
foreach my $name ($self->lsdir($Curdir)){
next if $name =~ /\#/;
next if $name =~ $distprefix && -d $name;
$name = lc($name) if $Is{VMS};
next if $name eq $Curdir or $name eq $Updir or $ignore{$name};
next unless $self->libscan($name);
if (-d $name){
next if -l $name; # We do not support symlinks at all
next if $self->{NORECURS};
$dir{$name} = $name if (-f $self->catfile($name,"Makefile.PL"));
} elsif ($name =~ /\.xs\z/){
my($c); ($c = $name) =~ s/\.xs\z/.c/;
$xs{$name} = $c;
$c{$c} = 1;
} elsif ($name =~ /\.c(pp|xx|c)?\z/i){ # .c .C .cpp .cxx .cc
$c{$name} = 1
unless $name =~ m/perlmain\.c/; # See MAP_TARGET
} elsif ($name =~ /\.h\z/i){
$h{$name} = 1;
} elsif ($name =~ /\.PL\z/) {
($pl_files{$name} = $name) =~ s/\.PL\z// ;
} elsif (($Is{VMS} || $Is{Dos}) && $name =~ /[._]pl$/i) {
# case-insensitive filesystem, one dot per name, so foo.h.PL
# under Unix appears as foo.h_pl under VMS or fooh.pl on Dos
local($/); open(my $pl, '<', $name); my $txt = <$pl>; close $pl;
if ($txt =~ /Extracting \S+ \(with variable substitutions/) {
($pl_files{$name} = $name) =~ s/[._]pl\z//i ;
}
else {
$pm{$name} = $self->catfile($self->{INST_LIBDIR},$name);
}
} elsif ($name =~ /\.(p[ml]|pod)\z/){
$pm{$name} = $self->catfile($self->{INST_LIBDIR},$name);
}
}
$self->{PL_FILES} ||= \%pl_files;
$self->{DIR} ||= [sort keys %dir];
$self->{XS} ||= \%xs;
$self->{C} ||= [sort keys %c];
$self->{H} ||= [sort keys %h];
$self->{PM} ||= \%pm;
my @o_files = @{$self->{C}};
%o = (%o, map { $_ => 1 } grep s/\.c(pp|xx|c)?\z/$self->{OBJ_EXT}/i, @o_files);
$self->{O_FILES} = [sort keys %o];
}
=item init_MANPODS
Determines if man pages should be generated and initializes MAN1PODS
and MAN3PODS as appropriate.
=cut
sub init_MANPODS {
my $self = shift;
# Set up names of manual pages to generate from pods
foreach my $man (qw(MAN1 MAN3)) {
if ( $self->{"${man}PODS"}
or $self->{"INSTALL${man}DIR"} =~ /^(none|\s*)$/
) {
$self->{"${man}PODS"} ||= {};
}
else {
my $init_method = "init_${man}PODS";
$self->$init_method();
}
}
}
sub _has_pod {
my($self, $file) = @_;
my($ispod)=0;
if (open( my $fh, '<', $file )) {
while (<$fh>) {
if (/^=(?:head\d+|item|pod)\b/) {
$ispod=1;
last;
}
}
close $fh;
} else {
# If it doesn't exist yet, we assume, it has pods in it
$ispod = 1;
}
return $ispod;
}
=item init_MAN1PODS
Initializes MAN1PODS from the list of EXE_FILES.
=cut
sub init_MAN1PODS {
my($self) = @_;
if ( exists $self->{EXE_FILES} ) {
foreach my $name (@{$self->{EXE_FILES}}) {
next unless $self->_has_pod($name);
$self->{MAN1PODS}->{$name} =
$self->catfile("\$(INST_MAN1DIR)",
basename($name).".\$(MAN1EXT)");
}
}
}
=item init_MAN3PODS
Initializes MAN3PODS from the list of PM files.
=cut
sub init_MAN3PODS {
my $self = shift;
my %manifypods = (); # we collect the keys first, i.e. the files
# we have to convert to pod
foreach my $name (keys %{$self->{PM}}) {
if ($name =~ /\.pod\z/ ) {
$manifypods{$name} = $self->{PM}{$name};
} elsif ($name =~ /\.p[ml]\z/ ) {
if( $self->_has_pod($name) ) {
$manifypods{$name} = $self->{PM}{$name};
}
}
}
my $parentlibs_re = join '|', @{$self->{PMLIBPARENTDIRS}};
# Remove "Configure.pm" and similar, if it's not the only pod listed
# To force inclusion, just name it "Configure.pod", or override
# MAN3PODS
foreach my $name (keys %manifypods) {
if (
($self->{PERL_CORE} and $name =~ /(config|setup).*\.pm/is) or
( $name =~ m/^README\.pod$/i ) # don't manify top-level README.pod
) {
delete $manifypods{$name};
next;
}
my($manpagename) = $name;
$manpagename =~ s/\.p(od|m|l)\z//;
# everything below lib is ok
unless($manpagename =~ s!^\W*($parentlibs_re)\W+!!s) {
$manpagename = $self->catfile(
split(/::/,$self->{PARENT_NAME}),$manpagename
);
}
$manpagename = $self->replace_manpage_separator($manpagename);
$self->{MAN3PODS}->{$name} =
$self->catfile("\$(INST_MAN3DIR)", "$manpagename.\$(MAN3EXT)");
}
}
=item init_PM
Initializes PMLIBDIRS and PM from PMLIBDIRS.
=cut
sub init_PM {
my $self = shift;
# Some larger extensions often wish to install a number of *.pm/pl
# files into the library in various locations.
# The attribute PMLIBDIRS holds an array reference which lists
# subdirectories which we should search for library files to
# install. PMLIBDIRS defaults to [ 'lib', $self->{BASEEXT} ]. We
# recursively search through the named directories (skipping any
# which don't exist or contain Makefile.PL files).
# For each *.pm or *.pl file found $self->libscan() is called with
# the default installation path in $_[1]. The return value of
# libscan defines the actual installation location. The default
# libscan function simply returns the path. The file is skipped
# if libscan returns false.
# The default installation location passed to libscan in $_[1] is:
#
# ./*.pm => $(INST_LIBDIR)/*.pm
# ./xyz/... => $(INST_LIBDIR)/xyz/...
# ./lib/... => $(INST_LIB)/...
#
# In this way the 'lib' directory is seen as the root of the actual
# perl library whereas the others are relative to INST_LIBDIR
# (which includes PARENT_NAME). This is a subtle distinction but one
# that's important for nested modules.
unless( $self->{PMLIBDIRS} ) {
if( $Is{VMS} ) {
# Avoid logical name vs directory collisions
$self->{PMLIBDIRS} = ['./lib', "./$self->{BASEEXT}"];
}
else {
$self->{PMLIBDIRS} = ['lib', $self->{BASEEXT}];
}
}
#only existing directories that aren't in $dir are allowed
# Avoid $_ wherever possible:
# @{$self->{PMLIBDIRS}} = grep -d && !$dir{$_}, @{$self->{PMLIBDIRS}};
my (@pmlibdirs) = @{$self->{PMLIBDIRS}};
@{$self->{PMLIBDIRS}} = ();
my %dir = map { ($_ => $_) } @{$self->{DIR}};
foreach my $pmlibdir (@pmlibdirs) {
-d $pmlibdir && !$dir{$pmlibdir} && push @{$self->{PMLIBDIRS}}, $pmlibdir;
}
unless( $self->{PMLIBPARENTDIRS} ) {
@{$self->{PMLIBPARENTDIRS}} = ('lib');
}
return if $self->{PM} and $self->{ARGS}{PM};
if (@{$self->{PMLIBDIRS}}){
print "Searching PMLIBDIRS: @{$self->{PMLIBDIRS}}\n"
if ($Verbose >= 2);
require File::Find;
File::Find::find(sub {
if (-d $_){
unless ($self->libscan($_)){
$File::Find::prune = 1;
}
return;
}
return if /\#/;
return if /~$/; # emacs temp files
return if /,v$/; # RCS files
return if m{\.swp$}; # vim swap files
my $path = $File::Find::name;
my $prefix = $self->{INST_LIBDIR};
my $striplibpath;
my $parentlibs_re = join '|', @{$self->{PMLIBPARENTDIRS}};
$prefix = $self->{INST_LIB}
if ($striplibpath = $path) =~ s{^(\W*)($parentlibs_re)\W}
{$1}i;
my($inst) = $self->catfile($prefix,$striplibpath);
local($_) = $inst; # for backwards compatibility
$inst = $self->libscan($inst);
print "libscan($path) => '$inst'\n" if ($Verbose >= 2);
return unless $inst;
if ($self->{XSMULTI} and $inst =~ /\.xs\z/) {
my($base); ($base = $path) =~ s/\.xs\z//;
$self->{XS}{$path} = "$base.c";
push @{$self->{C}}, "$base.c";
push @{$self->{O_FILES}}, "$base$self->{OBJ_EXT}";
} else {
$self->{PM}{$path} = $inst;
}
}, @{$self->{PMLIBDIRS}});
}
}
=item init_DIRFILESEP
Using / for Unix. Called by init_main.
=cut
sub init_DIRFILESEP {
my($self) = shift;
$self->{DIRFILESEP} = '/';
}
=item init_main
Initializes AR, AR_STATIC_ARGS, BASEEXT, CONFIG, DISTNAME, DLBASE,
EXE_EXT, FULLEXT, FULLPERL, FULLPERLRUN, FULLPERLRUNINST, INST_*,
INSTALL*, INSTALLDIRS, LIB_EXT, LIBPERL_A, MAP_TARGET, NAME,
OBJ_EXT, PARENT_NAME, PERL, PERL_ARCHLIB, PERL_INC, PERL_LIB,
PERL_SRC, PERLRUN, PERLRUNINST, PREFIX, VERSION,
VERSION_SYM, XS_VERSION.
=cut
sub init_main {
my($self) = @_;
# --- Initialize Module Name and Paths
# NAME = Foo::Bar::Oracle
# FULLEXT = Foo/Bar/Oracle
# BASEEXT = Oracle
# PARENT_NAME = Foo::Bar
### Only UNIX:
### ($self->{FULLEXT} =
### $self->{NAME}) =~ s!::!/!g ; #eg. BSD/Foo/Socket
$self->{FULLEXT} = $self->catdir(split /::/, $self->{NAME});
# Copied from DynaLoader:
my(@modparts) = split(/::/,$self->{NAME});
my($modfname) = $modparts[-1];
# Some systems have restrictions on files names for DLL's etc.
# mod2fname returns appropriate file base name (typically truncated)
# It may also edit @modparts if required.
# We require DynaLoader to make sure that mod2fname is loaded
eval { require DynaLoader };
if (defined &DynaLoader::mod2fname) {
$modfname = &DynaLoader::mod2fname(\@modparts);
}
($self->{PARENT_NAME}, $self->{BASEEXT}) = $self->{NAME} =~ m!(?:([\w:]+)::)?(\w+)\z! ;
$self->{PARENT_NAME} ||= '';
if (defined &DynaLoader::mod2fname) {
# As of 5.001m, dl_os2 appends '_'
$self->{DLBASE} = $modfname;
} else {
$self->{DLBASE} = '$(BASEEXT)';
}
# --- Initialize PERL_LIB, PERL_SRC
# *Real* information: where did we get these two from? ...
my $inc_config_dir = dirname($INC{'Config.pm'});
my $inc_carp_dir = dirname($INC{'Carp.pm'});
unless ($self->{PERL_SRC}){
foreach my $dir_count (1..8) { # 8 is the VMS limit for nesting
my $dir = $self->catdir(($Updir) x $dir_count);
if (-f $self->catfile($dir,"config_h.SH") &&
-f $self->catfile($dir,"perl.h") &&
-f $self->catfile($dir,"lib","strict.pm")
) {
$self->{PERL_SRC}=$dir ;
last;
}
}
}
warn "PERL_CORE is set but I can't find your PERL_SRC!\n" if
$self->{PERL_CORE} and !$self->{PERL_SRC};
if ($self->{PERL_SRC}){
$self->{PERL_LIB} ||= $self->catdir("$self->{PERL_SRC}","lib");
$self->{PERL_ARCHLIB} = $self->{PERL_LIB};
$self->{PERL_INC} = ($Is{Win32}) ?
$self->catdir($self->{PERL_LIB},"CORE") : $self->{PERL_SRC};
# catch a situation that has occurred a few times in the past:
unless (
-s $self->catfile($self->{PERL_SRC},'cflags')
or
$Is{VMS}
&&
-s $self->catfile($self->{PERL_SRC},'vmsish.h')
or
$Is{Win32}
){
warn qq{
You cannot build extensions below the perl source tree after executing
a 'make clean' in the perl source tree.
To rebuild extensions distributed with the perl source you should
simply Configure (to include those extensions) and then build perl as
normal. After installing perl the source tree can be deleted. It is
not needed for building extensions by running 'perl Makefile.PL'
usually without extra arguments.
It is recommended that you unpack and build additional extensions away
from the perl source tree.
};
}
} else {
# we should also consider $ENV{PERL5LIB} here
my $old = $self->{PERL_LIB} || $self->{PERL_ARCHLIB} || $self->{PERL_INC};
$self->{PERL_LIB} ||= $Config{privlibexp};
$self->{PERL_ARCHLIB} ||= $Config{archlibexp};
$self->{PERL_INC} = $self->catdir("$self->{PERL_ARCHLIB}","CORE"); # wild guess for now
my $perl_h;
if (not -f ($perl_h = $self->catfile($self->{PERL_INC},"perl.h"))
and not $old){
# Maybe somebody tries to build an extension with an
# uninstalled Perl outside of Perl build tree
my $lib;
for my $dir (@INC) {
$lib = $dir, last if -e $self->catfile($dir, "Config.pm");
}
if ($lib) {
# Win32 puts its header files in /perl/src/lib/CORE.
# Unix leaves them in /perl/src.
my $inc = $Is{Win32} ? $self->catdir($lib, "CORE" )
: dirname $lib;
if (-e $self->catfile($inc, "perl.h")) {
$self->{PERL_LIB} = $lib;
$self->{PERL_ARCHLIB} = $lib;
$self->{PERL_INC} = $inc;
$self->{UNINSTALLED_PERL} = 1;
print <<EOP;
... Detected uninstalled Perl. Trying to continue.
EOP
}
}
}
}
if ($Is{Android}) {
# Android fun times!
# ../../perl -I../../lib -MFile::Glob -e1 works
# ../../../perl -I../../../lib -MFile::Glob -e1 fails to find
# the .so for File::Glob.
# This always affects core perl, but may also affect an installed
# perl built with -Duserelocatableinc.
$self->{PERL_LIB} = File::Spec->rel2abs($self->{PERL_LIB});
$self->{PERL_ARCHLIB} = File::Spec->rel2abs($self->{PERL_ARCHLIB});
}
$self->{PERL_INCDEP} = $self->{PERL_INC};
$self->{PERL_ARCHLIBDEP} = $self->{PERL_ARCHLIB};
# We get SITELIBEXP and SITEARCHEXP directly via
# Get_from_Config. When we are running standard modules, these
# won't matter, we will set INSTALLDIRS to "perl". Otherwise we
# set it to "site". I prefer that INSTALLDIRS be set from outside
# MakeMaker.
$self->{INSTALLDIRS} ||= "site";
$self->{MAN1EXT} ||= $Config{man1ext};
$self->{MAN3EXT} ||= $Config{man3ext};
# Get some stuff out of %Config if we haven't yet done so
print "CONFIG must be an array ref\n"
if ($self->{CONFIG} and ref $self->{CONFIG} ne 'ARRAY');
$self->{CONFIG} = [] unless (ref $self->{CONFIG});
push(@{$self->{CONFIG}}, @ExtUtils::MakeMaker::Get_from_Config);
push(@{$self->{CONFIG}}, 'shellflags') if $Config{shellflags};
my(%once_only);
foreach my $m (@{$self->{CONFIG}}){
next if $once_only{$m};
print "CONFIG key '$m' does not exist in Config.pm\n"
unless exists $Config{$m};
$self->{uc $m} ||= $Config{$m};
$once_only{$m} = 1;
}
# This is too dangerous:
# if ($^O eq "next") {
# $self->{AR} = "libtool";
# $self->{AR_STATIC_ARGS} = "-o";
# }
# But I leave it as a placeholder
$self->{AR_STATIC_ARGS} = $Config{arflags};
$self->{AR_STATIC_ARGS} ||= 'cr';
# These should never be needed
$self->{OBJ_EXT} ||= '.o';
$self->{LIB_EXT} ||= '.a';
$self->{MAP_TARGET} ||= "perl";
$self->{LIBPERL_A} ||= "libperl$self->{LIB_EXT}";
# make a simple check if we find strict
warn "Warning: PERL_LIB ($self->{PERL_LIB}) seems not to be a perl library directory
(strict.pm not found)"
unless -f $self->catfile("$self->{PERL_LIB}","strict.pm") ||
$self->{NAME} eq "ExtUtils::MakeMaker";
}
=item init_tools
Initializes tools to use their common (and faster) Unix commands.
=cut
sub init_tools {
my $self = shift;
$self->{ECHO} ||= 'echo';
$self->{ECHO_N} ||= 'echo -n';
$self->{RM_F} ||= "rm -f";
$self->{RM_RF} ||= "rm -rf";
$self->{TOUCH} ||= "touch";
$self->{TEST_F} ||= "test -f";
$self->{TEST_S} ||= "test -s";
$self->{CP} ||= "cp";
$self->{MV} ||= "mv";
$self->{CHMOD} ||= "chmod";
$self->{FALSE} ||= 'false';
$self->{TRUE} ||= 'true';
$self->{LD} ||= 'ld';
return $self->SUPER::init_tools(@_);
# After SUPER::init_tools so $Config{shell} has a
# chance to get set.
$self->{SHELL} ||= '/bin/sh';
return;
}
=item init_linker
Unix has no need of special linker flags.
=cut
sub init_linker {
my($self) = shift;
$self->{PERL_ARCHIVE} ||= '';
$self->{PERL_ARCHIVEDEP} ||= '';
$self->{PERL_ARCHIVE_AFTER} ||= '';
$self->{EXPORT_LIST} ||= '';
}
=begin _protected
=item init_lib2arch
$mm->init_lib2arch
=end _protected
=cut
sub init_lib2arch {
my($self) = shift;
# The user who requests an installation directory explicitly
# should not have to tell us an architecture installation directory
# as well. We look if a directory exists that is named after the
# architecture. If not we take it as a sign that it should be the
# same as the requested installation directory. Otherwise we take
# the found one.
for my $libpair ({l=>"privlib", a=>"archlib"},
{l=>"sitelib", a=>"sitearch"},
{l=>"vendorlib", a=>"vendorarch"},
)
{
my $lib = "install$libpair->{l}";
my $Lib = uc $lib;
my $Arch = uc "install$libpair->{a}";
if( $self->{$Lib} && ! $self->{$Arch} ){
my($ilib) = $Config{$lib};
$self->prefixify($Arch,$ilib,$self->{$Lib});
unless (-d $self->{$Arch}) {
print "Directory $self->{$Arch} not found\n"
if $Verbose;
$self->{$Arch} = $self->{$Lib};
}
print "Defaulting $Arch to $self->{$Arch}\n" if $Verbose;
}
}
}
=item init_PERL
$mm->init_PERL;
Called by init_main. Sets up ABSPERL, PERL, FULLPERL and all the
*PERLRUN* permutations.
PERL is allowed to be miniperl
FULLPERL must be a complete perl
ABSPERL is PERL converted to an absolute path
*PERLRUN contains everything necessary to run perl, find it's
libraries, etc...
*PERLRUNINST is *PERLRUN + everything necessary to find the
modules being built.
=cut
sub init_PERL {
my($self) = shift;
my @defpath = ();
foreach my $component ($self->{PERL_SRC}, $self->path(),
$Config{binexp})
{
push @defpath, $component if defined $component;
}
# Build up a set of file names (not command names).
my $thisperl = $self->canonpath($^X);
$thisperl .= $Config{exe_ext} unless
# VMS might have a file version # at the end
$Is{VMS} ? $thisperl =~ m/$Config{exe_ext}(;\d+)?$/i
: $thisperl =~ m/$Config{exe_ext}$/i;
# We need a relative path to perl when in the core.
$thisperl = $self->abs2rel($thisperl) if $self->{PERL_CORE};
my @perls = ($thisperl);
push @perls, map { "$_$Config{exe_ext}" }
("perl$Config{version}", 'perl5', 'perl');
# miniperl has priority over all but the canonical perl when in the
# core. Otherwise its a last resort.
my $miniperl = "miniperl$Config{exe_ext}";
if( $self->{PERL_CORE} ) {
splice @perls, 1, 0, $miniperl;
}
else {
push @perls, $miniperl;
}
$self->{PERL} ||=
$self->find_perl(5.0, \@perls, \@defpath, $Verbose );
my $perl = $self->{PERL};
$perl =~ s/^"//;
my $has_mcr = $perl =~ s/^MCR\s*//;
my $perlflags = '';
my $stripped_perl;
while ($perl) {
($stripped_perl = $perl) =~ s/"$//;
last if -x $stripped_perl;
last unless $perl =~ s/(\s+\S+)$//;
$perlflags = $1.$perlflags;
}
$self->{PERL} = $stripped_perl;
$self->{PERL} = 'MCR '.$self->{PERL} if $has_mcr || $Is{VMS};
# When built for debugging, VMS doesn't create perl.exe but ndbgperl.exe.
my $perl_name = 'perl';
$perl_name = 'ndbgperl' if $Is{VMS} &&
defined $Config{usevmsdebug} && $Config{usevmsdebug} eq 'define';
$perl_name = 'cperl' if $Is{Win32} && $^V =~ /c$/;
# XXX This logic is flawed. If "miniperl" is anywhere in the path
# it will get confused. It should be fixed to work only on the filename.
# Define 'FULLPERL' to be a non-miniperl (used in test: target)
unless ($self->{FULLPERL}) {
($self->{FULLPERL} = $self->{PERL}) =~ s/\Q$miniperl\E$/$perl_name$Config{exe_ext}/i;
$self->{FULLPERL} = qq{"$self->{FULLPERL}"}.$perlflags;
}
# Can't have an image name with quotes, and findperl will have
# already escaped spaces.
$self->{FULLPERL} =~ tr/"//d if $Is{VMS};
# Little hack to get around VMS's find_perl putting "MCR" in front
# sometimes.
$self->{ABSPERL} = $self->{PERL};
$has_mcr = $self->{ABSPERL} =~ s/^MCR\s*//;
if( $self->file_name_is_absolute($self->{ABSPERL}) ) {
$self->{ABSPERL} = '$(PERL)';
}
else {
$self->{ABSPERL} = $self->rel2abs($self->{ABSPERL});
# Quote the perl command if it contains whitespace
$self->{ABSPERL} = $self->quote_literal($self->{ABSPERL})
if $self->{ABSPERL} =~ /\s/;
$self->{ABSPERL} = 'MCR '.$self->{ABSPERL} if $has_mcr;
}
$self->{PERL} = qq{"$self->{PERL}"}.$perlflags;
# Can't have an image name with quotes, and findperl will have
# already escaped spaces.
$self->{PERL} =~ tr/"//d if $Is{VMS};
# Are we building the core?
$self->{PERL_CORE} = $ENV{PERL_CORE} unless exists $self->{PERL_CORE};
$self->{PERL_CORE} = 0 unless defined $self->{PERL_CORE};
# Make sure perl can find itself before it's installed.
my $lib_paths = $self->{UNINSTALLED_PERL} || $self->{PERL_CORE}
? ( $self->{PERL_ARCHLIB} && $self->{PERL_LIB} && $self->{PERL_ARCHLIB} ne $self->{PERL_LIB} ) ?
q{ "-I$(PERL_LIB)" "-I$(PERL_ARCHLIB)"} : q{ "-I$(PERL_LIB)"}
: undef;
my $inst_lib_paths = $self->{INST_ARCHLIB} ne $self->{INST_LIB}
? 'RUN)'.$perlflags.' "-I$(INST_ARCHLIB)" "-I$(INST_LIB)"'
: 'RUN)'.$perlflags.' "-I$(INST_LIB)"';
# How do we run perl?
foreach my $perl (qw(PERL FULLPERL ABSPERL)) {
my $run = $perl.'RUN';
$self->{$run} = qq{\$($perl)};
$self->{$run} .= $lib_paths if $lib_paths;
$self->{$perl.'RUNINST'} = '$('.$perl.$inst_lib_paths;
}
return 1;
}
=item init_platform
=item platform_constants
Add MM_Unix_VERSION.
=cut
sub init_platform {
my($self) = shift;
$self->{MM_Unix_VERSION} = $VERSION;
$self->{PERL_MALLOC_DEF} = '-DPERL_EXTMALLOC_DEF -Dmalloc=Perl_malloc '.
'-Dfree=Perl_mfree -Drealloc=Perl_realloc '.
'-Dcalloc=Perl_calloc';
}
sub platform_constants {
my($self) = shift;
my $make_frag = '';
foreach my $macro (qw(MM_Unix_VERSION PERL_MALLOC_DEF))
{
next unless defined $self->{$macro};
$make_frag .= "$macro = $self->{$macro}\n";
}
return $make_frag;
}
=item init_PERM
$mm->init_PERM
Called by init_main. Initializes PERL_*
=cut
sub init_PERM {
my($self) = shift;
$self->{PERM_DIR} = 755 unless defined $self->{PERM_DIR};
$self->{PERM_RW} = 644 unless defined $self->{PERM_RW};
$self->{PERM_RWX} = 755 unless defined $self->{PERM_RWX};
return 1;
}
=item init_xs
$mm->init_xs
Sets up macros having to do with XS code. Currently just INST_STATIC,
INST_DYNAMIC and INST_BOOT.
=cut
sub init_xs {
my $self = shift;
if ($self->has_link_code()) {
$self->{INST_STATIC} =
$self->catfile('$(INST_ARCHAUTODIR)', '$(BASEEXT)$(LIB_EXT)');
$self->{INST_DYNAMIC} =
$self->catfile('$(INST_ARCHAUTODIR)', '$(DLBASE).$(DLEXT)');
$self->{INST_BOOT} =
$self->catfile('$(INST_ARCHAUTODIR)', '$(BASEEXT).bs');
if ($self->{XSMULTI}) {
my @exts = $self->_xs_list_basenames;
my (@statics, @dynamics, @boots);
for my $ext (@exts) {
my ($v, $d, $f) = File::Spec->splitpath($ext);
my @d = File::Spec->splitdir($d);
shift @d if defined $d[0] and $d[0] eq 'lib';
my $instdir = $self->catdir('$(INST_ARCHLIB)', 'auto', @d, $f);
my $instfile = $self->catfile($instdir, $f);
push @statics, "$instfile\$(LIB_EXT)";
# Dynamic library names may need special handling.
my $dynfile = $instfile;
eval { require DynaLoader };
if (defined &DynaLoader::mod2fname) {
$dynfile = $self->catfile($instdir, &DynaLoader::mod2fname([@d, $f]));
}
push @dynamics, "$dynfile.\$(DLEXT)";
push @boots, "$instfile.bs";
}
$self->{INST_STATIC} = join ' ', @statics;
$self->{INST_DYNAMIC} = join ' ', @dynamics;
$self->{INST_BOOT} = join ' ', @boots;
}
} else {
$self->{INST_STATIC} = '';
$self->{INST_DYNAMIC} = '';
$self->{INST_BOOT} = '';
}
}
=item install (o)
Defines the install target.
=cut
sub install {
my($self, %attribs) = @_;
my(@m);
push @m, q{
install :: pure_install doc_install
$(NOECHO) $(NOOP)
install_perl :: pure_perl_install doc_perl_install
$(NOECHO) $(NOOP)
install_site :: pure_site_install doc_site_install
$(NOECHO) $(NOOP)
install_vendor :: pure_vendor_install doc_vendor_install
$(NOECHO) $(NOOP)
pure_install :: pure_$(INSTALLDIRS)_install
$(NOECHO) $(NOOP)
doc_install :: doc_$(INSTALLDIRS)_install
$(NOECHO) $(NOOP)
pure__install : pure_site_install
$(NOECHO) $(ECHO) INSTALLDIRS not defined, defaulting to INSTALLDIRS=site
doc__install : doc_site_install
$(NOECHO) $(ECHO) INSTALLDIRS not defined, defaulting to INSTALLDIRS=site
pure_perl_install :: all
$(NOECHO) $(MOD_INSTALL) \
};
push @m,
q{ read "}.$self->catfile('$(PERL_ARCHLIB)','auto','$(FULLEXT)','.packlist').q{" \
write "}.$self->catfile('$(DESTINSTALLARCHLIB)','auto','$(FULLEXT)','.packlist').q{" \
} unless $self->{NO_PACKLIST};
push @m,
q{ "$(INST_LIB)" "$(DESTINSTALLPRIVLIB)" \
"$(INST_ARCHLIB)" "$(DESTINSTALLARCHLIB)" \
"$(INST_BIN)" "$(DESTINSTALLBIN)" \
"$(INST_SCRIPT)" "$(DESTINSTALLSCRIPT)" \
"$(INST_MAN1DIR)" "$(DESTINSTALLMAN1DIR)" \
"$(INST_MAN3DIR)" "$(DESTINSTALLMAN3DIR)"
$(NOECHO) $(WARN_IF_OLD_PACKLIST) \
"}.$self->catdir('$(SITEARCHEXP)','auto','$(FULLEXT)').q{"
pure_site_install :: all
$(NOECHO) $(MOD_INSTALL) \
};
push @m,
q{ read "}.$self->catfile('$(SITEARCHEXP)','auto','$(FULLEXT)','.packlist').q{" \
write "}.$self->catfile('$(DESTINSTALLSITEARCH)','auto','$(FULLEXT)','.packlist').q{" \
} unless $self->{NO_PACKLIST};
push @m,
q{ "$(INST_LIB)" "$(DESTINSTALLSITELIB)" \
"$(INST_ARCHLIB)" "$(DESTINSTALLSITEARCH)" \
"$(INST_BIN)" "$(DESTINSTALLSITEBIN)" \
"$(INST_SCRIPT)" "$(DESTINSTALLSITESCRIPT)" \
"$(INST_MAN1DIR)" "$(DESTINSTALLSITEMAN1DIR)" \
"$(INST_MAN3DIR)" "$(DESTINSTALLSITEMAN3DIR)"
$(NOECHO) $(WARN_IF_OLD_PACKLIST) \
"}.$self->catdir('$(PERL_ARCHLIB)','auto','$(FULLEXT)').q{"
pure_vendor_install :: all
$(NOECHO) $(MOD_INSTALL) \
};
push @m,
q{ read "}.$self->catfile('$(VENDORARCHEXP)','auto','$(FULLEXT)','.packlist').q{" \
write "}.$self->catfile('$(DESTINSTALLVENDORARCH)','auto','$(FULLEXT)','.packlist').q{" \
} unless $self->{NO_PACKLIST};
push @m,
q{ "$(INST_LIB)" "$(DESTINSTALLVENDORLIB)" \
"$(INST_ARCHLIB)" "$(DESTINSTALLVENDORARCH)" \
"$(INST_BIN)" "$(DESTINSTALLVENDORBIN)" \
"$(INST_SCRIPT)" "$(DESTINSTALLVENDORSCRIPT)" \
"$(INST_MAN1DIR)" "$(DESTINSTALLVENDORMAN1DIR)" \
"$(INST_MAN3DIR)" "$(DESTINSTALLVENDORMAN3DIR)"
};
push @m, q{
doc_perl_install :: all
$(NOECHO) $(NOOP)
doc_site_install :: all
$(NOECHO) $(NOOP)
doc_vendor_install :: all
$(NOECHO) $(NOOP)
} if $self->{NO_PERLLOCAL};
push @m, q{
doc_perl_install :: all
$(NOECHO) $(ECHO) Appending installation info to "$(DESTINSTALLARCHLIB)/perllocal.pod"
-$(NOECHO) $(MKPATH) "$(DESTINSTALLARCHLIB)"
-$(NOECHO) $(DOC_INSTALL) \
"Module" "$(NAME)" \
"installed into" "$(INSTALLPRIVLIB)" \
LINKTYPE "$(LINKTYPE)" \
VERSION "$(VERSION)" \
EXE_FILES "$(EXE_FILES)" \
>> "}.$self->catfile('$(DESTINSTALLARCHLIB)','perllocal.pod').q{"
doc_site_install :: all
$(NOECHO) $(ECHO) Appending installation info to "$(DESTINSTALLARCHLIB)/perllocal.pod"
-$(NOECHO) $(MKPATH) "$(DESTINSTALLARCHLIB)"
-$(NOECHO) $(DOC_INSTALL) \
"Module" "$(NAME)" \
"installed into" "$(INSTALLSITELIB)" \
LINKTYPE "$(LINKTYPE)" \
VERSION "$(VERSION)" \
EXE_FILES "$(EXE_FILES)" \
>> "}.$self->catfile('$(DESTINSTALLARCHLIB)','perllocal.pod').q{"
doc_vendor_install :: all
$(NOECHO) $(ECHO) Appending installation info to "$(DESTINSTALLARCHLIB)/perllocal.pod"
-$(NOECHO) $(MKPATH) "$(DESTINSTALLARCHLIB)"
-$(NOECHO) $(DOC_INSTALL) \
"Module" "$(NAME)" \
"installed into" "$(INSTALLVENDORLIB)" \
LINKTYPE "$(LINKTYPE)" \
VERSION "$(VERSION)" \
EXE_FILES "$(EXE_FILES)" \
>> "}.$self->catfile('$(DESTINSTALLARCHLIB)','perllocal.pod').q{"
} unless $self->{NO_PERLLOCAL};
push @m, q{
uninstall :: uninstall_from_$(INSTALLDIRS)dirs
$(NOECHO) $(NOOP)
uninstall_from_perldirs ::
$(NOECHO) $(UNINSTALL) "}.$self->catfile('$(PERL_ARCHLIB)','auto','$(FULLEXT)','.packlist').q{"
uninstall_from_sitedirs ::
$(NOECHO) $(UNINSTALL) "}.$self->catfile('$(SITEARCHEXP)','auto','$(FULLEXT)','.packlist').q{"
uninstall_from_vendordirs ::
$(NOECHO) $(UNINSTALL) "}.$self->catfile('$(VENDORARCHEXP)','auto','$(FULLEXT)','.packlist').q{"
};
join("",@m);
}
=item installbin (o)
Defines targets to make and to install EXE_FILES.
=cut
sub installbin {
my($self) = shift;
return "" unless $self->{EXE_FILES} && ref $self->{EXE_FILES} eq "ARRAY";
my @exefiles = sort @{$self->{EXE_FILES}};
return "" unless @exefiles;
@exefiles = map vmsify($_), @exefiles if $Is{VMS};
my %fromto;
for my $from (@exefiles) {
my($path)= $self->catfile('$(INST_SCRIPT)', basename($from));
local($_) = $path; # for backwards compatibility
my $to = $self->libscan($path);
print "libscan($from) => '$to'\n" if ($Verbose >=2);
$to = vmsify($to) if $Is{VMS};
$fromto{$from} = $to;
}
my @to = sort values %fromto;
my @m;
push(@m, qq{
EXE_FILES = @exefiles
pure_all :: @to
\$(NOECHO) \$(NOOP)
realclean ::
});
# realclean can get rather large.
push @m, map "\t$_\n", $self->split_command('$(RM_F)', @to);
push @m, "\n";
# A target for each exe file.
my @froms = sort keys %fromto;
for my $from (@froms) {
# 1 2
push @m, _sprintf562 <<'MAKE', $from, $fromto{$from};
%2$s : %1$s $(FIRST_MAKEFILE) $(INST_SCRIPT)$(DFSEP).exists $(INST_BIN)$(DFSEP).exists
$(NOECHO) $(RM_F) %2$s
$(CP) %1$s %2$s
$(FIXIN) %2$s
-$(NOECHO) $(CHMOD) $(PERM_RWX) %2$s
MAKE
}
join "", @m;
}
=item linkext (o)
Defines the linkext target which in turn defines the LINKTYPE.
=cut
# LINKTYPE => static or dynamic or ''
sub linkext {
my($self, %attribs) = @_;
my $linktype = $attribs{LINKTYPE};
$linktype = $self->{LINKTYPE} unless defined $linktype;
if (defined $linktype and $linktype eq '') {
warn "Warning: LINKTYPE set to '', no longer necessary\n";
}
$linktype = '$(LINKTYPE)' unless defined $linktype;
"
linkext :: $linktype
\$(NOECHO) \$(NOOP)
";
}
=item lsdir
Takes as arguments a directory name and a regular expression. Returns
all entries in the directory that match the regular expression.
=cut
sub lsdir {
# $self
my(undef, $dir, $regex) = @_;
opendir(my $dh, defined($dir) ? $dir : ".")
or return;
my @ls = readdir $dh;
closedir $dh;
@ls = grep(/$regex/, @ls) if defined $regex;
@ls;
}
=item macro (o)
Simple subroutine to insert the macros defined by the macro attribute
into the Makefile.
=cut
sub macro {
my($self,%attribs) = @_;
my @m;
foreach my $key (sort keys %attribs) {
my $val = $attribs{$key};
push @m, "$key = $val\n";
}
join "", @m;
}
=item makeaperl (o)
Called by staticmake. Defines how to write the Makefile to produce a
static new perl.
By default the Makefile produced includes all the static extensions in
the perl library. (Purified versions of library files, e.g.,
DynaLoader_pure_p1_c0_032.a are automatically ignored to avoid link errors.)
=cut
sub makeaperl {
my($self, %attribs) = @_;
my($makefilename, $searchdirs, $static, $extra, $perlinc, $target, $tmp, $libperl) =
@attribs{qw(MAKE DIRS STAT EXTRA INCL TARGET TMP LIBPERL)};
s/^(.*)/"-I$1"/ for @{$perlinc || []};
my(@m);
push @m, "
# --- MakeMaker makeaperl section ---
MAP_TARGET = $target
FULLPERL = $self->{FULLPERL}
MAP_PERLINC = @{$perlinc || []}
";
return join '', @m if $self->{PARENT};
my($dir) = join ":", @{$self->{DIR}};
unless ($self->{MAKEAPERL}) {
push @m, q{
$(MAP_TARGET) :: $(MAKE_APERL_FILE)
$(MAKE) $(USEMAKEFILE) $(MAKE_APERL_FILE) $@
$(MAKE_APERL_FILE) : static $(FIRST_MAKEFILE) pm_to_blib
$(NOECHO) $(ECHO) Writing \"$(MAKE_APERL_FILE)\" for this $(MAP_TARGET)
$(NOECHO) $(PERLRUNINST) \
Makefile.PL DIR="}, $dir, q{" \
MAKEFILE=$(MAKE_APERL_FILE) LINKTYPE=static \
MAKEAPERL=1 NORECURS=1 CCCDLFLAGS=};
foreach (@ARGV){
my $arg = $_; # avoid lvalue aliasing
if ( $arg =~ /(^.*?=)(.*['\s].*)/ ) {
$arg = $1 . $self->quote_literal($2);
}
push @m, " \\\n\t\t$arg";
}
push @m, "\n";
return join '', @m;
}
my $cccmd = $self->const_cccmd($libperl);
$cccmd =~ s/^CCCMD\s*=\s*//;
$cccmd =~ s/\$\(INC\)/ "-I$self->{PERL_INC}" /;
$cccmd .= " $Config{cccdlflags}"
if ($Config{useshrplib} eq 'true');
$cccmd =~ s/\(CC\)/\(PERLMAINCC\)/;
# The front matter of the linkcommand...
my $linkcmd = join ' ', "\$(CC)",
grep($_, @Config{qw(ldflags ccdlflags)});
$linkcmd =~ s/\s+/ /g;
$linkcmd =~ s,(perl\.exp),\$(PERL_INC)/$1,;
# Which *.a files could we make use of...
my $staticlib21 = $self->_find_static_libs($searchdirs);
# We trust that what has been handed in as argument, will be buildable
$static = [] unless $static;
@$staticlib21{@{$static}} = (1) x @{$static};
$extra = [] unless $extra && ref $extra eq 'ARRAY';
for (sort keys %$staticlib21) {
next unless /\Q$self->{LIB_EXT}\E\z/;
$_ = dirname($_) . "/extralibs.ld";
push @$extra, $_;
}
s/^(.*)/"-I$1"/ for @{$perlinc || []};
$target ||= "perl";
$tmp ||= ".";
# MAP_STATIC doesn't look into subdirs yet. Once "all" is made and we
# regenerate the Makefiles, MAP_STATIC and the dependencies for
# extralibs.all are computed correctly
my @map_static = reverse sort keys %$staticlib21;
push @m, "
MAP_LINKCMD = $linkcmd
MAP_STATIC = ", join(" \\\n\t", map { qq{"$_"} } @map_static), "
MAP_STATICDEP = ", join(' ', map { $self->quote_dep($_) } @map_static), "
MAP_PRELIBS = $Config{perllibs} $Config{cryptlib}
";
my $lperl;
if (defined $libperl) {
($lperl = $libperl) =~ s/\$\(A\)/$self->{LIB_EXT}/;
}
unless ($libperl && -f $lperl) { # Ilya's code...
my $dir = $self->{PERL_SRC} || "$self->{PERL_ARCHLIB}/CORE";
$dir = "$self->{PERL_ARCHLIB}/.." if $self->{UNINSTALLED_PERL};
$libperl ||= "libperl$self->{LIB_EXT}";
$libperl = "$dir/$libperl";
$lperl ||= "libperl$self->{LIB_EXT}";
$lperl = "$dir/$lperl";
if (! -f $libperl and ! -f $lperl) {
# We did not find a static libperl. Maybe there is a shared one?
if ($Is{SunOS}) {
$lperl = $libperl = "$dir/$Config{libperl}";
# SUNOS ld does not take the full path to a shared library
$libperl = '' if $Is{SunOS4};
}
}
print <<EOF unless -f $lperl || defined($self->{PERL_SRC});
Warning: $libperl not found
If you're going to build a static perl binary, make sure perl is installed
otherwise ignore this warning
EOF
}
# SUNOS ld does not take the full path to a shared library
my $llibperl = $libperl ? '$(MAP_LIBPERL)' : '-lperl';
my $libperl_dep = $self->quote_dep($libperl);
push @m, "
MAP_LIBPERL = $libperl
MAP_LIBPERLDEP = $libperl_dep
LLIBPERL = $llibperl
";
push @m, '
$(INST_ARCHAUTODIR)/extralibs.all : $(INST_ARCHAUTODIR)$(DFSEP).exists '.join(" \\\n\t", @$extra).'
$(NOECHO) $(RM_F) $@
$(NOECHO) $(TOUCH) $@
';
foreach my $catfile (@$extra){
push @m, "\tcat $catfile >> \$\@\n";
}
# without XSMULTI leads to duplicate objects: one direct and one via the MAP_STATIC
my $ldfrom = ''; # $self->{XSMULTI} ? '' : '$(LDFROM)';
# 1 2 3 4
push @m, _sprintf562 <<'EOF', $tmp, $ldfrom, $self->xs_obj_opt('$@'), $makefilename;
$(MAP_TARGET) :: %1$s/perlmain$(OBJ_EXT) $(MAP_LIBPERLDEP) $(MAP_STATICDEP) $(INST_ARCHAUTODIR)/extralibs.all
$(MAP_LINKCMD) %2$s $(OPTIMIZE) %1$s/perlmain$(OBJ_EXT) %3$s $(MAP_STATIC) "$(LLIBPERL)" `cat $(INST_ARCHAUTODIR)/extralibs.all` $(MAP_PRELIBS)
$(NOECHO) $(ECHO) "To install the new '$(MAP_TARGET)' binary, call"
$(NOECHO) $(ECHO) " $(MAKE) $(USEMAKEFILE) %4$s inst_perl MAP_TARGET=$(MAP_TARGET)"
$(NOECHO) $(ECHO) " $(MAKE) $(USEMAKEFILE) %4$s map_clean"
%1$s/perlmain\$(OBJ_EXT): %1$s/perlmain.c
EOF
push @m, "\t".$self->cd($tmp, qq[$cccmd "-I\$(PERL_INC)" perlmain.c])."\n";
my $maybe_DynaLoader = $Config{usedl} ? 'q(DynaLoader)' : '';
push @m, _sprintf562 <<'EOF', $tmp, $makefilename, $maybe_DynaLoader;
%1$s/perlmain.c: %2$s
$(NOECHO) $(ECHO) Writing $@
$(NOECHO) $(PERL) $(MAP_PERLINC) "-MExtUtils::Miniperl" \
-e "writemain(grep(s#.*/auto/##s, @ARGV), %3$s)" $(MAP_STATIC) > $@t
$(MV) $@t $@
EOF
push @m, "\t", q{$(NOECHO) $(PERL) "$(INSTALLSCRIPT)/fixpmain"
} if (defined (&Dos::UseLFN) && Dos::UseLFN()==0);
push @m, q{
doc_inst_perl :
$(NOECHO) $(ECHO) Appending installation info to "$(DESTINSTALLARCHLIB)/perllocal.pod"
-$(NOECHO) $(MKPATH) "$(DESTINSTALLARCHLIB)"
-$(NOECHO) $(DOC_INSTALL) \
"Perl binary" "$(MAP_TARGET)" \
MAP_STATIC "$(MAP_STATIC)" \
MAP_EXTRA "`cat $(INST_ARCHAUTODIR)/extralibs.all`" \
MAP_LIBPERL "$(MAP_LIBPERL)" \
>> "}.$self->catfile('$(DESTINSTALLARCHLIB)','perllocal.pod').q{"
};
push @m, q{
inst_perl : pure_inst_perl doc_inst_perl
pure_inst_perl : $(MAP_TARGET)
}.$self->{CP}.q{ $(MAP_TARGET) "}.$self->catfile('$(DESTINSTALLBIN)','$(MAP_TARGET)').q{"
clean :: map_clean
map_clean :
}.$self->{RM_F}.qq{ $tmp/perlmain\$(OBJ_EXT) $tmp/perlmain.c \$(MAP_TARGET) $makefilename \$(INST_ARCHAUTODIR)/extralibs.all
};
join '', @m;
}
# utility method
sub _find_static_libs {
my ($self, $searchdirs) = @_;
# don't use File::Spec here because on Win32 F::F still uses "/"
my $installed_version = join('/',
'auto', $self->{FULLEXT}, "$self->{BASEEXT}$self->{LIB_EXT}"
);
my %staticlib21;
require File::Find;
File::Find::find(sub {
if ($File::Find::name =~ m{/auto/share\z}) {
# in a subdir of auto/share, prune because e.g.
# Alien::pkgconfig uses File::ShareDir to put .a files
# there. do not want
$File::Find::prune = 1;
return;
}
return unless m/\Q$self->{LIB_EXT}\E$/;
return unless -f 'extralibs.ld'; # this checks is a "proper" XS installation
# Skip perl's libraries.
return if m/^libperl/ or m/^perl\Q$self->{LIB_EXT}\E$/;
# Skip purified versions of libraries
# (e.g., DynaLoader_pure_p1_c0_032.a)
return if m/_pure_\w+_\w+_\w+\.\w+$/ and -f "$File::Find::dir/.pure";
if( exists $self->{INCLUDE_EXT} ){
my $found = 0;
(my $xx = $File::Find::name) =~ s,.*?/auto/,,s;
$xx =~ s,/?$_,,;
$xx =~ s,/,::,g;
# Throw away anything not explicitly marked for inclusion.
# DynaLoader is implied.
foreach my $incl ((@{$self->{INCLUDE_EXT}},'DynaLoader')){
if( $xx eq $incl ){
$found++;
last;
}
}
return unless $found;
}
elsif( exists $self->{EXCLUDE_EXT} ){
(my $xx = $File::Find::name) =~ s,.*?/auto/,,s;
$xx =~ s,/?$_,,;
$xx =~ s,/,::,g;
# Throw away anything explicitly marked for exclusion
foreach my $excl (@{$self->{EXCLUDE_EXT}}){
return if( $xx eq $excl );
}
}
# don't include the installed version of this extension. I
# leave this line here, although it is not necessary anymore:
# I patched minimod.PL instead, so that Miniperl.pm won't
# include duplicates
# Once the patch to minimod.PL is in the distribution, I can
# drop it
return if $File::Find::name =~ m:\Q$installed_version\E\z:;
return if !$self->xs_static_lib_is_xs($_);
use Cwd 'cwd';
$staticlib21{cwd() . "/" . $_}++;
}, grep( -d $_, map { $self->catdir($_, 'auto') } @{$searchdirs || []}) );
return \%staticlib21;
}
=item xs_static_lib_is_xs (o)
Called by a utility method of makeaperl. Checks whether a given file
is an XS library by seeing whether it defines any symbols starting
with C<boot_>.
=cut
sub xs_static_lib_is_xs {
my ($self, $libfile) = @_;
my $devnull = File::Spec->devnull;
return `nm $libfile 2>$devnull` =~ /\bboot_/;
}
=item makefile (o)
Defines how to rewrite the Makefile.
=cut
sub makefile {
my($self) = shift;
my $m;
# We do not know what target was originally specified so we
# must force a manual rerun to be sure. But as it should only
# happen very rarely it is not a significant problem.
$m = '
$(OBJECT) : $(FIRST_MAKEFILE)
' if $self->{OBJECT};
my $newer_than_target = $Is{VMS} ? '$(MMS$SOURCE_LIST)' : '$?';
my $mpl_args = join " ", map qq["$_"], @ARGV;
my $cross = '';
if (defined $::Cross::platform) {
# Inherited from win32/buildext.pl
$cross = "-MCross=$::Cross::platform ";
}
$m .= sprintf <<'MAKE_FRAG', $newer_than_target, $cross, $mpl_args;
# We take a very conservative approach here, but it's worth it.
# We move Makefile to Makefile.old here to avoid gnu make looping.
$(FIRST_MAKEFILE) : Makefile.PL $(CONFIGDEP)
$(NOECHO) $(ECHO) "Makefile out-of-date with respect to %s"
$(NOECHO) $(ECHO) "Cleaning current config before rebuilding Makefile..."
-$(NOECHO) $(RM_F) $(MAKEFILE_OLD)
-$(NOECHO) $(MV) $(FIRST_MAKEFILE) $(MAKEFILE_OLD)
- $(MAKE) $(USEMAKEFILE) $(MAKEFILE_OLD) clean $(DEV_NULL)
$(PERLRUN) %sMakefile.PL %s
$(NOECHO) $(ECHO) "==> Your Makefile has been rebuilt. <=="
$(NOECHO) $(ECHO) "==> Please rerun the $(MAKE) command. <=="
$(FALSE)
MAKE_FRAG
return $m;
}
=item maybe_command
Returns true, if the argument is likely to be a command.
=cut
sub maybe_command {
my($self,$file) = @_;
return $file if -x $file && ! -d $file;
return;
}
=item needs_linking (o)
Does this module need linking? Looks into subdirectory objects (see
also has_link_code())
=cut
sub needs_linking {
my($self) = shift;
my $caller = (caller(0))[3];
confess("needs_linking called too early") if
$caller =~ /^ExtUtils::MakeMaker::/;
return $self->{NEEDS_LINKING} if defined $self->{NEEDS_LINKING};
if ($self->has_link_code or $self->{MAKEAPERL}){
$self->{NEEDS_LINKING} = 1;
return 1;
}
foreach my $child (keys %{$self->{CHILDREN}}) {
if ($self->{CHILDREN}->{$child}->needs_linking) {
$self->{NEEDS_LINKING} = 1;
return 1;
}
}
return $self->{NEEDS_LINKING} = 0;
}
=item parse_abstract
parse a file and return what you think is the ABSTRACT
=cut
sub parse_abstract {
my($self,$parsefile) = @_;
my($result, $fh);
local $/ = "\n";
open($fh, '<', $parsefile) or die "Could not open '$parsefile': $!";
binmode $fh;
my $inpod = 0;
my $pod_encoding;
my $package = $self->{DISTNAME};
$package =~ s/-/::/g;
while (<$fh>) {
$inpod = /^=(?!cut)/ ? 1 : /^=cut/ ? 0 : $inpod;
next if !$inpod;
s#\r*\n\z##; # handle CRLF input
if ( /^=encoding\s*(.*)$/i ) {
$pod_encoding = $1;
}
if ( /^($package(?:\.pm)? \s+ -+ \s+)(.*)/x ) {
$result = $2;
next;
}
next unless $result;
if ( $result && ( /^\s*$/ || /^\=/ ) ) {
last;
}
$result = join ' ', $result, $_;
}
close $fh;
if ( $pod_encoding and !( $] < 5.008 or !$Config{useperlio} ) ) {
# Have to wrap in an eval{} for when running under PERL_CORE
# Encode isn't available during build phase and parsing
# ABSTRACT isn't important there
eval {
require Encode;
$result = Encode::decode($pod_encoding, $result);
}
}
return $result;
}
=item parse_version
my $version = MM->parse_version($file);
Parse a $file and return what $VERSION is set to by the first assignment.
It will return the string "undef" if it can't figure out what $VERSION
is. $VERSION should be for all to see, so C<our $VERSION> or plain $VERSION
are okay, but C<my $VERSION> is not.
C<package Foo VERSION> is also checked for. The first version
declaration found is used, but this may change as it differs from how
Perl does it.
parse_version() will try to C<use version> before checking for
C<$VERSION> so the following will work.
$VERSION = qv(1.2.3);
=cut
sub parse_version {
my($self,$parsefile) = @_;
my $result;
local $/ = "\n";
local $_;
if (!ref $parsefile and !-e $parsefile and $Config::Config{usecperl}) {
no strict 'refs';
my ($prereq) = $parsefile =~ /\.c:(.*)$/;
my $normal;
$normal = ${$prereq."::VERSION"} if $prereq;
$result = $normal if defined $normal;
$result = "undef" unless defined $result;
return $result;
}
my $fh;
if (!ref $parsefile) { # IO::Scalar is already open
open($fh, '<', $parsefile) or die "Could not open '$parsefile': $!";
} else {
$fh = $parsefile;
}
my $inpod = 0;
while (<$fh>) {
$inpod = /^=(?!cut)/ ? 1 : /^=cut/ ? 0 : $inpod;
next if $inpod || /^\s*#/;
chop;
next if /^\s*(if|unless|elsif)/;
if ( m{^ \s* package \s+ \w[\w\:\']* \s+ (v?[0-9._]+) \s* (;|\{) }x ) {
local $^W = 0;
$result = $1;
}
elsif ( m{(?<!\\) ([\$*]) (([\w\:\']*) \bVERSION)\b .* (?<![<>=!])\=[^=]}x ) {
$result = $self->get_version($parsefile, $1, $2);
}
else {
next;
}
last if defined $result;
}
close $fh;
if ( defined $result && $result !~ /^v?[\d_\.]+c?$/ ) {
require version;
my $normal = eval { version->new( $result ) };
$result = $normal if defined $normal;
}
$result = "undef" unless defined $result;
return $result;
}
sub get_version {
my ($self, $parsefile, $sigil, $name) = @_;
my $line = $_; # from the while() loop in parse_version
{
package ExtUtils::MakeMaker::_version;
undef *version; # in case of unexpected version() sub
eval {
require version;
version::->import;
};
no strict;
local *{$name};
local $^W = 0;
$line = $1 if $line =~ m{^(.+)}s;
eval($line); ## no critic
return ${$name};
}
}
=item pasthru (o)
Defines the string that is passed to recursive make calls in
subdirectories. The variables like C<PASTHRU_DEFINE> are used in each
level, and passed downwards on the command-line with e.g. the value of
that level's DEFINE. Example:
# Level 0 has DEFINE = -Dfunky
# This code will define level 0's PASTHRU=PASTHRU_DEFINE="$(DEFINE)
# $(PASTHRU_DEFINE)"
# Level 0's $(CCCMD) will include macros $(DEFINE) and $(PASTHRU_DEFINE)
# So will level 1's, so when level 1 compiles, it will get right values
# And so ad infinitum
=cut
sub pasthru {
my($self) = shift;
my(@m);
my(@pasthru);
my($sep) = $Is{VMS} ? ',' : '';
$sep .= "\\\n\t";
foreach my $key (qw(LIB LIBPERL_A LINKTYPE OPTIMIZE
PREFIX INSTALL_BASE)
)
{
next unless defined $self->{$key};
push @pasthru, "$key=\"\$($key)\"";
}
foreach my $key (qw(DEFINE INC)) {
# default to the make var
my $val = qq{\$($key)};
# expand within perl if given since need to use quote_literal
# since INC might include space-protecting ""!
chomp($val = $self->{$key}) if defined $self->{$key};
$val .= " \$(PASTHRU_$key)";
my $quoted = $self->quote_literal($val);
push @pasthru, qq{PASTHRU_$key=$quoted};
}
push @m, "\nPASTHRU = ", join ($sep, @pasthru), "\n";
join "", @m;
}
=item perl_script
Takes one argument, a file name, and returns the file name, if the
argument is likely to be a perl script. On MM_Unix this is true for
any ordinary, readable file.
=cut
sub perl_script {
my($self,$file) = @_;
return $file if -r $file && -f _;
return;
}
=item perldepend (o)
Defines the dependency from all *.h files that come with the perl
distribution.
=cut
sub perldepend {
my($self) = shift;
my(@m);
my $configdep = $Config{usecperl} ? 'Config_heavy.pl' : 'Config.pm';
my $make_config = $self->cd('$(PERL_SRC)', '$(MAKE) lib$(DFSEP)' . $configdep);
push @m, sprintf <<'MAKE_FRAG', $configdep, $configdep, $make_config if $self->{PERL_SRC};
# Check for unpropogated config.sh changes. Should never happen.
# We do NOT just update config.h because that is not sufficient.
# An out of date config.h is not fatal but complains loudly!
$(PERL_INCDEP)/config.h: $(PERL_SRC)/config.sh
-$(NOECHO) $(ECHO) "Warning: $(PERL_INC)/config.h out of date with $(PERL_SRC)/config.sh"; $(FALSE)
$(PERL_ARCHLIB)/%s: $(PERL_SRC)/config.sh
$(NOECHO) $(ECHO) "Warning: $(PERL_ARCHLIB)/%s may be out of date with $(PERL_SRC)/config.sh"
%s
MAKE_FRAG
return join "", @m unless $self->needs_linking;
if ($self->{OBJECT}) {
# Need to add an object file dependency on the perl headers.
# this is very important for XS modules in perl.git development.
push @m, $self->_perl_header_files_fragment("/"); # Directory separator between $(PERL_INC)/header.h
}
push @m, join(" ", sort values %{$self->{XS}})." : \$(XSUBPPDEPS)\n" if %{$self->{XS}};
return join "\n", @m;
}
=item pm_to_blib
Defines target that copies all files in the hash PM to their
destination and autosplits them. See L<ExtUtils::Install/DESCRIPTION>
=cut
sub pm_to_blib {
my $self = shift;
my($autodir) = $self->catdir('$(INST_LIB)','auto');
my $r = q{
pm_to_blib : $(FIRST_MAKEFILE) $(TO_INST_PM)
};
# VMS will swallow '' and PM_FILTER is often empty. So use q[]
my $pm_to_blib = $self->oneliner(<<CODE, ['-MExtUtils::Install']);
pm_to_blib({\@ARGV}, '$autodir', q[\$(PM_FILTER)], '\$(PERM_DIR)')
CODE
my @cmds = $self->split_command($pm_to_blib,
map { ($self->quote_literal($_) => $self->quote_literal($self->{PM}->{$_})) } sort keys %{$self->{PM}});
$r .= join '', map { "\t\$(NOECHO) $_\n" } @cmds;
$r .= qq{\t\$(NOECHO) \$(TOUCH) pm_to_blib\n};
return $r;
}
# transform dot-separated version string into comma-separated quadruple
# examples: '1.2.3.4.5' => '1,2,3,4'
# '1.2.3' => '1,2,3,0'
sub _ppd_version {
my ($self, $string) = @_;
return join ',', ((split /\./, $string), (0) x 4)[0..3];
}
=item ppd
Defines target that creates a PPD (Perl Package Description) file
for a binary distribution.
=cut
sub ppd {
my($self) = @_;
my $abstract = $self->{ABSTRACT} || '';
$abstract =~ s/\n/\\n/sg;
$abstract =~ s/</</g;
$abstract =~ s/>/>/g;
my $author = join(', ',@{ ref $self->{AUTHOR} eq 'ARRAY' ? $self->{AUTHOR} : [ $self->{AUTHOR} || '']});
$author =~ s/</</g;
$author =~ s/>/>/g;
my $ppd_file = "$self->{DISTNAME}.ppd";
my @ppd_chunks = qq(<SOFTPKG NAME="$self->{DISTNAME}" VERSION="$self->{VERSION}">\n);
push @ppd_chunks, sprintf <<'PPD_HTML', $abstract, $author;
<ABSTRACT>%s</ABSTRACT>
<AUTHOR>%s</AUTHOR>
PPD_HTML
push @ppd_chunks, " <IMPLEMENTATION>\n";
if ( $self->{MIN_PERL_VERSION} ) {
my $min_perl_version = $self->_ppd_version($self->{MIN_PERL_VERSION});
push @ppd_chunks, sprintf <<'PPD_PERLVERS', $min_perl_version;
<PERLCORE VERSION="%s" />
PPD_PERLVERS
}
# Don't add "perl" to requires. perl dependencies are
# handles by ARCHITECTURE.
my %prereqs = %{$self->{PREREQ_PM}};
delete $prereqs{perl};
# Build up REQUIRE
foreach my $prereq (sort keys %prereqs) {
my $name = $prereq;
$name .= '::' unless $name =~ /::/;
my $version = $prereqs{$prereq};
my %attrs = ( NAME => $name );
$attrs{VERSION} = $version if $version;
my $attrs = join " ", map { qq[$_="$attrs{$_}"] } sort keys %attrs;
push @ppd_chunks, qq( <REQUIRE $attrs />\n);
}
my $archname = $Config{archname};
if ($] >= 5.008) {
# archname did not change from 5.6 to 5.8, but those versions may
# not be not binary compatible so now we append the part of the
# version that changes when binary compatibility may change
$archname .= "-$Config{PERL_REVISION}.$Config{PERL_VERSION}";
}
push @ppd_chunks, sprintf <<'PPD_OUT', $archname;
<ARCHITECTURE NAME="%s" />
PPD_OUT
if ($self->{PPM_INSTALL_SCRIPT}) {
if ($self->{PPM_INSTALL_EXEC}) {
push @ppd_chunks, sprintf qq{ <INSTALL EXEC="%s">%s</INSTALL>\n},
$self->{PPM_INSTALL_EXEC}, $self->{PPM_INSTALL_SCRIPT};
}
else {
push @ppd_chunks, sprintf qq{ <INSTALL>%s</INSTALL>\n},
$self->{PPM_INSTALL_SCRIPT};
}
}
if ($self->{PPM_UNINSTALL_SCRIPT}) {
if ($self->{PPM_UNINSTALL_EXEC}) {
push @ppd_chunks, sprintf qq{ <UNINSTALL EXEC="%s">%s</UNINSTALL>\n},
$self->{PPM_UNINSTALL_EXEC}, $self->{PPM_UNINSTALL_SCRIPT};
}
else {
push @ppd_chunks, sprintf qq{ <UNINSTALL>%s</UNINSTALL>\n},
$self->{PPM_UNINSTALL_SCRIPT};
}
}
my ($bin_location) = $self->{BINARY_LOCATION} || '';
$bin_location =~ s/\\/\\\\/g;
push @ppd_chunks, sprintf <<'PPD_XML', $bin_location;
<CODEBASE HREF="%s" />
</IMPLEMENTATION>
</SOFTPKG>
PPD_XML
my @ppd_cmds = $self->stashmeta(join('', @ppd_chunks), $ppd_file);
return sprintf <<'PPD_OUT', join "\n\t", @ppd_cmds;
# Creates a PPD (Perl Package Description) for a binary distribution.
ppd :
%s
PPD_OUT
}
=item prefixify
$MM->prefixify($var, $prefix, $new_prefix, $default);
Using either $MM->{uc $var} || $Config{lc $var}, it will attempt to
replace it's $prefix with a $new_prefix.
Should the $prefix fail to match I<AND> a PREFIX was given as an
argument to WriteMakefile() it will set it to the $new_prefix +
$default. This is for systems whose file layouts don't neatly fit into
our ideas of prefixes.
This is for heuristics which attempt to create directory structures
that mirror those of the installed perl.
For example:
$MM->prefixify('installman1dir', '/usr', '/home/foo', 'man/man1');
this will attempt to remove '/usr' from the front of the
$MM->{INSTALLMAN1DIR} path (initializing it to $Config{installman1dir}
if necessary) and replace it with '/home/foo'. If this fails it will
simply use '/home/foo/man/man1'.
=cut
sub prefixify {
my($self,$var,$sprefix,$rprefix,$default) = @_;
my $path = $self->{uc $var} ||
$Config_Override{lc $var} || $Config{lc $var} || '';
$rprefix .= '/' if $sprefix =~ m|/$|;
warn " prefixify $var => $path\n" if $Verbose >= 2;
warn " from $sprefix to $rprefix\n" if $Verbose >= 2;
if( $self->{ARGS}{PREFIX} &&
$path !~ s{^\Q$sprefix\E\b}{$rprefix}s )
{
warn " cannot prefix, using default.\n" if $Verbose >= 2;
warn " no default!\n" if !$default && $Verbose >= 2;
$path = $self->catdir($rprefix, $default) if $default;
}
print " now $path\n" if $Verbose >= 2;
return $self->{uc $var} = $path;
}
=item processPL (o)
Defines targets to run *.PL files.
=cut
sub processPL {
my $self = shift;
my $pl_files = $self->{PL_FILES};
return "" unless $pl_files;
my $m = '';
foreach my $plfile (sort keys %$pl_files) {
my $targets = $pl_files->{$plfile};
my $list =
ref($targets) eq 'HASH' ? [ sort keys %$targets ] :
ref($targets) eq 'ARRAY' ? $pl_files->{$plfile} :
[$pl_files->{$plfile}];
foreach my $target (@$list) {
if( $Is{VMS} ) {
$plfile = vmsify($self->eliminate_macros($plfile));
$target = vmsify($self->eliminate_macros($target));
}
# Normally a .PL file runs AFTER pm_to_blib so it can have
# blib in its @INC and load the just built modules. BUT if
# the generated module is something in $(TO_INST_PM) which
# pm_to_blib depends on then it can't depend on pm_to_blib
# else we have a dependency loop.
my $pm_dep;
my $perlrun;
if( defined $self->{PM}{$target} ) {
$pm_dep = '';
$perlrun = 'PERLRUN';
}
else {
$pm_dep = 'pm_to_blib';
$perlrun = 'PERLRUNINST';
}
my $extra_inputs = '';
if( ref($targets) eq 'HASH' ) {
my $inputs = ref($targets->{$target})
? $targets->{$target}
: [$targets->{$target}];
for my $input (@$inputs) {
if( $Is{VMS} ) {
$input = vmsify($self->eliminate_macros($input));
}
$extra_inputs .= ' '.$input;
}
}
$m .= <<MAKE_FRAG;
pure_all :: $target
\$(NOECHO) \$(NOOP)
$target :: $plfile $pm_dep $extra_inputs
\$($perlrun) $plfile $target $extra_inputs
MAKE_FRAG
}
}
return $m;
}
=item specify_shell
Specify SHELL if needed - not done on Unix.
=cut
sub specify_shell {
return '';
}
=item quote_paren
Backslashes parentheses C<()> in command line arguments.
Doesn't handle recursive Makefile C<$(...)> constructs,
but handles simple ones.
=cut
sub quote_paren {
my $arg = shift;
$arg =~ s{\$\((.+?)\)}{\$\\\\($1\\\\)}g; # protect $(...)
$arg =~ s{(?<!\\)([()])}{\\$1}g; # quote unprotected
$arg =~ s{\$\\\\\((.+?)\\\\\)}{\$($1)}g; # unprotect $(...)
return $arg;
}
=item replace_manpage_separator
my $man_name = $MM->replace_manpage_separator($file_path);
Takes the name of a package, which may be a nested package, in the
form 'Foo/Bar.pm' and replaces the slash with C<::> or something else
safe for a man page file name. Returns the replacement.
=cut
sub replace_manpage_separator {
my($self,$man) = @_;
$man =~ s,/+,::,g;
return $man;
}
=item cd
=cut
sub cd {
my($self, $dir, @cmds) = @_;
# No leading tab and no trailing newline makes for easier embedding
my $make_frag = join "\n\t", map { "cd $dir && $_" } @cmds;
return $make_frag;
}
=item oneliner
=cut
sub oneliner {
my($self, $cmd, $switches) = @_;
$switches = [] unless defined $switches;
# Strip leading and trailing newlines
$cmd =~ s{^\n+}{};
$cmd =~ s{\n+$}{};
my @cmds = split /\n/, $cmd;
$cmd = join " \n\t -e ", map $self->quote_literal($_), @cmds;
$cmd = $self->escape_newlines($cmd);
$switches = join ' ', @$switches;
return qq{\$(ABSPERLRUN) $switches -e $cmd --};
}
=item quote_literal
Quotes macro literal value suitable for being used on a command line so
that when expanded by make, will be received by command as given to
this method:
my $quoted = $mm->quote_literal(q{it isn't});
# returns:
# 'it isn'\''t'
print MAKEFILE "target:\n\techo $quoted\n";
# when run "make target", will output:
# it isn't
=cut
sub quote_literal {
my($self, $text, $opts) = @_;
$opts->{allow_variables} = 1 unless defined $opts->{allow_variables};
# Quote single quotes
$text =~ s{'}{'\\''}g;
$text = $opts->{allow_variables}
? $self->escape_dollarsigns($text) : $self->escape_all_dollarsigns($text);
return "'$text'";
}
=item escape_newlines
=cut
sub escape_newlines {
my($self, $text) = @_;
$text =~ s{\n}{\\\n}g;
return $text;
}
=item max_exec_len
Using POSIX::ARG_MAX. Otherwise falling back to 4096.
=cut
sub max_exec_len {
my $self = shift;
if (!defined $self->{_MAX_EXEC_LEN}) {
if (my $arg_max = eval { require POSIX; &POSIX::ARG_MAX }) {
$self->{_MAX_EXEC_LEN} = $arg_max;
}
else { # POSIX minimum exec size
$self->{_MAX_EXEC_LEN} = 4096;
}
}
return $self->{_MAX_EXEC_LEN};
}
=item static (o)
Defines the static target.
=cut
sub static {
# --- Static Loading Sections ---
my($self) = shift;
'
## $(INST_PM) has been moved to the all: target.
## It remains here for awhile to allow for old usage: "make static"
static :: $(FIRST_MAKEFILE) $(INST_STATIC)
$(NOECHO) $(NOOP)
';
}
sub static_lib {
my($self) = @_;
return '' unless $self->has_link_code;
my(@m);
my @libs;
if ($self->{XSMULTI}) {
for my $ext ($self->_xs_list_basenames) {
my ($v, $d, $f) = File::Spec->splitpath($ext);
my @d = File::Spec->splitdir($d);
shift @d if $d[0] eq 'lib';
my $instdir = $self->catdir('$(INST_ARCHLIB)', 'auto', @d, $f);
my $instfile = $self->catfile($instdir, "$f\$(LIB_EXT)");
my $objfile = "$ext\$(OBJ_EXT)";
push @libs, [ $objfile, $instfile, $instdir ];
}
} else {
@libs = ([ qw($(OBJECT) $(INST_STATIC) $(INST_ARCHAUTODIR)) ]);
}
push @m, map { $self->xs_make_static_lib(@$_); } @libs;
join "\n", @m;
}
=item xs_make_static_lib
Defines the recipes for the C<static_lib> section.
=cut
sub xs_make_static_lib {
my ($self, $from, $to, $todir) = @_;
my @m = sprintf '%s: %s $(MYEXTLIB) %s$(DFSEP).exists'."\n", $to, $from, $todir;
push @m, "\t\$(RM_F) \"\$\@\"\n";
push @m, $self->static_lib_fixtures;
push @m, $self->static_lib_pure_cmd($from);
push @m, "\t\$(CHMOD) \$(PERM_RWX) \$\@\n";
push @m, $self->static_lib_closures($todir);
join '', @m;
}
=item static_lib_closures
Records C<$(EXTRALIBS)> in F<extralibs.ld> and F<$(PERL_SRC)/ext.libs>.
=cut
sub static_lib_closures {
my ($self, $todir) = @_;
my @m = sprintf <<'MAKE_FRAG', $todir;
$(NOECHO) $(ECHO) "$(EXTRALIBS)" > %s$(DFSEP)extralibs.ld
MAKE_FRAG
# Old mechanism - still available:
push @m, <<'MAKE_FRAG' if $self->{PERL_SRC} && $self->{EXTRALIBS};
$(NOECHO) $(ECHO) "$(EXTRALIBS)" >> $(PERL_SRC)$(DFSEP)ext.libs
MAKE_FRAG
@m;
}
=item static_lib_fixtures
Handles copying C<$(MYEXTLIB)> as starter for final static library that
then gets added to.
=cut
sub static_lib_fixtures {
my ($self) = @_;
# If this extension has its own library (eg SDBM_File)
# then copy that to $(INST_STATIC) and add $(OBJECT) into it.
return unless $self->{MYEXTLIB};
"\t\$(CP) \$(MYEXTLIB) \"\$\@\"\n";
}
=item static_lib_pure_cmd
Defines how to run the archive utility.
=cut
sub static_lib_pure_cmd {
my ($self, $from) = @_;
my $ar;
if (exists $self->{FULL_AR} && -x $self->{FULL_AR}) {
# Prefer the absolute pathed ar if available so that PATH
# doesn't confuse us. Perl itself is built with the full_ar.
$ar = 'FULL_AR';
} else {
$ar = 'AR';
}
sprintf <<'MAKE_FRAG', $ar, $from;
$(%s) $(AR_STATIC_ARGS) "$@" %s
$(RANLIB) "$@"
MAKE_FRAG
}
=item staticmake (o)
Calls makeaperl.
=cut
sub staticmake {
my($self, %attribs) = @_;
my(@static);
my(@searchdirs)=($self->{PERL_ARCHLIB}, $self->{SITEARCHEXP}, $self->{INST_ARCHLIB});
# And as it's not yet built, we add the current extension
# but only if it has some C code (or XS code, which implies C code)
if (@{$self->{C}}) {
@static = $self->catfile($self->{INST_ARCHLIB},
"auto",
$self->{FULLEXT},
"$self->{BASEEXT}$self->{LIB_EXT}"
);
}
# Either we determine now, which libraries we will produce in the
# subdirectories or we do it at runtime of the make.
# We could ask all subdir objects, but I cannot imagine, why it
# would be necessary.
# Instead we determine all libraries for the new perl at
# runtime.
my(@perlinc) = ($self->{INST_ARCHLIB}, $self->{INST_LIB}, $self->{PERL_ARCHLIB}, $self->{PERL_LIB});
$self->makeaperl(MAKE => $self->{MAKEFILE},
DIRS => \@searchdirs,
STAT => \@static,
INCL => \@perlinc,
TARGET => $self->{MAP_TARGET},
TMP => "",
LIBPERL => $self->{LIBPERL_A}
);
}
=item subdir_x (o)
Helper subroutine for subdirs
=cut
sub subdir_x {
my($self, $subdir) = @_;
my $subdir_cmd = $self->cd($subdir,
'$(MAKE) $(USEMAKEFILE) $(FIRST_MAKEFILE) all $(PASTHRU)'
);
return sprintf <<'EOT', $subdir_cmd;
subdirs ::
$(NOECHO) %s
EOT
}
=item subdirs (o)
Defines targets to process subdirectories.
=cut
sub subdirs {
# --- Sub-directory Sections ---
my($self) = shift;
my(@m);
# This method provides a mechanism to automatically deal with
# subdirectories containing further Makefile.PL scripts.
# It calls the subdir_x() method for each subdirectory.
foreach my $dir (@{$self->{DIR}}){
push @m, $self->subdir_x($dir);
#### print "Including $dir subdirectory\n";
}
if (@m){
unshift @m, <<'EOF';
# The default clean, realclean and test targets in this Makefile
# have automatically been given entries for each subdir.
EOF
} else {
push(@m, "\n# none")
}
join('',@m);
}
=item test (o)
Defines the test targets.
=cut
sub test {
my($self, %attribs) = @_;
my $tests = $attribs{TESTS} || '';
if (!$tests && -d 't' && defined $attribs{RECURSIVE_TEST_FILES}) {
$tests = $self->find_tests_recursive;
}
elsif (!$tests && -d 't') {
$tests = $self->find_tests;
}
# have to do this because nmake is broken
$tests =~ s!/!\\!g if $self->is_make_type('nmake');
# note: 'test.pl' name is also hardcoded in init_dirscan()
my @m;
my $default_testtype = $Config{usedl} ? 'dynamic' : 'static';
push @m, <<EOF;
TEST_VERBOSE=0
TEST_TYPE=test_\$(LINKTYPE)
TEST_FILE = test.pl
TEST_FILES = $tests
TESTDB_SW = -d
testdb :: testdb_\$(LINKTYPE)
\$(NOECHO) \$(NOOP)
test :: \$(TEST_TYPE)
\$(NOECHO) \$(NOOP)
# Occasionally we may face this degenerate target:
test_ : test_$default_testtype
\$(NOECHO) \$(NOOP)
EOF
for my $linktype (qw(dynamic static)) {
my $directdeps = join ' ', grep !$self->{SKIPHASH}{$_}, $linktype, "pure_all"; # no depend on a linktype if SKIPped
push @m, "subdirs-test_$linktype :: $directdeps\n";
foreach my $dir (@{ $self->{DIR} }) {
my $test = $self->cd($dir, "\$(MAKE) test_$linktype \$(PASTHRU)");
push @m, "\t\$(NOECHO) $test\n";
}
push @m, "\n";
if ($tests or -f "test.pl") {
for my $testspec ([ '', '' ], [ 'db', ' $(TESTDB_SW)' ]) {
my ($db, $switch) = @$testspec;
my ($command, $deps);
# if testdb, build all but don't test all
$deps = $db eq 'db' ? $directdeps : "subdirs-test_$linktype";
if ($linktype eq 'static' and $self->needs_linking) {
my $target = File::Spec->rel2abs('$(MAP_TARGET)');
$command = qq{"$target" \$(MAP_PERLINC)};
$deps .= ' $(MAP_TARGET)';
} else {
$command = '$(FULLPERLRUN)' . $switch;
}
push @m, "test${db}_$linktype :: $deps\n";
if ($db eq 'db') {
push @m, $self->test_via_script($command, '$(TEST_FILE)')
} else {
push @m, $self->test_via_script($command, '$(TEST_FILE)')
if -f "test.pl";
push @m, $self->test_via_harness($command, '$(TEST_FILES)')
if $tests;
}
push @m, "\n";
}
} else {
push @m, _sprintf562 <<'EOF', $linktype;
testdb_%1$s test_%1$s :: subdirs-test_%1$s
$(NOECHO) $(ECHO) 'No tests defined for $(NAME) extension.'
EOF
}
}
join "", @m;
}
=item test_via_harness (override)
For some reason which I forget, Unix machines like to have
PERL_DL_NONLAZY set for tests.
=cut
sub test_via_harness {
my($self, $perl, $tests) = @_;
return $self->SUPER::test_via_harness("PERL_DL_NONLAZY=1 $perl", $tests);
}
=item test_via_script (override)
Again, the PERL_DL_NONLAZY thing.
=cut
sub test_via_script {
my($self, $perl, $script) = @_;
return $self->SUPER::test_via_script("PERL_DL_NONLAZY=1 $perl", $script);
}
=item tool_xsubpp (o)
Determines typemaps, xsubpp version, prototype behaviour.
=cut
sub tool_xsubpp {
my($self) = shift;
return "" unless $self->needs_linking;
my $xsdir;
my @xsubpp_dirs = @INC;
# Make sure we pick up the new xsubpp if we're building perl.
unshift @xsubpp_dirs, $self->{PERL_LIB} if $self->{PERL_CORE};
my $foundxsubpp = 0;
foreach my $dir (@xsubpp_dirs) {
$xsdir = $self->catdir($dir, 'ExtUtils');
if( -r $self->catfile($xsdir, "xsubpp") ) {
$foundxsubpp = 1;
last;
}
}
die "ExtUtils::MM_Unix::tool_xsubpp : Can't find xsubpp" if !$foundxsubpp;
my $tmdir = $self->catdir($self->{PERL_LIB},"ExtUtils");
my(@tmdeps) = $self->catfile($tmdir,'typemap');
if( $self->{TYPEMAPS} ){
foreach my $typemap (@{$self->{TYPEMAPS}}){
if( ! -f $typemap ) {
warn "Typemap $typemap not found.\n";
}
else {
$typemap = vmsify($typemap) if $Is{VMS};
push(@tmdeps, $typemap);
}
}
}
push(@tmdeps, "typemap") if -f "typemap";
# absolutised because with deep-located typemaps, eg "lib/XS/typemap",
# if xsubpp is called from top level with
# $(XSUBPP) ... -typemap "lib/XS/typemap" "lib/XS/Test.xs"
# it says:
# Can't find lib/XS/type map in (fulldir)/lib/XS
# because ExtUtils::ParseXS::process_file chdir's to .xs file's
# location. This is the only way to get all specified typemaps used,
# wherever located.
my @tmargs = map { '-typemap '.$self->quote_literal(File::Spec->rel2abs($_)) } @tmdeps;
$_ = $self->quote_dep($_) for @tmdeps;
if( exists $self->{XSOPT} ){
unshift( @tmargs, $self->{XSOPT} );
}
if ($Is{VMS} &&
$Config{'ldflags'} &&
$Config{'ldflags'} =~ m!/Debug!i &&
(!exists($self->{XSOPT}) || $self->{XSOPT} !~ /linenumbers/)
)
{
unshift(@tmargs,'-nolinenumbers');
}
$self->{XSPROTOARG} = "" unless defined $self->{XSPROTOARG};
my $xsdirdep = $self->quote_dep($xsdir);
# -dep for use when dependency not command
return qq{
XSUBPPDIR = $xsdir
XSUBPP = "\$(XSUBPPDIR)\$(DFSEP)xsubpp"
XSUBPPRUN = \$(PERLRUN) \$(XSUBPP)
XSPROTOARG = $self->{XSPROTOARG}
XSUBPPDEPS = @tmdeps $xsdirdep\$(DFSEP)xsubpp
XSUBPPARGS = @tmargs
XSUBPP_EXTRA_ARGS =
};
}
=item all_target
Build man pages, too
=cut
sub all_target {
my $self = shift;
return <<'MAKE_EXT';
all :: pure_all manifypods
$(NOECHO) $(NOOP)
MAKE_EXT
}
=item top_targets (o)
Defines the targets all, subdirs, config, and O_FILES
=cut
sub top_targets {
# --- Target Sections ---
my($self) = shift;
my(@m);
push @m, $self->all_target, "\n" unless $self->{SKIPHASH}{'all'};
push @m, sprintf <<'EOF';
pure_all :: config pm_to_blib subdirs linkext
$(NOECHO) $(NOOP)
$(NOECHO) $(NOOP)
subdirs :: $(MYEXTLIB)
$(NOECHO) $(NOOP)
config :: $(FIRST_MAKEFILE) blibdirs
$(NOECHO) $(NOOP)
EOF
push @m, '
$(O_FILES) : $(H_FILES)
' if @{$self->{O_FILES} || []} && @{$self->{H} || []};
push @m, q{
help :
perldoc ExtUtils::MakeMaker
};
join('',@m);
}
=item writedoc
Obsolete, deprecated method. Not used since Version 5.21.
=cut
sub writedoc {
# --- perllocal.pod section ---
my($self,$what,$name,@attribs)=@_;
my $time = gmtime($ENV{SOURCE_DATE_EPOCH} || time);
print "=head2 $time: $what C<$name>\n\n=over 4\n\n=item *\n\n";
print join "\n\n=item *\n\n", map("C<$_>",@attribs);
print "\n\n=back\n\n";
}
=item xs_c (o)
Defines the suffix rules to compile XS files to C.
=cut
sub xs_c {
my($self) = shift;
return '' unless $self->needs_linking();
'
.xs.c:
$(XSUBPPRUN) $(XSPROTOARG) $(XSUBPPARGS) $(XSUBPP_EXTRA_ARGS) $*.xs > $*.xsc
$(MV) $*.xsc $*.c
';
}
=item xs_cpp (o)
Defines the suffix rules to compile XS files to C++.
=cut
sub xs_cpp {
my($self) = shift;
return '' unless $self->needs_linking();
'
.xs.cpp:
$(XSUBPPRUN) $(XSPROTOARG) $(XSUBPPARGS) $*.xs > $*.xsc
$(MV) $*.xsc $*.cpp
';
}
=item xs_o (o)
Defines suffix rules to go from XS to object files directly. This was
originally only intended for broken make implementations, but is now
necessary for per-XS file under C<XSMULTI>, since each XS file might
have an individual C<$(VERSION)>.
=cut
sub xs_o {
my ($self) = @_;
return '' unless $self->needs_linking();
my $m_o = $self->{XSMULTI} ? $self->xs_obj_opt('$*$(OBJ_EXT)') : '';
my $dbgout = $self->dbgoutflag;
$dbgout = $dbgout ? "$dbgout " : '';
my $frag = '';
# dmake makes noise about ambiguous rule
$frag .= sprintf <<'EOF', $dbgout, $m_o unless $self->is_make_type('dmake');
.xs$(OBJ_EXT) :
$(XSUBPPRUN) $(XSPROTOARG) $(XSUBPPARGS) $*.xs > $*.xsc
$(MV) $*.xsc $*.c
$(CCCMD) $(CCCDLFLAGS) "-I$(PERL_INC)" $(PASTHRU_DEFINE) $(DEFINE) %s$*.c %s
EOF
if ($self->{XSMULTI}) {
for my $ext ($self->_xs_list_basenames) {
my $pmfile = "$ext.pm";
croak "$ext.xs has no matching $pmfile: $!" unless -f $pmfile;
my $version = $self->parse_version($pmfile);
my $cccmd = $self->{CONST_CCCMD};
$cccmd =~ s/^\s*CCCMD\s*=\s*//;
$cccmd =~ s/\$\(DEFINE_VERSION\)/-DVERSION=\\"$version\\"/;
$cccmd =~ s/\$\(XS_DEFINE_VERSION\)/-DXS_VERSION=\\"$version\\"/;
$self->_xsbuild_replace_macro($cccmd, 'xs', $ext, 'INC');
my $define = '$(DEFINE)';
$self->_xsbuild_replace_macro($define, 'xs', $ext, 'DEFINE');
# 1 2 3 4 5
$frag .= _sprintf562 <<'EOF', $ext, $cccmd, $m_o, $define, $dbgout;
%1$s$(OBJ_EXT): %1$s.xs
$(XSUBPPRUN) $(XSPROTOARG) $(XSUBPPARGS) $*.xs > $*.xsc
$(MV) $*.xsc $*.c
%2$s $(CCCDLFLAGS) "-I$(PERL_INC)" $(PASTHRU_DEFINE) %4$s %5$s$*.c %3$s
EOF
}
}
$frag;
}
# param gets modified
sub _xsbuild_replace_macro {
my ($self, undef, $xstype, $ext, $varname) = @_;
my $value = $self->_xsbuild_value($xstype, $ext, $varname);
return unless defined $value;
$_[1] =~ s/\$\($varname\)/$value/;
}
sub _xsbuild_value {
my ($self, $xstype, $ext, $varname) = @_;
return $self->{XSBUILD}{$xstype}{$ext}{$varname}
if $self->{XSBUILD}{$xstype}{$ext}{$varname};
return $self->{XSBUILD}{$xstype}{all}{$varname}
if $self->{XSBUILD}{$xstype}{all}{$varname};
();
}
1;
=back
=head1 SEE ALSO
L<ExtUtils::MakeMaker>
=cut
__END__
| {'repo_name': 'perl11/cperl', 'stars': '121', 'repo_language': 'Perl', 'file_name': 'warp', 'mime_type': 'text/x-shellscript', 'hash': -4840608817760825014, 'source_dataset': 'data'} |
//===- RegisterCoalescer.cpp - Generic Register Coalescing Interface ------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the generic RegisterCoalescer interface which
// is used as the common interface used by all clients and
// implementations of register coalescing.
//
//===----------------------------------------------------------------------===//
#include "RegisterCoalescer.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/BitVector.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/CodeGen/LiveInterval.h"
#include "llvm/CodeGen/LiveIntervals.h"
#include "llvm/CodeGen/LiveRangeEdit.h"
#include "llvm/CodeGen/MachineBasicBlock.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineLoopInfo.h"
#include "llvm/CodeGen/MachineOperand.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/CodeGen/RegisterClassInfo.h"
#include "llvm/CodeGen/SlotIndexes.h"
#include "llvm/CodeGen/TargetInstrInfo.h"
#include "llvm/CodeGen/TargetOpcodes.h"
#include "llvm/CodeGen/TargetRegisterInfo.h"
#include "llvm/CodeGen/TargetSubtargetInfo.h"
#include "llvm/IR/DebugLoc.h"
#include "llvm/MC/LaneBitmask.h"
#include "llvm/MC/MCInstrDesc.h"
#include "llvm/MC/MCRegisterInfo.h"
#include "llvm/Pass.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <cassert>
#include <iterator>
#include <limits>
#include <tuple>
#include <utility>
#include <vector>
using namespace llvm;
#define DEBUG_TYPE "regalloc"
STATISTIC(numJoins , "Number of interval joins performed");
STATISTIC(numCrossRCs , "Number of cross class joins performed");
STATISTIC(numCommutes , "Number of instruction commuting performed");
STATISTIC(numExtends , "Number of copies extended");
STATISTIC(NumReMats , "Number of instructions re-materialized");
STATISTIC(NumInflated , "Number of register classes inflated");
STATISTIC(NumLaneConflicts, "Number of dead lane conflicts tested");
STATISTIC(NumLaneResolves, "Number of dead lane conflicts resolved");
static cl::opt<bool> EnableJoining("join-liveintervals",
cl::desc("Coalesce copies (default=true)"),
cl::init(true), cl::Hidden);
static cl::opt<bool> UseTerminalRule("terminal-rule",
cl::desc("Apply the terminal rule"),
cl::init(false), cl::Hidden);
/// Temporary flag to test critical edge unsplitting.
static cl::opt<bool>
EnableJoinSplits("join-splitedges",
cl::desc("Coalesce copies on split edges (default=subtarget)"), cl::Hidden);
/// Temporary flag to test global copy optimization.
static cl::opt<cl::boolOrDefault>
EnableGlobalCopies("join-globalcopies",
cl::desc("Coalesce copies that span blocks (default=subtarget)"),
cl::init(cl::BOU_UNSET), cl::Hidden);
static cl::opt<bool>
VerifyCoalescing("verify-coalescing",
cl::desc("Verify machine instrs before and after register coalescing"),
cl::Hidden);
namespace {
class RegisterCoalescer : public MachineFunctionPass,
private LiveRangeEdit::Delegate {
MachineFunction* MF;
MachineRegisterInfo* MRI;
const TargetRegisterInfo* TRI;
const TargetInstrInfo* TII;
LiveIntervals *LIS;
const MachineLoopInfo* Loops;
AliasAnalysis *AA;
RegisterClassInfo RegClassInfo;
/// A LaneMask to remember on which subregister live ranges we need to call
/// shrinkToUses() later.
LaneBitmask ShrinkMask;
/// True if the main range of the currently coalesced intervals should be
/// checked for smaller live intervals.
bool ShrinkMainRange;
/// True if the coalescer should aggressively coalesce global copies
/// in favor of keeping local copies.
bool JoinGlobalCopies;
/// True if the coalescer should aggressively coalesce fall-thru
/// blocks exclusively containing copies.
bool JoinSplitEdges;
/// Copy instructions yet to be coalesced.
SmallVector<MachineInstr*, 8> WorkList;
SmallVector<MachineInstr*, 8> LocalWorkList;
/// Set of instruction pointers that have been erased, and
/// that may be present in WorkList.
SmallPtrSet<MachineInstr*, 8> ErasedInstrs;
/// Dead instructions that are about to be deleted.
SmallVector<MachineInstr*, 8> DeadDefs;
/// Virtual registers to be considered for register class inflation.
SmallVector<unsigned, 8> InflateRegs;
/// Recursively eliminate dead defs in DeadDefs.
void eliminateDeadDefs();
/// LiveRangeEdit callback for eliminateDeadDefs().
void LRE_WillEraseInstruction(MachineInstr *MI) override;
/// Coalesce the LocalWorkList.
void coalesceLocals();
/// Join compatible live intervals
void joinAllIntervals();
/// Coalesce copies in the specified MBB, putting
/// copies that cannot yet be coalesced into WorkList.
void copyCoalesceInMBB(MachineBasicBlock *MBB);
/// Tries to coalesce all copies in CurrList. Returns true if any progress
/// was made.
bool copyCoalesceWorkList(MutableArrayRef<MachineInstr*> CurrList);
/// Attempt to join intervals corresponding to SrcReg/DstReg, which are the
/// src/dst of the copy instruction CopyMI. This returns true if the copy
/// was successfully coalesced away. If it is not currently possible to
/// coalesce this interval, but it may be possible if other things get
/// coalesced, then it returns true by reference in 'Again'.
bool joinCopy(MachineInstr *CopyMI, bool &Again);
/// Attempt to join these two intervals. On failure, this
/// returns false. The output "SrcInt" will not have been modified, so we
/// can use this information below to update aliases.
bool joinIntervals(CoalescerPair &CP);
/// Attempt joining two virtual registers. Return true on success.
bool joinVirtRegs(CoalescerPair &CP);
/// Attempt joining with a reserved physreg.
bool joinReservedPhysReg(CoalescerPair &CP);
/// Add the LiveRange @p ToMerge as a subregister liverange of @p LI.
/// Subranges in @p LI which only partially interfere with the desired
/// LaneMask are split as necessary. @p LaneMask are the lanes that
/// @p ToMerge will occupy in the coalescer register. @p LI has its subrange
/// lanemasks already adjusted to the coalesced register.
void mergeSubRangeInto(LiveInterval &LI, const LiveRange &ToMerge,
LaneBitmask LaneMask, CoalescerPair &CP);
/// Join the liveranges of two subregisters. Joins @p RRange into
/// @p LRange, @p RRange may be invalid afterwards.
void joinSubRegRanges(LiveRange &LRange, LiveRange &RRange,
LaneBitmask LaneMask, const CoalescerPair &CP);
/// We found a non-trivially-coalescable copy. If the source value number is
/// defined by a copy from the destination reg see if we can merge these two
/// destination reg valno# into a single value number, eliminating a copy.
/// This returns true if an interval was modified.
bool adjustCopiesBackFrom(const CoalescerPair &CP, MachineInstr *CopyMI);
/// Return true if there are definitions of IntB
/// other than BValNo val# that can reach uses of AValno val# of IntA.
bool hasOtherReachingDefs(LiveInterval &IntA, LiveInterval &IntB,
VNInfo *AValNo, VNInfo *BValNo);
/// We found a non-trivially-coalescable copy.
/// If the source value number is defined by a commutable instruction and
/// its other operand is coalesced to the copy dest register, see if we
/// can transform the copy into a noop by commuting the definition.
/// This returns true if an interval was modified.
bool removeCopyByCommutingDef(const CoalescerPair &CP,MachineInstr *CopyMI);
/// We found a copy which can be moved to its less frequent predecessor.
bool removePartialRedundancy(const CoalescerPair &CP, MachineInstr &CopyMI);
/// If the source of a copy is defined by a
/// trivial computation, replace the copy by rematerialize the definition.
bool reMaterializeTrivialDef(const CoalescerPair &CP, MachineInstr *CopyMI,
bool &IsDefCopy);
/// Return true if a copy involving a physreg should be joined.
bool canJoinPhys(const CoalescerPair &CP);
/// Replace all defs and uses of SrcReg to DstReg and update the subregister
/// number if it is not zero. If DstReg is a physical register and the
/// existing subregister number of the def / use being updated is not zero,
/// make sure to set it to the correct physical subregister.
void updateRegDefsUses(unsigned SrcReg, unsigned DstReg, unsigned SubIdx);
/// If the given machine operand reads only undefined lanes add an undef
/// flag.
/// This can happen when undef uses were previously concealed by a copy
/// which we coalesced. Example:
/// %0:sub0<def,read-undef> = ...
/// %1 = COPY %0 <-- Coalescing COPY reveals undef
/// = use %1:sub1 <-- hidden undef use
void addUndefFlag(const LiveInterval &Int, SlotIndex UseIdx,
MachineOperand &MO, unsigned SubRegIdx);
/// Handle copies of undef values. If the undef value is an incoming
/// PHI value, it will convert @p CopyMI to an IMPLICIT_DEF.
/// Returns nullptr if @p CopyMI was not in any way eliminable. Otherwise,
/// it returns @p CopyMI (which could be an IMPLICIT_DEF at this point).
MachineInstr *eliminateUndefCopy(MachineInstr *CopyMI);
/// Check whether or not we should apply the terminal rule on the
/// destination (Dst) of \p Copy.
/// When the terminal rule applies, Copy is not profitable to
/// coalesce.
/// Dst is terminal if it has exactly one affinity (Dst, Src) and
/// at least one interference (Dst, Dst2). If Dst is terminal, the
/// terminal rule consists in checking that at least one of
/// interfering node, say Dst2, has an affinity of equal or greater
/// weight with Src.
/// In that case, Dst2 and Dst will not be able to be both coalesced
/// with Src. Since Dst2 exposes more coalescing opportunities than
/// Dst, we can drop \p Copy.
bool applyTerminalRule(const MachineInstr &Copy) const;
/// Wrapper method for \see LiveIntervals::shrinkToUses.
/// This method does the proper fixing of the live-ranges when the afore
/// mentioned method returns true.
void shrinkToUses(LiveInterval *LI,
SmallVectorImpl<MachineInstr * > *Dead = nullptr) {
if (LIS->shrinkToUses(LI, Dead)) {
/// Check whether or not \p LI is composed by multiple connected
/// components and if that is the case, fix that.
SmallVector<LiveInterval*, 8> SplitLIs;
LIS->splitSeparateComponents(*LI, SplitLIs);
}
}
/// Wrapper Method to do all the necessary work when an Instruction is
/// deleted.
/// Optimizations should use this to make sure that deleted instructions
/// are always accounted for.
void deleteInstr(MachineInstr* MI) {
ErasedInstrs.insert(MI);
LIS->RemoveMachineInstrFromMaps(*MI);
MI->eraseFromParent();
}
public:
static char ID; ///< Class identification, replacement for typeinfo
RegisterCoalescer() : MachineFunctionPass(ID) {
initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
}
void getAnalysisUsage(AnalysisUsage &AU) const override;
void releaseMemory() override;
/// This is the pass entry point.
bool runOnMachineFunction(MachineFunction&) override;
/// Implement the dump method.
void print(raw_ostream &O, const Module* = nullptr) const override;
};
} // end anonymous namespace
char RegisterCoalescer::ID = 0;
char &llvm::RegisterCoalescerID = RegisterCoalescer::ID;
INITIALIZE_PASS_BEGIN(RegisterCoalescer, "simple-register-coalescing",
"Simple Register Coalescing", false, false)
INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
INITIALIZE_PASS_END(RegisterCoalescer, "simple-register-coalescing",
"Simple Register Coalescing", false, false)
static bool isMoveInstr(const TargetRegisterInfo &tri, const MachineInstr *MI,
unsigned &Src, unsigned &Dst,
unsigned &SrcSub, unsigned &DstSub) {
if (MI->isCopy()) {
Dst = MI->getOperand(0).getReg();
DstSub = MI->getOperand(0).getSubReg();
Src = MI->getOperand(1).getReg();
SrcSub = MI->getOperand(1).getSubReg();
} else if (MI->isSubregToReg()) {
Dst = MI->getOperand(0).getReg();
DstSub = tri.composeSubRegIndices(MI->getOperand(0).getSubReg(),
MI->getOperand(3).getImm());
Src = MI->getOperand(2).getReg();
SrcSub = MI->getOperand(2).getSubReg();
} else
return false;
return true;
}
/// Return true if this block should be vacated by the coalescer to eliminate
/// branches. The important cases to handle in the coalescer are critical edges
/// split during phi elimination which contain only copies. Simple blocks that
/// contain non-branches should also be vacated, but this can be handled by an
/// earlier pass similar to early if-conversion.
static bool isSplitEdge(const MachineBasicBlock *MBB) {
if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
return false;
for (const auto &MI : *MBB) {
if (!MI.isCopyLike() && !MI.isUnconditionalBranch())
return false;
}
return true;
}
bool CoalescerPair::setRegisters(const MachineInstr *MI) {
SrcReg = DstReg = 0;
SrcIdx = DstIdx = 0;
NewRC = nullptr;
Flipped = CrossClass = false;
unsigned Src, Dst, SrcSub, DstSub;
if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
return false;
Partial = SrcSub || DstSub;
// If one register is a physreg, it must be Dst.
if (TargetRegisterInfo::isPhysicalRegister(Src)) {
if (TargetRegisterInfo::isPhysicalRegister(Dst))
return false;
std::swap(Src, Dst);
std::swap(SrcSub, DstSub);
Flipped = true;
}
const MachineRegisterInfo &MRI = MI->getMF()->getRegInfo();
if (TargetRegisterInfo::isPhysicalRegister(Dst)) {
// Eliminate DstSub on a physreg.
if (DstSub) {
Dst = TRI.getSubReg(Dst, DstSub);
if (!Dst) return false;
DstSub = 0;
}
// Eliminate SrcSub by picking a corresponding Dst superregister.
if (SrcSub) {
Dst = TRI.getMatchingSuperReg(Dst, SrcSub, MRI.getRegClass(Src));
if (!Dst) return false;
} else if (!MRI.getRegClass(Src)->contains(Dst)) {
return false;
}
} else {
// Both registers are virtual.
const TargetRegisterClass *SrcRC = MRI.getRegClass(Src);
const TargetRegisterClass *DstRC = MRI.getRegClass(Dst);
// Both registers have subreg indices.
if (SrcSub && DstSub) {
// Copies between different sub-registers are never coalescable.
if (Src == Dst && SrcSub != DstSub)
return false;
NewRC = TRI.getCommonSuperRegClass(SrcRC, SrcSub, DstRC, DstSub,
SrcIdx, DstIdx);
if (!NewRC)
return false;
} else if (DstSub) {
// SrcReg will be merged with a sub-register of DstReg.
SrcIdx = DstSub;
NewRC = TRI.getMatchingSuperRegClass(DstRC, SrcRC, DstSub);
} else if (SrcSub) {
// DstReg will be merged with a sub-register of SrcReg.
DstIdx = SrcSub;
NewRC = TRI.getMatchingSuperRegClass(SrcRC, DstRC, SrcSub);
} else {
// This is a straight copy without sub-registers.
NewRC = TRI.getCommonSubClass(DstRC, SrcRC);
}
// The combined constraint may be impossible to satisfy.
if (!NewRC)
return false;
// Prefer SrcReg to be a sub-register of DstReg.
// FIXME: Coalescer should support subregs symmetrically.
if (DstIdx && !SrcIdx) {
std::swap(Src, Dst);
std::swap(SrcIdx, DstIdx);
Flipped = !Flipped;
}
CrossClass = NewRC != DstRC || NewRC != SrcRC;
}
// Check our invariants
assert(TargetRegisterInfo::isVirtualRegister(Src) && "Src must be virtual");
assert(!(TargetRegisterInfo::isPhysicalRegister(Dst) && DstSub) &&
"Cannot have a physical SubIdx");
SrcReg = Src;
DstReg = Dst;
return true;
}
bool CoalescerPair::flip() {
if (TargetRegisterInfo::isPhysicalRegister(DstReg))
return false;
std::swap(SrcReg, DstReg);
std::swap(SrcIdx, DstIdx);
Flipped = !Flipped;
return true;
}
bool CoalescerPair::isCoalescable(const MachineInstr *MI) const {
if (!MI)
return false;
unsigned Src, Dst, SrcSub, DstSub;
if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
return false;
// Find the virtual register that is SrcReg.
if (Dst == SrcReg) {
std::swap(Src, Dst);
std::swap(SrcSub, DstSub);
} else if (Src != SrcReg) {
return false;
}
// Now check that Dst matches DstReg.
if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
if (!TargetRegisterInfo::isPhysicalRegister(Dst))
return false;
assert(!DstIdx && !SrcIdx && "Inconsistent CoalescerPair state.");
// DstSub could be set for a physreg from INSERT_SUBREG.
if (DstSub)
Dst = TRI.getSubReg(Dst, DstSub);
// Full copy of Src.
if (!SrcSub)
return DstReg == Dst;
// This is a partial register copy. Check that the parts match.
return TRI.getSubReg(DstReg, SrcSub) == Dst;
} else {
// DstReg is virtual.
if (DstReg != Dst)
return false;
// Registers match, do the subregisters line up?
return TRI.composeSubRegIndices(SrcIdx, SrcSub) ==
TRI.composeSubRegIndices(DstIdx, DstSub);
}
}
void RegisterCoalescer::getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesCFG();
AU.addRequired<AAResultsWrapperPass>();
AU.addRequired<LiveIntervals>();
AU.addPreserved<LiveIntervals>();
AU.addPreserved<SlotIndexes>();
AU.addRequired<MachineLoopInfo>();
AU.addPreserved<MachineLoopInfo>();
AU.addPreservedID(MachineDominatorsID);
MachineFunctionPass::getAnalysisUsage(AU);
}
void RegisterCoalescer::eliminateDeadDefs() {
SmallVector<unsigned, 8> NewRegs;
LiveRangeEdit(nullptr, NewRegs, *MF, *LIS,
nullptr, this).eliminateDeadDefs(DeadDefs);
}
void RegisterCoalescer::LRE_WillEraseInstruction(MachineInstr *MI) {
// MI may be in WorkList. Make sure we don't visit it.
ErasedInstrs.insert(MI);
}
bool RegisterCoalescer::adjustCopiesBackFrom(const CoalescerPair &CP,
MachineInstr *CopyMI) {
assert(!CP.isPartial() && "This doesn't work for partial copies.");
assert(!CP.isPhys() && "This doesn't work for physreg copies.");
LiveInterval &IntA =
LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
LiveInterval &IntB =
LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
SlotIndex CopyIdx = LIS->getInstructionIndex(*CopyMI).getRegSlot();
// We have a non-trivially-coalescable copy with IntA being the source and
// IntB being the dest, thus this defines a value number in IntB. If the
// source value number (in IntA) is defined by a copy from B, see if we can
// merge these two pieces of B into a single value number, eliminating a copy.
// For example:
//
// A3 = B0
// ...
// B1 = A3 <- this copy
//
// In this case, B0 can be extended to where the B1 copy lives, allowing the
// B1 value number to be replaced with B0 (which simplifies the B
// liveinterval).
// BValNo is a value number in B that is defined by a copy from A. 'B1' in
// the example above.
LiveInterval::iterator BS = IntB.FindSegmentContaining(CopyIdx);
if (BS == IntB.end()) return false;
VNInfo *BValNo = BS->valno;
// Get the location that B is defined at. Two options: either this value has
// an unknown definition point or it is defined at CopyIdx. If unknown, we
// can't process it.
if (BValNo->def != CopyIdx) return false;
// AValNo is the value number in A that defines the copy, A3 in the example.
SlotIndex CopyUseIdx = CopyIdx.getRegSlot(true);
LiveInterval::iterator AS = IntA.FindSegmentContaining(CopyUseIdx);
// The live segment might not exist after fun with physreg coalescing.
if (AS == IntA.end()) return false;
VNInfo *AValNo = AS->valno;
// If AValNo is defined as a copy from IntB, we can potentially process this.
// Get the instruction that defines this value number.
MachineInstr *ACopyMI = LIS->getInstructionFromIndex(AValNo->def);
// Don't allow any partial copies, even if isCoalescable() allows them.
if (!CP.isCoalescable(ACopyMI) || !ACopyMI->isFullCopy())
return false;
// Get the Segment in IntB that this value number starts with.
LiveInterval::iterator ValS =
IntB.FindSegmentContaining(AValNo->def.getPrevSlot());
if (ValS == IntB.end())
return false;
// Make sure that the end of the live segment is inside the same block as
// CopyMI.
MachineInstr *ValSEndInst =
LIS->getInstructionFromIndex(ValS->end.getPrevSlot());
if (!ValSEndInst || ValSEndInst->getParent() != CopyMI->getParent())
return false;
// Okay, we now know that ValS ends in the same block that the CopyMI
// live-range starts. If there are no intervening live segments between them
// in IntB, we can merge them.
if (ValS+1 != BS) return false;
LLVM_DEBUG(dbgs() << "Extending: " << printReg(IntB.reg, TRI));
SlotIndex FillerStart = ValS->end, FillerEnd = BS->start;
// We are about to delete CopyMI, so need to remove it as the 'instruction
// that defines this value #'. Update the valnum with the new defining
// instruction #.
BValNo->def = FillerStart;
// Okay, we can merge them. We need to insert a new liverange:
// [ValS.end, BS.begin) of either value number, then we merge the
// two value numbers.
IntB.addSegment(LiveInterval::Segment(FillerStart, FillerEnd, BValNo));
// Okay, merge "B1" into the same value number as "B0".
if (BValNo != ValS->valno)
IntB.MergeValueNumberInto(BValNo, ValS->valno);
// Do the same for the subregister segments.
for (LiveInterval::SubRange &S : IntB.subranges()) {
// Check for SubRange Segments of the form [1234r,1234d:0) which can be
// removed to prevent creating bogus SubRange Segments.
LiveInterval::iterator SS = S.FindSegmentContaining(CopyIdx);
if (SS != S.end() && SlotIndex::isSameInstr(SS->start, SS->end)) {
S.removeSegment(*SS, true);
continue;
}
VNInfo *SubBValNo = S.getVNInfoAt(CopyIdx);
S.addSegment(LiveInterval::Segment(FillerStart, FillerEnd, SubBValNo));
VNInfo *SubValSNo = S.getVNInfoAt(AValNo->def.getPrevSlot());
if (SubBValNo != SubValSNo)
S.MergeValueNumberInto(SubBValNo, SubValSNo);
}
LLVM_DEBUG(dbgs() << " result = " << IntB << '\n');
// If the source instruction was killing the source register before the
// merge, unset the isKill marker given the live range has been extended.
int UIdx = ValSEndInst->findRegisterUseOperandIdx(IntB.reg, true);
if (UIdx != -1) {
ValSEndInst->getOperand(UIdx).setIsKill(false);
}
// Rewrite the copy.
CopyMI->substituteRegister(IntA.reg, IntB.reg, 0, *TRI);
// If the copy instruction was killing the destination register or any
// subrange before the merge trim the live range.
bool RecomputeLiveRange = AS->end == CopyIdx;
if (!RecomputeLiveRange) {
for (LiveInterval::SubRange &S : IntA.subranges()) {
LiveInterval::iterator SS = S.FindSegmentContaining(CopyUseIdx);
if (SS != S.end() && SS->end == CopyIdx) {
RecomputeLiveRange = true;
break;
}
}
}
if (RecomputeLiveRange)
shrinkToUses(&IntA);
++numExtends;
return true;
}
bool RegisterCoalescer::hasOtherReachingDefs(LiveInterval &IntA,
LiveInterval &IntB,
VNInfo *AValNo,
VNInfo *BValNo) {
// If AValNo has PHI kills, conservatively assume that IntB defs can reach
// the PHI values.
if (LIS->hasPHIKill(IntA, AValNo))
return true;
for (LiveRange::Segment &ASeg : IntA.segments) {
if (ASeg.valno != AValNo) continue;
LiveInterval::iterator BI =
std::upper_bound(IntB.begin(), IntB.end(), ASeg.start);
if (BI != IntB.begin())
--BI;
for (; BI != IntB.end() && ASeg.end >= BI->start; ++BI) {
if (BI->valno == BValNo)
continue;
if (BI->start <= ASeg.start && BI->end > ASeg.start)
return true;
if (BI->start > ASeg.start && BI->start < ASeg.end)
return true;
}
}
return false;
}
/// Copy segments with value number @p SrcValNo from liverange @p Src to live
/// range @Dst and use value number @p DstValNo there.
static void addSegmentsWithValNo(LiveRange &Dst, VNInfo *DstValNo,
const LiveRange &Src, const VNInfo *SrcValNo) {
for (const LiveRange::Segment &S : Src.segments) {
if (S.valno != SrcValNo)
continue;
Dst.addSegment(LiveRange::Segment(S.start, S.end, DstValNo));
}
}
bool RegisterCoalescer::removeCopyByCommutingDef(const CoalescerPair &CP,
MachineInstr *CopyMI) {
assert(!CP.isPhys());
LiveInterval &IntA =
LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
LiveInterval &IntB =
LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
// We found a non-trivially-coalescable copy with IntA being the source and
// IntB being the dest, thus this defines a value number in IntB. If the
// source value number (in IntA) is defined by a commutable instruction and
// its other operand is coalesced to the copy dest register, see if we can
// transform the copy into a noop by commuting the definition. For example,
//
// A3 = op A2 killed B0
// ...
// B1 = A3 <- this copy
// ...
// = op A3 <- more uses
//
// ==>
//
// B2 = op B0 killed A2
// ...
// B1 = B2 <- now an identity copy
// ...
// = op B2 <- more uses
// BValNo is a value number in B that is defined by a copy from A. 'B1' in
// the example above.
SlotIndex CopyIdx = LIS->getInstructionIndex(*CopyMI).getRegSlot();
VNInfo *BValNo = IntB.getVNInfoAt(CopyIdx);
assert(BValNo != nullptr && BValNo->def == CopyIdx);
// AValNo is the value number in A that defines the copy, A3 in the example.
VNInfo *AValNo = IntA.getVNInfoAt(CopyIdx.getRegSlot(true));
assert(AValNo && !AValNo->isUnused() && "COPY source not live");
if (AValNo->isPHIDef())
return false;
MachineInstr *DefMI = LIS->getInstructionFromIndex(AValNo->def);
if (!DefMI)
return false;
if (!DefMI->isCommutable())
return false;
// If DefMI is a two-address instruction then commuting it will change the
// destination register.
int DefIdx = DefMI->findRegisterDefOperandIdx(IntA.reg);
assert(DefIdx != -1);
unsigned UseOpIdx;
if (!DefMI->isRegTiedToUseOperand(DefIdx, &UseOpIdx))
return false;
// FIXME: The code below tries to commute 'UseOpIdx' operand with some other
// commutable operand which is expressed by 'CommuteAnyOperandIndex'value
// passed to the method. That _other_ operand is chosen by
// the findCommutedOpIndices() method.
//
// That is obviously an area for improvement in case of instructions having
// more than 2 operands. For example, if some instruction has 3 commutable
// operands then all possible variants (i.e. op#1<->op#2, op#1<->op#3,
// op#2<->op#3) of commute transformation should be considered/tried here.
unsigned NewDstIdx = TargetInstrInfo::CommuteAnyOperandIndex;
if (!TII->findCommutedOpIndices(*DefMI, UseOpIdx, NewDstIdx))
return false;
MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
unsigned NewReg = NewDstMO.getReg();
if (NewReg != IntB.reg || !IntB.Query(AValNo->def).isKill())
return false;
// Make sure there are no other definitions of IntB that would reach the
// uses which the new definition can reach.
if (hasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
return false;
// If some of the uses of IntA.reg is already coalesced away, return false.
// It's not possible to determine whether it's safe to perform the coalescing.
for (MachineOperand &MO : MRI->use_nodbg_operands(IntA.reg)) {
MachineInstr *UseMI = MO.getParent();
unsigned OpNo = &MO - &UseMI->getOperand(0);
SlotIndex UseIdx = LIS->getInstructionIndex(*UseMI);
LiveInterval::iterator US = IntA.FindSegmentContaining(UseIdx);
if (US == IntA.end() || US->valno != AValNo)
continue;
// If this use is tied to a def, we can't rewrite the register.
if (UseMI->isRegTiedToDefOperand(OpNo))
return false;
}
LLVM_DEBUG(dbgs() << "\tremoveCopyByCommutingDef: " << AValNo->def << '\t'
<< *DefMI);
// At this point we have decided that it is legal to do this
// transformation. Start by commuting the instruction.
MachineBasicBlock *MBB = DefMI->getParent();
MachineInstr *NewMI =
TII->commuteInstruction(*DefMI, false, UseOpIdx, NewDstIdx);
if (!NewMI)
return false;
if (TargetRegisterInfo::isVirtualRegister(IntA.reg) &&
TargetRegisterInfo::isVirtualRegister(IntB.reg) &&
!MRI->constrainRegClass(IntB.reg, MRI->getRegClass(IntA.reg)))
return false;
if (NewMI != DefMI) {
LIS->ReplaceMachineInstrInMaps(*DefMI, *NewMI);
MachineBasicBlock::iterator Pos = DefMI;
MBB->insert(Pos, NewMI);
MBB->erase(DefMI);
}
// If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
// A = or A, B
// ...
// B = A
// ...
// C = killed A
// ...
// = B
// Update uses of IntA of the specific Val# with IntB.
for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(IntA.reg),
UE = MRI->use_end();
UI != UE; /* ++UI is below because of possible MI removal */) {
MachineOperand &UseMO = *UI;
++UI;
if (UseMO.isUndef())
continue;
MachineInstr *UseMI = UseMO.getParent();
if (UseMI->isDebugValue()) {
// FIXME These don't have an instruction index. Not clear we have enough
// info to decide whether to do this replacement or not. For now do it.
UseMO.setReg(NewReg);
continue;
}
SlotIndex UseIdx = LIS->getInstructionIndex(*UseMI).getRegSlot(true);
LiveInterval::iterator US = IntA.FindSegmentContaining(UseIdx);
assert(US != IntA.end() && "Use must be live");
if (US->valno != AValNo)
continue;
// Kill flags are no longer accurate. They are recomputed after RA.
UseMO.setIsKill(false);
if (TargetRegisterInfo::isPhysicalRegister(NewReg))
UseMO.substPhysReg(NewReg, *TRI);
else
UseMO.setReg(NewReg);
if (UseMI == CopyMI)
continue;
if (!UseMI->isCopy())
continue;
if (UseMI->getOperand(0).getReg() != IntB.reg ||
UseMI->getOperand(0).getSubReg())
continue;
// This copy will become a noop. If it's defining a new val#, merge it into
// BValNo.
SlotIndex DefIdx = UseIdx.getRegSlot();
VNInfo *DVNI = IntB.getVNInfoAt(DefIdx);
if (!DVNI)
continue;
LLVM_DEBUG(dbgs() << "\t\tnoop: " << DefIdx << '\t' << *UseMI);
assert(DVNI->def == DefIdx);
BValNo = IntB.MergeValueNumberInto(DVNI, BValNo);
for (LiveInterval::SubRange &S : IntB.subranges()) {
VNInfo *SubDVNI = S.getVNInfoAt(DefIdx);
if (!SubDVNI)
continue;
VNInfo *SubBValNo = S.getVNInfoAt(CopyIdx);
assert(SubBValNo->def == CopyIdx);
S.MergeValueNumberInto(SubDVNI, SubBValNo);
}
deleteInstr(UseMI);
}
// Extend BValNo by merging in IntA live segments of AValNo. Val# definition
// is updated.
BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator();
if (IntB.hasSubRanges()) {
if (!IntA.hasSubRanges()) {
LaneBitmask Mask = MRI->getMaxLaneMaskForVReg(IntA.reg);
IntA.createSubRangeFrom(Allocator, Mask, IntA);
}
SlotIndex AIdx = CopyIdx.getRegSlot(true);
for (LiveInterval::SubRange &SA : IntA.subranges()) {
VNInfo *ASubValNo = SA.getVNInfoAt(AIdx);
assert(ASubValNo != nullptr);
IntB.refineSubRanges(Allocator, SA.LaneMask,
[&Allocator,&SA,CopyIdx,ASubValNo](LiveInterval::SubRange &SR) {
VNInfo *BSubValNo = SR.empty()
? SR.getNextValue(CopyIdx, Allocator)
: SR.getVNInfoAt(CopyIdx);
assert(BSubValNo != nullptr);
addSegmentsWithValNo(SR, BSubValNo, SA, ASubValNo);
});
}
}
BValNo->def = AValNo->def;
addSegmentsWithValNo(IntB, BValNo, IntA, AValNo);
LLVM_DEBUG(dbgs() << "\t\textended: " << IntB << '\n');
LIS->removeVRegDefAt(IntA, AValNo->def);
LLVM_DEBUG(dbgs() << "\t\ttrimmed: " << IntA << '\n');
++numCommutes;
return true;
}
/// For copy B = A in BB2, if A is defined by A = B in BB0 which is a
/// predecessor of BB2, and if B is not redefined on the way from A = B
/// in BB2 to B = A in BB2, B = A in BB2 is partially redundant if the
/// execution goes through the path from BB0 to BB2. We may move B = A
/// to the predecessor without such reversed copy.
/// So we will transform the program from:
/// BB0:
/// A = B; BB1:
/// ... ...
/// / \ /
/// BB2:
/// ...
/// B = A;
///
/// to:
///
/// BB0: BB1:
/// A = B; ...
/// ... B = A;
/// / \ /
/// BB2:
/// ...
///
/// A special case is when BB0 and BB2 are the same BB which is the only
/// BB in a loop:
/// BB1:
/// ...
/// BB0/BB2: ----
/// B = A; |
/// ... |
/// A = B; |
/// |-------
/// |
/// We may hoist B = A from BB0/BB2 to BB1.
///
/// The major preconditions for correctness to remove such partial
/// redundancy include:
/// 1. A in B = A in BB2 is defined by a PHI in BB2, and one operand of
/// the PHI is defined by the reversed copy A = B in BB0.
/// 2. No B is referenced from the start of BB2 to B = A.
/// 3. No B is defined from A = B to the end of BB0.
/// 4. BB1 has only one successor.
///
/// 2 and 4 implicitly ensure B is not live at the end of BB1.
/// 4 guarantees BB2 is hotter than BB1, so we can only move a copy to a
/// colder place, which not only prevent endless loop, but also make sure
/// the movement of copy is beneficial.
bool RegisterCoalescer::removePartialRedundancy(const CoalescerPair &CP,
MachineInstr &CopyMI) {
assert(!CP.isPhys());
if (!CopyMI.isFullCopy())
return false;
MachineBasicBlock &MBB = *CopyMI.getParent();
if (MBB.isEHPad())
return false;
if (MBB.pred_size() != 2)
return false;
LiveInterval &IntA =
LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
LiveInterval &IntB =
LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
// A is defined by PHI at the entry of MBB.
SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot(true);
VNInfo *AValNo = IntA.getVNInfoAt(CopyIdx);
assert(AValNo && !AValNo->isUnused() && "COPY source not live");
if (!AValNo->isPHIDef())
return false;
// No B is referenced before CopyMI in MBB.
if (IntB.overlaps(LIS->getMBBStartIdx(&MBB), CopyIdx))
return false;
// MBB has two predecessors: one contains A = B so no copy will be inserted
// for it. The other one will have a copy moved from MBB.
bool FoundReverseCopy = false;
MachineBasicBlock *CopyLeftBB = nullptr;
for (MachineBasicBlock *Pred : MBB.predecessors()) {
VNInfo *PVal = IntA.getVNInfoBefore(LIS->getMBBEndIdx(Pred));
MachineInstr *DefMI = LIS->getInstructionFromIndex(PVal->def);
if (!DefMI || !DefMI->isFullCopy()) {
CopyLeftBB = Pred;
continue;
}
// Check DefMI is a reverse copy and it is in BB Pred.
if (DefMI->getOperand(0).getReg() != IntA.reg ||
DefMI->getOperand(1).getReg() != IntB.reg ||
DefMI->getParent() != Pred) {
CopyLeftBB = Pred;
continue;
}
// If there is any other def of B after DefMI and before the end of Pred,
// we need to keep the copy of B = A at the end of Pred if we remove
// B = A from MBB.
bool ValB_Changed = false;
for (auto VNI : IntB.valnos) {
if (VNI->isUnused())
continue;
if (PVal->def < VNI->def && VNI->def < LIS->getMBBEndIdx(Pred)) {
ValB_Changed = true;
break;
}
}
if (ValB_Changed) {
CopyLeftBB = Pred;
continue;
}
FoundReverseCopy = true;
}
// If no reverse copy is found in predecessors, nothing to do.
if (!FoundReverseCopy)
return false;
// If CopyLeftBB is nullptr, it means every predecessor of MBB contains
// reverse copy, CopyMI can be removed trivially if only IntA/IntB is updated.
// If CopyLeftBB is not nullptr, move CopyMI from MBB to CopyLeftBB and
// update IntA/IntB.
//
// If CopyLeftBB is not nullptr, ensure CopyLeftBB has a single succ so
// MBB is hotter than CopyLeftBB.
if (CopyLeftBB && CopyLeftBB->succ_size() > 1)
return false;
// Now (almost sure it's) ok to move copy.
if (CopyLeftBB) {
// Position in CopyLeftBB where we should insert new copy.
auto InsPos = CopyLeftBB->getFirstTerminator();
// Make sure that B isn't referenced in the terminators (if any) at the end
// of the predecessor since we're about to insert a new definition of B
// before them.
if (InsPos != CopyLeftBB->end()) {
SlotIndex InsPosIdx = LIS->getInstructionIndex(*InsPos).getRegSlot(true);
if (IntB.overlaps(InsPosIdx, LIS->getMBBEndIdx(CopyLeftBB)))
return false;
}
LLVM_DEBUG(dbgs() << "\tremovePartialRedundancy: Move the copy to "
<< printMBBReference(*CopyLeftBB) << '\t' << CopyMI);
// Insert new copy to CopyLeftBB.
MachineInstr *NewCopyMI = BuildMI(*CopyLeftBB, InsPos, CopyMI.getDebugLoc(),
TII->get(TargetOpcode::COPY), IntB.reg)
.addReg(IntA.reg);
SlotIndex NewCopyIdx =
LIS->InsertMachineInstrInMaps(*NewCopyMI).getRegSlot();
IntB.createDeadDef(NewCopyIdx, LIS->getVNInfoAllocator());
for (LiveInterval::SubRange &SR : IntB.subranges())
SR.createDeadDef(NewCopyIdx, LIS->getVNInfoAllocator());
// If the newly created Instruction has an address of an instruction that was
// deleted before (object recycled by the allocator) it needs to be removed from
// the deleted list.
ErasedInstrs.erase(NewCopyMI);
} else {
LLVM_DEBUG(dbgs() << "\tremovePartialRedundancy: Remove the copy from "
<< printMBBReference(MBB) << '\t' << CopyMI);
}
// Remove CopyMI.
// Note: This is fine to remove the copy before updating the live-ranges.
// While updating the live-ranges, we only look at slot indices and
// never go back to the instruction.
// Mark instructions as deleted.
deleteInstr(&CopyMI);
// Update the liveness.
SmallVector<SlotIndex, 8> EndPoints;
VNInfo *BValNo = IntB.Query(CopyIdx).valueOutOrDead();
LIS->pruneValue(*static_cast<LiveRange *>(&IntB), CopyIdx.getRegSlot(),
&EndPoints);
BValNo->markUnused();
// Extend IntB to the EndPoints of its original live interval.
LIS->extendToIndices(IntB, EndPoints);
// Now, do the same for its subranges.
for (LiveInterval::SubRange &SR : IntB.subranges()) {
EndPoints.clear();
VNInfo *BValNo = SR.Query(CopyIdx).valueOutOrDead();
assert(BValNo && "All sublanes should be live");
LIS->pruneValue(SR, CopyIdx.getRegSlot(), &EndPoints);
BValNo->markUnused();
LIS->extendToIndices(SR, EndPoints);
}
// If any dead defs were extended, truncate them.
shrinkToUses(&IntB);
// Finally, update the live-range of IntA.
shrinkToUses(&IntA);
return true;
}
/// Returns true if @p MI defines the full vreg @p Reg, as opposed to just
/// defining a subregister.
static bool definesFullReg(const MachineInstr &MI, unsigned Reg) {
assert(!TargetRegisterInfo::isPhysicalRegister(Reg) &&
"This code cannot handle physreg aliasing");
for (const MachineOperand &Op : MI.operands()) {
if (!Op.isReg() || !Op.isDef() || Op.getReg() != Reg)
continue;
// Return true if we define the full register or don't care about the value
// inside other subregisters.
if (Op.getSubReg() == 0 || Op.isUndef())
return true;
}
return false;
}
bool RegisterCoalescer::reMaterializeTrivialDef(const CoalescerPair &CP,
MachineInstr *CopyMI,
bool &IsDefCopy) {
IsDefCopy = false;
unsigned SrcReg = CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg();
unsigned SrcIdx = CP.isFlipped() ? CP.getDstIdx() : CP.getSrcIdx();
unsigned DstReg = CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg();
unsigned DstIdx = CP.isFlipped() ? CP.getSrcIdx() : CP.getDstIdx();
if (TargetRegisterInfo::isPhysicalRegister(SrcReg))
return false;
LiveInterval &SrcInt = LIS->getInterval(SrcReg);
SlotIndex CopyIdx = LIS->getInstructionIndex(*CopyMI);
VNInfo *ValNo = SrcInt.Query(CopyIdx).valueIn();
assert(ValNo && "CopyMI input register not live");
if (ValNo->isPHIDef() || ValNo->isUnused())
return false;
MachineInstr *DefMI = LIS->getInstructionFromIndex(ValNo->def);
if (!DefMI)
return false;
if (DefMI->isCopyLike()) {
IsDefCopy = true;
return false;
}
if (!TII->isAsCheapAsAMove(*DefMI))
return false;
if (!TII->isTriviallyReMaterializable(*DefMI, AA))
return false;
if (!definesFullReg(*DefMI, SrcReg))
return false;
bool SawStore = false;
if (!DefMI->isSafeToMove(AA, SawStore))
return false;
const MCInstrDesc &MCID = DefMI->getDesc();
if (MCID.getNumDefs() != 1)
return false;
// Only support subregister destinations when the def is read-undef.
MachineOperand &DstOperand = CopyMI->getOperand(0);
unsigned CopyDstReg = DstOperand.getReg();
if (DstOperand.getSubReg() && !DstOperand.isUndef())
return false;
// If both SrcIdx and DstIdx are set, correct rematerialization would widen
// the register substantially (beyond both source and dest size). This is bad
// for performance since it can cascade through a function, introducing many
// extra spills and fills (e.g. ARM can easily end up copying QQQQPR registers
// around after a few subreg copies).
if (SrcIdx && DstIdx)
return false;
const TargetRegisterClass *DefRC = TII->getRegClass(MCID, 0, TRI, *MF);
if (!DefMI->isImplicitDef()) {
if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
unsigned NewDstReg = DstReg;
unsigned NewDstIdx = TRI->composeSubRegIndices(CP.getSrcIdx(),
DefMI->getOperand(0).getSubReg());
if (NewDstIdx)
NewDstReg = TRI->getSubReg(DstReg, NewDstIdx);
// Finally, make sure that the physical subregister that will be
// constructed later is permitted for the instruction.
if (!DefRC->contains(NewDstReg))
return false;
} else {
// Theoretically, some stack frame reference could exist. Just make sure
// it hasn't actually happened.
assert(TargetRegisterInfo::isVirtualRegister(DstReg) &&
"Only expect to deal with virtual or physical registers");
}
}
DebugLoc DL = CopyMI->getDebugLoc();
MachineBasicBlock *MBB = CopyMI->getParent();
MachineBasicBlock::iterator MII =
std::next(MachineBasicBlock::iterator(CopyMI));
TII->reMaterialize(*MBB, MII, DstReg, SrcIdx, *DefMI, *TRI);
MachineInstr &NewMI = *std::prev(MII);
NewMI.setDebugLoc(DL);
// In a situation like the following:
// %0:subreg = instr ; DefMI, subreg = DstIdx
// %1 = copy %0:subreg ; CopyMI, SrcIdx = 0
// instead of widening %1 to the register class of %0 simply do:
// %1 = instr
const TargetRegisterClass *NewRC = CP.getNewRC();
if (DstIdx != 0) {
MachineOperand &DefMO = NewMI.getOperand(0);
if (DefMO.getSubReg() == DstIdx) {
assert(SrcIdx == 0 && CP.isFlipped()
&& "Shouldn't have SrcIdx+DstIdx at this point");
const TargetRegisterClass *DstRC = MRI->getRegClass(DstReg);
const TargetRegisterClass *CommonRC =
TRI->getCommonSubClass(DefRC, DstRC);
if (CommonRC != nullptr) {
NewRC = CommonRC;
DstIdx = 0;
DefMO.setSubReg(0);
DefMO.setIsUndef(false); // Only subregs can have def+undef.
}
}
}
// CopyMI may have implicit operands, save them so that we can transfer them
// over to the newly materialized instruction after CopyMI is removed.
SmallVector<MachineOperand, 4> ImplicitOps;
ImplicitOps.reserve(CopyMI->getNumOperands() -
CopyMI->getDesc().getNumOperands());
for (unsigned I = CopyMI->getDesc().getNumOperands(),
E = CopyMI->getNumOperands();
I != E; ++I) {
MachineOperand &MO = CopyMI->getOperand(I);
if (MO.isReg()) {
assert(MO.isImplicit() && "No explicit operands after implicit operands.");
// Discard VReg implicit defs.
if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
ImplicitOps.push_back(MO);
}
}
LIS->ReplaceMachineInstrInMaps(*CopyMI, NewMI);
CopyMI->eraseFromParent();
ErasedInstrs.insert(CopyMI);
// NewMI may have dead implicit defs (E.g. EFLAGS for MOV<bits>r0 on X86).
// We need to remember these so we can add intervals once we insert
// NewMI into SlotIndexes.
SmallVector<unsigned, 4> NewMIImplDefs;
for (unsigned i = NewMI.getDesc().getNumOperands(),
e = NewMI.getNumOperands();
i != e; ++i) {
MachineOperand &MO = NewMI.getOperand(i);
if (MO.isReg() && MO.isDef()) {
assert(MO.isImplicit() && MO.isDead() &&
TargetRegisterInfo::isPhysicalRegister(MO.getReg()));
NewMIImplDefs.push_back(MO.getReg());
}
}
if (TargetRegisterInfo::isVirtualRegister(DstReg)) {
unsigned NewIdx = NewMI.getOperand(0).getSubReg();
if (DefRC != nullptr) {
if (NewIdx)
NewRC = TRI->getMatchingSuperRegClass(NewRC, DefRC, NewIdx);
else
NewRC = TRI->getCommonSubClass(NewRC, DefRC);
assert(NewRC && "subreg chosen for remat incompatible with instruction");
}
// Remap subranges to new lanemask and change register class.
LiveInterval &DstInt = LIS->getInterval(DstReg);
for (LiveInterval::SubRange &SR : DstInt.subranges()) {
SR.LaneMask = TRI->composeSubRegIndexLaneMask(DstIdx, SR.LaneMask);
}
MRI->setRegClass(DstReg, NewRC);
// Update machine operands and add flags.
updateRegDefsUses(DstReg, DstReg, DstIdx);
NewMI.getOperand(0).setSubReg(NewIdx);
// updateRegDefUses can add an "undef" flag to the definition, since
// it will replace DstReg with DstReg.DstIdx. If NewIdx is 0, make
// sure that "undef" is not set.
if (NewIdx == 0)
NewMI.getOperand(0).setIsUndef(false);
// Add dead subregister definitions if we are defining the whole register
// but only part of it is live.
// This could happen if the rematerialization instruction is rematerializing
// more than actually is used in the register.
// An example would be:
// %1 = LOAD CONSTANTS 5, 8 ; Loading both 5 and 8 in different subregs
// ; Copying only part of the register here, but the rest is undef.
// %2:sub_16bit<def, read-undef> = COPY %1:sub_16bit
// ==>
// ; Materialize all the constants but only using one
// %2 = LOAD_CONSTANTS 5, 8
//
// at this point for the part that wasn't defined before we could have
// subranges missing the definition.
if (NewIdx == 0 && DstInt.hasSubRanges()) {
SlotIndex CurrIdx = LIS->getInstructionIndex(NewMI);
SlotIndex DefIndex =
CurrIdx.getRegSlot(NewMI.getOperand(0).isEarlyClobber());
LaneBitmask MaxMask = MRI->getMaxLaneMaskForVReg(DstReg);
VNInfo::Allocator& Alloc = LIS->getVNInfoAllocator();
for (LiveInterval::SubRange &SR : DstInt.subranges()) {
if (!SR.liveAt(DefIndex))
SR.createDeadDef(DefIndex, Alloc);
MaxMask &= ~SR.LaneMask;
}
if (MaxMask.any()) {
LiveInterval::SubRange *SR = DstInt.createSubRange(Alloc, MaxMask);
SR->createDeadDef(DefIndex, Alloc);
}
}
// Make sure that the subrange for resultant undef is removed
// For example:
// %1:sub1<def,read-undef> = LOAD CONSTANT 1
// %2 = COPY %1
// ==>
// %2:sub1<def, read-undef> = LOAD CONSTANT 1
// ; Correct but need to remove the subrange for %2:sub0
// ; as it is now undef
if (NewIdx != 0 && DstInt.hasSubRanges()) {
// The affected subregister segments can be removed.
SlotIndex CurrIdx = LIS->getInstructionIndex(NewMI);
LaneBitmask DstMask = TRI->getSubRegIndexLaneMask(NewIdx);
bool UpdatedSubRanges = false;
for (LiveInterval::SubRange &SR : DstInt.subranges()) {
if ((SR.LaneMask & DstMask).none()) {
LLVM_DEBUG(dbgs()
<< "Removing undefined SubRange "
<< PrintLaneMask(SR.LaneMask) << " : " << SR << "\n");
// VNI is in ValNo - remove any segments in this SubRange that have this ValNo
if (VNInfo *RmValNo = SR.getVNInfoAt(CurrIdx.getRegSlot())) {
SR.removeValNo(RmValNo);
UpdatedSubRanges = true;
}
}
}
if (UpdatedSubRanges)
DstInt.removeEmptySubRanges();
}
} else if (NewMI.getOperand(0).getReg() != CopyDstReg) {
// The New instruction may be defining a sub-register of what's actually
// been asked for. If so it must implicitly define the whole thing.
assert(TargetRegisterInfo::isPhysicalRegister(DstReg) &&
"Only expect virtual or physical registers in remat");
NewMI.getOperand(0).setIsDead(true);
NewMI.addOperand(MachineOperand::CreateReg(
CopyDstReg, true /*IsDef*/, true /*IsImp*/, false /*IsKill*/));
// Record small dead def live-ranges for all the subregisters
// of the destination register.
// Otherwise, variables that live through may miss some
// interferences, thus creating invalid allocation.
// E.g., i386 code:
// %1 = somedef ; %1 GR8
// %2 = remat ; %2 GR32
// CL = COPY %2.sub_8bit
// = somedef %1 ; %1 GR8
// =>
// %1 = somedef ; %1 GR8
// dead ECX = remat ; implicit-def CL
// = somedef %1 ; %1 GR8
// %1 will see the interferences with CL but not with CH since
// no live-ranges would have been created for ECX.
// Fix that!
SlotIndex NewMIIdx = LIS->getInstructionIndex(NewMI);
for (MCRegUnitIterator Units(NewMI.getOperand(0).getReg(), TRI);
Units.isValid(); ++Units)
if (LiveRange *LR = LIS->getCachedRegUnit(*Units))
LR->createDeadDef(NewMIIdx.getRegSlot(), LIS->getVNInfoAllocator());
}
if (NewMI.getOperand(0).getSubReg())
NewMI.getOperand(0).setIsUndef();
// Transfer over implicit operands to the rematerialized instruction.
for (MachineOperand &MO : ImplicitOps)
NewMI.addOperand(MO);
SlotIndex NewMIIdx = LIS->getInstructionIndex(NewMI);
for (unsigned i = 0, e = NewMIImplDefs.size(); i != e; ++i) {
unsigned Reg = NewMIImplDefs[i];
for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
if (LiveRange *LR = LIS->getCachedRegUnit(*Units))
LR->createDeadDef(NewMIIdx.getRegSlot(), LIS->getVNInfoAllocator());
}
LLVM_DEBUG(dbgs() << "Remat: " << NewMI);
++NumReMats;
// The source interval can become smaller because we removed a use.
shrinkToUses(&SrcInt, &DeadDefs);
if (!DeadDefs.empty()) {
// If the virtual SrcReg is completely eliminated, update all DBG_VALUEs
// to describe DstReg instead.
for (MachineOperand &UseMO : MRI->use_operands(SrcReg)) {
MachineInstr *UseMI = UseMO.getParent();
if (UseMI->isDebugValue()) {
UseMO.setReg(DstReg);
// Move the debug value directly after the def of the rematerialized
// value in DstReg.
MBB->splice(std::next(NewMI.getIterator()), UseMI->getParent(), UseMI);
LLVM_DEBUG(dbgs() << "\t\tupdated: " << *UseMI);
}
}
eliminateDeadDefs();
}
return true;
}
MachineInstr *RegisterCoalescer::eliminateUndefCopy(MachineInstr *CopyMI) {
// ProcessImplicitDefs may leave some copies of <undef> values, it only
// removes local variables. When we have a copy like:
//
// %1 = COPY undef %2
//
// We delete the copy and remove the corresponding value number from %1.
// Any uses of that value number are marked as <undef>.
// Note that we do not query CoalescerPair here but redo isMoveInstr as the
// CoalescerPair may have a new register class with adjusted subreg indices
// at this point.
unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
isMoveInstr(*TRI, CopyMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx);
SlotIndex Idx = LIS->getInstructionIndex(*CopyMI);
const LiveInterval &SrcLI = LIS->getInterval(SrcReg);
// CopyMI is undef iff SrcReg is not live before the instruction.
if (SrcSubIdx != 0 && SrcLI.hasSubRanges()) {
LaneBitmask SrcMask = TRI->getSubRegIndexLaneMask(SrcSubIdx);
for (const LiveInterval::SubRange &SR : SrcLI.subranges()) {
if ((SR.LaneMask & SrcMask).none())
continue;
if (SR.liveAt(Idx))
return nullptr;
}
} else if (SrcLI.liveAt(Idx))
return nullptr;
// If the undef copy defines a live-out value (i.e. an input to a PHI def),
// then replace it with an IMPLICIT_DEF.
LiveInterval &DstLI = LIS->getInterval(DstReg);
SlotIndex RegIndex = Idx.getRegSlot();
LiveRange::Segment *Seg = DstLI.getSegmentContaining(RegIndex);
assert(Seg != nullptr && "No segment for defining instruction");
if (VNInfo *V = DstLI.getVNInfoAt(Seg->end)) {
if (V->isPHIDef()) {
CopyMI->setDesc(TII->get(TargetOpcode::IMPLICIT_DEF));
for (unsigned i = CopyMI->getNumOperands(); i != 0; --i) {
MachineOperand &MO = CopyMI->getOperand(i-1);
if (MO.isReg() && MO.isUse())
CopyMI->RemoveOperand(i-1);
}
LLVM_DEBUG(dbgs() << "\tReplaced copy of <undef> value with an "
"implicit def\n");
return CopyMI;
}
}
// Remove any DstReg segments starting at the instruction.
LLVM_DEBUG(dbgs() << "\tEliminating copy of <undef> value\n");
// Remove value or merge with previous one in case of a subregister def.
if (VNInfo *PrevVNI = DstLI.getVNInfoAt(Idx)) {
VNInfo *VNI = DstLI.getVNInfoAt(RegIndex);
DstLI.MergeValueNumberInto(VNI, PrevVNI);
// The affected subregister segments can be removed.
LaneBitmask DstMask = TRI->getSubRegIndexLaneMask(DstSubIdx);
for (LiveInterval::SubRange &SR : DstLI.subranges()) {
if ((SR.LaneMask & DstMask).none())
continue;
VNInfo *SVNI = SR.getVNInfoAt(RegIndex);
assert(SVNI != nullptr && SlotIndex::isSameInstr(SVNI->def, RegIndex));
SR.removeValNo(SVNI);
}
DstLI.removeEmptySubRanges();
} else
LIS->removeVRegDefAt(DstLI, RegIndex);
// Mark uses as undef.
for (MachineOperand &MO : MRI->reg_nodbg_operands(DstReg)) {
if (MO.isDef() /*|| MO.isUndef()*/)
continue;
const MachineInstr &MI = *MO.getParent();
SlotIndex UseIdx = LIS->getInstructionIndex(MI);
LaneBitmask UseMask = TRI->getSubRegIndexLaneMask(MO.getSubReg());
bool isLive;
if (!UseMask.all() && DstLI.hasSubRanges()) {
isLive = false;
for (const LiveInterval::SubRange &SR : DstLI.subranges()) {
if ((SR.LaneMask & UseMask).none())
continue;
if (SR.liveAt(UseIdx)) {
isLive = true;
break;
}
}
} else
isLive = DstLI.liveAt(UseIdx);
if (isLive)
continue;
MO.setIsUndef(true);
LLVM_DEBUG(dbgs() << "\tnew undef: " << UseIdx << '\t' << MI);
}
// A def of a subregister may be a use of the other subregisters, so
// deleting a def of a subregister may also remove uses. Since CopyMI
// is still part of the function (but about to be erased), mark all
// defs of DstReg in it as <undef>, so that shrinkToUses would
// ignore them.
for (MachineOperand &MO : CopyMI->operands())
if (MO.isReg() && MO.isDef() && MO.getReg() == DstReg)
MO.setIsUndef(true);
LIS->shrinkToUses(&DstLI);
return CopyMI;
}
void RegisterCoalescer::addUndefFlag(const LiveInterval &Int, SlotIndex UseIdx,
MachineOperand &MO, unsigned SubRegIdx) {
LaneBitmask Mask = TRI->getSubRegIndexLaneMask(SubRegIdx);
if (MO.isDef())
Mask = ~Mask;
bool IsUndef = true;
for (const LiveInterval::SubRange &S : Int.subranges()) {
if ((S.LaneMask & Mask).none())
continue;
if (S.liveAt(UseIdx)) {
IsUndef = false;
break;
}
}
if (IsUndef) {
MO.setIsUndef(true);
// We found out some subregister use is actually reading an undefined
// value. In some cases the whole vreg has become undefined at this
// point so we have to potentially shrink the main range if the
// use was ending a live segment there.
LiveQueryResult Q = Int.Query(UseIdx);
if (Q.valueOut() == nullptr)
ShrinkMainRange = true;
}
}
void RegisterCoalescer::updateRegDefsUses(unsigned SrcReg,
unsigned DstReg,
unsigned SubIdx) {
bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
LiveInterval *DstInt = DstIsPhys ? nullptr : &LIS->getInterval(DstReg);
if (DstInt && DstInt->hasSubRanges() && DstReg != SrcReg) {
for (MachineOperand &MO : MRI->reg_operands(DstReg)) {
unsigned SubReg = MO.getSubReg();
if (SubReg == 0 || MO.isUndef())
continue;
MachineInstr &MI = *MO.getParent();
if (MI.isDebugValue())
continue;
SlotIndex UseIdx = LIS->getInstructionIndex(MI).getRegSlot(true);
addUndefFlag(*DstInt, UseIdx, MO, SubReg);
}
}
SmallPtrSet<MachineInstr*, 8> Visited;
for (MachineRegisterInfo::reg_instr_iterator
I = MRI->reg_instr_begin(SrcReg), E = MRI->reg_instr_end();
I != E; ) {
MachineInstr *UseMI = &*(I++);
// Each instruction can only be rewritten once because sub-register
// composition is not always idempotent. When SrcReg != DstReg, rewriting
// the UseMI operands removes them from the SrcReg use-def chain, but when
// SrcReg is DstReg we could encounter UseMI twice if it has multiple
// operands mentioning the virtual register.
if (SrcReg == DstReg && !Visited.insert(UseMI).second)
continue;
SmallVector<unsigned,8> Ops;
bool Reads, Writes;
std::tie(Reads, Writes) = UseMI->readsWritesVirtualRegister(SrcReg, &Ops);
// If SrcReg wasn't read, it may still be the case that DstReg is live-in
// because SrcReg is a sub-register.
if (DstInt && !Reads && SubIdx && !UseMI->isDebugValue())
Reads = DstInt->liveAt(LIS->getInstructionIndex(*UseMI));
// Replace SrcReg with DstReg in all UseMI operands.
for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
MachineOperand &MO = UseMI->getOperand(Ops[i]);
// Adjust <undef> flags in case of sub-register joins. We don't want to
// turn a full def into a read-modify-write sub-register def and vice
// versa.
if (SubIdx && MO.isDef())
MO.setIsUndef(!Reads);
// A subreg use of a partially undef (super) register may be a complete
// undef use now and then has to be marked that way.
if (SubIdx != 0 && MO.isUse() && MRI->shouldTrackSubRegLiveness(DstReg)) {
if (!DstInt->hasSubRanges()) {
BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator();
LaneBitmask Mask = MRI->getMaxLaneMaskForVReg(DstInt->reg);
DstInt->createSubRangeFrom(Allocator, Mask, *DstInt);
}
SlotIndex MIIdx = UseMI->isDebugValue()
? LIS->getSlotIndexes()->getIndexBefore(*UseMI)
: LIS->getInstructionIndex(*UseMI);
SlotIndex UseIdx = MIIdx.getRegSlot(true);
addUndefFlag(*DstInt, UseIdx, MO, SubIdx);
}
if (DstIsPhys)
MO.substPhysReg(DstReg, *TRI);
else
MO.substVirtReg(DstReg, SubIdx, *TRI);
}
LLVM_DEBUG({
dbgs() << "\t\tupdated: ";
if (!UseMI->isDebugValue())
dbgs() << LIS->getInstructionIndex(*UseMI) << "\t";
dbgs() << *UseMI;
});
}
}
bool RegisterCoalescer::canJoinPhys(const CoalescerPair &CP) {
// Always join simple intervals that are defined by a single copy from a
// reserved register. This doesn't increase register pressure, so it is
// always beneficial.
if (!MRI->isReserved(CP.getDstReg())) {
LLVM_DEBUG(dbgs() << "\tCan only merge into reserved registers.\n");
return false;
}
LiveInterval &JoinVInt = LIS->getInterval(CP.getSrcReg());
if (JoinVInt.containsOneValue())
return true;
LLVM_DEBUG(
dbgs() << "\tCannot join complex intervals into reserved register.\n");
return false;
}
bool RegisterCoalescer::joinCopy(MachineInstr *CopyMI, bool &Again) {
Again = false;
LLVM_DEBUG(dbgs() << LIS->getInstructionIndex(*CopyMI) << '\t' << *CopyMI);
CoalescerPair CP(*TRI);
if (!CP.setRegisters(CopyMI)) {
LLVM_DEBUG(dbgs() << "\tNot coalescable.\n");
return false;
}
if (CP.getNewRC()) {
auto SrcRC = MRI->getRegClass(CP.getSrcReg());
auto DstRC = MRI->getRegClass(CP.getDstReg());
unsigned SrcIdx = CP.getSrcIdx();
unsigned DstIdx = CP.getDstIdx();
if (CP.isFlipped()) {
std::swap(SrcIdx, DstIdx);
std::swap(SrcRC, DstRC);
}
if (!TRI->shouldCoalesce(CopyMI, SrcRC, SrcIdx, DstRC, DstIdx,
CP.getNewRC(), *LIS)) {
LLVM_DEBUG(dbgs() << "\tSubtarget bailed on coalescing.\n");
return false;
}
}
// Dead code elimination. This really should be handled by MachineDCE, but
// sometimes dead copies slip through, and we can't generate invalid live
// ranges.
if (!CP.isPhys() && CopyMI->allDefsAreDead()) {
LLVM_DEBUG(dbgs() << "\tCopy is dead.\n");
DeadDefs.push_back(CopyMI);
eliminateDeadDefs();
return true;
}
// Eliminate undefs.
if (!CP.isPhys()) {
// If this is an IMPLICIT_DEF, leave it alone, but don't try to coalesce.
if (MachineInstr *UndefMI = eliminateUndefCopy(CopyMI)) {
if (UndefMI->isImplicitDef())
return false;
deleteInstr(CopyMI);
return false; // Not coalescable.
}
}
// Coalesced copies are normally removed immediately, but transformations
// like removeCopyByCommutingDef() can inadvertently create identity copies.
// When that happens, just join the values and remove the copy.
if (CP.getSrcReg() == CP.getDstReg()) {
LiveInterval &LI = LIS->getInterval(CP.getSrcReg());
LLVM_DEBUG(dbgs() << "\tCopy already coalesced: " << LI << '\n');
const SlotIndex CopyIdx = LIS->getInstructionIndex(*CopyMI);
LiveQueryResult LRQ = LI.Query(CopyIdx);
if (VNInfo *DefVNI = LRQ.valueDefined()) {
VNInfo *ReadVNI = LRQ.valueIn();
assert(ReadVNI && "No value before copy and no <undef> flag.");
assert(ReadVNI != DefVNI && "Cannot read and define the same value.");
LI.MergeValueNumberInto(DefVNI, ReadVNI);
// Process subregister liveranges.
for (LiveInterval::SubRange &S : LI.subranges()) {
LiveQueryResult SLRQ = S.Query(CopyIdx);
if (VNInfo *SDefVNI = SLRQ.valueDefined()) {
VNInfo *SReadVNI = SLRQ.valueIn();
S.MergeValueNumberInto(SDefVNI, SReadVNI);
}
}
LLVM_DEBUG(dbgs() << "\tMerged values: " << LI << '\n');
}
deleteInstr(CopyMI);
return true;
}
// Enforce policies.
if (CP.isPhys()) {
LLVM_DEBUG(dbgs() << "\tConsidering merging "
<< printReg(CP.getSrcReg(), TRI) << " with "
<< printReg(CP.getDstReg(), TRI, CP.getSrcIdx()) << '\n');
if (!canJoinPhys(CP)) {
// Before giving up coalescing, if definition of source is defined by
// trivial computation, try rematerializing it.
bool IsDefCopy;
if (reMaterializeTrivialDef(CP, CopyMI, IsDefCopy))
return true;
if (IsDefCopy)
Again = true; // May be possible to coalesce later.
return false;
}
} else {
// When possible, let DstReg be the larger interval.
if (!CP.isPartial() && LIS->getInterval(CP.getSrcReg()).size() >
LIS->getInterval(CP.getDstReg()).size())
CP.flip();
LLVM_DEBUG({
dbgs() << "\tConsidering merging to "
<< TRI->getRegClassName(CP.getNewRC()) << " with ";
if (CP.getDstIdx() && CP.getSrcIdx())
dbgs() << printReg(CP.getDstReg()) << " in "
<< TRI->getSubRegIndexName(CP.getDstIdx()) << " and "
<< printReg(CP.getSrcReg()) << " in "
<< TRI->getSubRegIndexName(CP.getSrcIdx()) << '\n';
else
dbgs() << printReg(CP.getSrcReg(), TRI) << " in "
<< printReg(CP.getDstReg(), TRI, CP.getSrcIdx()) << '\n';
});
}
ShrinkMask = LaneBitmask::getNone();
ShrinkMainRange = false;
// Okay, attempt to join these two intervals. On failure, this returns false.
// Otherwise, if one of the intervals being joined is a physreg, this method
// always canonicalizes DstInt to be it. The output "SrcInt" will not have
// been modified, so we can use this information below to update aliases.
if (!joinIntervals(CP)) {
// Coalescing failed.
// If definition of source is defined by trivial computation, try
// rematerializing it.
bool IsDefCopy;
if (reMaterializeTrivialDef(CP, CopyMI, IsDefCopy))
return true;
// If we can eliminate the copy without merging the live segments, do so
// now.
if (!CP.isPartial() && !CP.isPhys()) {
if (adjustCopiesBackFrom(CP, CopyMI) ||
removeCopyByCommutingDef(CP, CopyMI)) {
deleteInstr(CopyMI);
LLVM_DEBUG(dbgs() << "\tTrivial!\n");
return true;
}
}
// Try and see if we can partially eliminate the copy by moving the copy to
// its predecessor.
if (!CP.isPartial() && !CP.isPhys())
if (removePartialRedundancy(CP, *CopyMI))
return true;
// Otherwise, we are unable to join the intervals.
LLVM_DEBUG(dbgs() << "\tInterference!\n");
Again = true; // May be possible to coalesce later.
return false;
}
// Coalescing to a virtual register that is of a sub-register class of the
// other. Make sure the resulting register is set to the right register class.
if (CP.isCrossClass()) {
++numCrossRCs;
MRI->setRegClass(CP.getDstReg(), CP.getNewRC());
}
// Removing sub-register copies can ease the register class constraints.
// Make sure we attempt to inflate the register class of DstReg.
if (!CP.isPhys() && RegClassInfo.isProperSubClass(CP.getNewRC()))
InflateRegs.push_back(CP.getDstReg());
// CopyMI has been erased by joinIntervals at this point. Remove it from
// ErasedInstrs since copyCoalesceWorkList() won't add a successful join back
// to the work list. This keeps ErasedInstrs from growing needlessly.
ErasedInstrs.erase(CopyMI);
// Rewrite all SrcReg operands to DstReg.
// Also update DstReg operands to include DstIdx if it is set.
if (CP.getDstIdx())
updateRegDefsUses(CP.getDstReg(), CP.getDstReg(), CP.getDstIdx());
updateRegDefsUses(CP.getSrcReg(), CP.getDstReg(), CP.getSrcIdx());
// Shrink subregister ranges if necessary.
if (ShrinkMask.any()) {
LiveInterval &LI = LIS->getInterval(CP.getDstReg());
for (LiveInterval::SubRange &S : LI.subranges()) {
if ((S.LaneMask & ShrinkMask).none())
continue;
LLVM_DEBUG(dbgs() << "Shrink LaneUses (Lane " << PrintLaneMask(S.LaneMask)
<< ")\n");
LIS->shrinkToUses(S, LI.reg);
}
LI.removeEmptySubRanges();
}
if (ShrinkMainRange) {
LiveInterval &LI = LIS->getInterval(CP.getDstReg());
shrinkToUses(&LI);
}
// SrcReg is guaranteed to be the register whose live interval that is
// being merged.
LIS->removeInterval(CP.getSrcReg());
// Update regalloc hint.
TRI->updateRegAllocHint(CP.getSrcReg(), CP.getDstReg(), *MF);
LLVM_DEBUG({
dbgs() << "\tSuccess: " << printReg(CP.getSrcReg(), TRI, CP.getSrcIdx())
<< " -> " << printReg(CP.getDstReg(), TRI, CP.getDstIdx()) << '\n';
dbgs() << "\tResult = ";
if (CP.isPhys())
dbgs() << printReg(CP.getDstReg(), TRI);
else
dbgs() << LIS->getInterval(CP.getDstReg());
dbgs() << '\n';
});
++numJoins;
return true;
}
bool RegisterCoalescer::joinReservedPhysReg(CoalescerPair &CP) {
unsigned DstReg = CP.getDstReg();
unsigned SrcReg = CP.getSrcReg();
assert(CP.isPhys() && "Must be a physreg copy");
assert(MRI->isReserved(DstReg) && "Not a reserved register");
LiveInterval &RHS = LIS->getInterval(SrcReg);
LLVM_DEBUG(dbgs() << "\t\tRHS = " << RHS << '\n');
assert(RHS.containsOneValue() && "Invalid join with reserved register");
// Optimization for reserved registers like ESP. We can only merge with a
// reserved physreg if RHS has a single value that is a copy of DstReg.
// The live range of the reserved register will look like a set of dead defs
// - we don't properly track the live range of reserved registers.
// Deny any overlapping intervals. This depends on all the reserved
// register live ranges to look like dead defs.
if (!MRI->isConstantPhysReg(DstReg)) {
for (MCRegUnitIterator UI(DstReg, TRI); UI.isValid(); ++UI) {
// Abort if not all the regunits are reserved.
for (MCRegUnitRootIterator RI(*UI, TRI); RI.isValid(); ++RI) {
if (!MRI->isReserved(*RI))
return false;
}
if (RHS.overlaps(LIS->getRegUnit(*UI))) {
LLVM_DEBUG(dbgs() << "\t\tInterference: " << printRegUnit(*UI, TRI)
<< '\n');
return false;
}
}
// We must also check for overlaps with regmask clobbers.
BitVector RegMaskUsable;
if (LIS->checkRegMaskInterference(RHS, RegMaskUsable) &&
!RegMaskUsable.test(DstReg)) {
LLVM_DEBUG(dbgs() << "\t\tRegMask interference\n");
return false;
}
}
// Skip any value computations, we are not adding new values to the
// reserved register. Also skip merging the live ranges, the reserved
// register live range doesn't need to be accurate as long as all the
// defs are there.
// Delete the identity copy.
MachineInstr *CopyMI;
if (CP.isFlipped()) {
// Physreg is copied into vreg
// %y = COPY %physreg_x
// ... //< no other def of %x here
// use %y
// =>
// ...
// use %x
CopyMI = MRI->getVRegDef(SrcReg);
} else {
// VReg is copied into physreg:
// %y = def
// ... //< no other def or use of %y here
// %y = COPY %physreg_x
// =>
// %y = def
// ...
if (!MRI->hasOneNonDBGUse(SrcReg)) {
LLVM_DEBUG(dbgs() << "\t\tMultiple vreg uses!\n");
return false;
}
if (!LIS->intervalIsInOneMBB(RHS)) {
LLVM_DEBUG(dbgs() << "\t\tComplex control flow!\n");
return false;
}
MachineInstr &DestMI = *MRI->getVRegDef(SrcReg);
CopyMI = &*MRI->use_instr_nodbg_begin(SrcReg);
SlotIndex CopyRegIdx = LIS->getInstructionIndex(*CopyMI).getRegSlot();
SlotIndex DestRegIdx = LIS->getInstructionIndex(DestMI).getRegSlot();
if (!MRI->isConstantPhysReg(DstReg)) {
// We checked above that there are no interfering defs of the physical
// register. However, for this case, where we intend to move up the def of
// the physical register, we also need to check for interfering uses.
SlotIndexes *Indexes = LIS->getSlotIndexes();
for (SlotIndex SI = Indexes->getNextNonNullIndex(DestRegIdx);
SI != CopyRegIdx; SI = Indexes->getNextNonNullIndex(SI)) {
MachineInstr *MI = LIS->getInstructionFromIndex(SI);
if (MI->readsRegister(DstReg, TRI)) {
LLVM_DEBUG(dbgs() << "\t\tInterference (read): " << *MI);
return false;
}
}
}
// We're going to remove the copy which defines a physical reserved
// register, so remove its valno, etc.
LLVM_DEBUG(dbgs() << "\t\tRemoving phys reg def of "
<< printReg(DstReg, TRI) << " at " << CopyRegIdx << "\n");
LIS->removePhysRegDefAt(DstReg, CopyRegIdx);
// Create a new dead def at the new def location.
for (MCRegUnitIterator UI(DstReg, TRI); UI.isValid(); ++UI) {
LiveRange &LR = LIS->getRegUnit(*UI);
LR.createDeadDef(DestRegIdx, LIS->getVNInfoAllocator());
}
}
deleteInstr(CopyMI);
// We don't track kills for reserved registers.
MRI->clearKillFlags(CP.getSrcReg());
return true;
}
//===----------------------------------------------------------------------===//
// Interference checking and interval joining
//===----------------------------------------------------------------------===//
//
// In the easiest case, the two live ranges being joined are disjoint, and
// there is no interference to consider. It is quite common, though, to have
// overlapping live ranges, and we need to check if the interference can be
// resolved.
//
// The live range of a single SSA value forms a sub-tree of the dominator tree.
// This means that two SSA values overlap if and only if the def of one value
// is contained in the live range of the other value. As a special case, the
// overlapping values can be defined at the same index.
//
// The interference from an overlapping def can be resolved in these cases:
//
// 1. Coalescable copies. The value is defined by a copy that would become an
// identity copy after joining SrcReg and DstReg. The copy instruction will
// be removed, and the value will be merged with the source value.
//
// There can be several copies back and forth, causing many values to be
// merged into one. We compute a list of ultimate values in the joined live
// range as well as a mappings from the old value numbers.
//
// 2. IMPLICIT_DEF. This instruction is only inserted to ensure all PHI
// predecessors have a live out value. It doesn't cause real interference,
// and can be merged into the value it overlaps. Like a coalescable copy, it
// can be erased after joining.
//
// 3. Copy of external value. The overlapping def may be a copy of a value that
// is already in the other register. This is like a coalescable copy, but
// the live range of the source register must be trimmed after erasing the
// copy instruction:
//
// %src = COPY %ext
// %dst = COPY %ext <-- Remove this COPY, trim the live range of %ext.
//
// 4. Clobbering undefined lanes. Vector registers are sometimes built by
// defining one lane at a time:
//
// %dst:ssub0<def,read-undef> = FOO
// %src = BAR
// %dst:ssub1 = COPY %src
//
// The live range of %src overlaps the %dst value defined by FOO, but
// merging %src into %dst:ssub1 is only going to clobber the ssub1 lane
// which was undef anyway.
//
// The value mapping is more complicated in this case. The final live range
// will have different value numbers for both FOO and BAR, but there is no
// simple mapping from old to new values. It may even be necessary to add
// new PHI values.
//
// 5. Clobbering dead lanes. A def may clobber a lane of a vector register that
// is live, but never read. This can happen because we don't compute
// individual live ranges per lane.
//
// %dst = FOO
// %src = BAR
// %dst:ssub1 = COPY %src
//
// This kind of interference is only resolved locally. If the clobbered
// lane value escapes the block, the join is aborted.
namespace {
/// Track information about values in a single virtual register about to be
/// joined. Objects of this class are always created in pairs - one for each
/// side of the CoalescerPair (or one for each lane of a side of the coalescer
/// pair)
class JoinVals {
/// Live range we work on.
LiveRange &LR;
/// (Main) register we work on.
const unsigned Reg;
/// Reg (and therefore the values in this liverange) will end up as
/// subregister SubIdx in the coalesced register. Either CP.DstIdx or
/// CP.SrcIdx.
const unsigned SubIdx;
/// The LaneMask that this liverange will occupy the coalesced register. May
/// be smaller than the lanemask produced by SubIdx when merging subranges.
const LaneBitmask LaneMask;
/// This is true when joining sub register ranges, false when joining main
/// ranges.
const bool SubRangeJoin;
/// Whether the current LiveInterval tracks subregister liveness.
const bool TrackSubRegLiveness;
/// Values that will be present in the final live range.
SmallVectorImpl<VNInfo*> &NewVNInfo;
const CoalescerPair &CP;
LiveIntervals *LIS;
SlotIndexes *Indexes;
const TargetRegisterInfo *TRI;
/// Value number assignments. Maps value numbers in LI to entries in
/// NewVNInfo. This is suitable for passing to LiveInterval::join().
SmallVector<int, 8> Assignments;
/// Conflict resolution for overlapping values.
enum ConflictResolution {
/// No overlap, simply keep this value.
CR_Keep,
/// Merge this value into OtherVNI and erase the defining instruction.
/// Used for IMPLICIT_DEF, coalescable copies, and copies from external
/// values.
CR_Erase,
/// Merge this value into OtherVNI but keep the defining instruction.
/// This is for the special case where OtherVNI is defined by the same
/// instruction.
CR_Merge,
/// Keep this value, and have it replace OtherVNI where possible. This
/// complicates value mapping since OtherVNI maps to two different values
/// before and after this def.
/// Used when clobbering undefined or dead lanes.
CR_Replace,
/// Unresolved conflict. Visit later when all values have been mapped.
CR_Unresolved,
/// Unresolvable conflict. Abort the join.
CR_Impossible
};
/// Per-value info for LI. The lane bit masks are all relative to the final
/// joined register, so they can be compared directly between SrcReg and
/// DstReg.
struct Val {
ConflictResolution Resolution = CR_Keep;
/// Lanes written by this def, 0 for unanalyzed values.
LaneBitmask WriteLanes;
/// Lanes with defined values in this register. Other lanes are undef and
/// safe to clobber.
LaneBitmask ValidLanes;
/// Value in LI being redefined by this def.
VNInfo *RedefVNI = nullptr;
/// Value in the other live range that overlaps this def, if any.
VNInfo *OtherVNI = nullptr;
/// Is this value an IMPLICIT_DEF that can be erased?
///
/// IMPLICIT_DEF values should only exist at the end of a basic block that
/// is a predecessor to a phi-value. These IMPLICIT_DEF instructions can be
/// safely erased if they are overlapping a live value in the other live
/// interval.
///
/// Weird control flow graphs and incomplete PHI handling in
/// ProcessImplicitDefs can very rarely create IMPLICIT_DEF values with
/// longer live ranges. Such IMPLICIT_DEF values should be treated like
/// normal values.
bool ErasableImplicitDef = false;
/// True when the live range of this value will be pruned because of an
/// overlapping CR_Replace value in the other live range.
bool Pruned = false;
/// True once Pruned above has been computed.
bool PrunedComputed = false;
/// True if this value is determined to be identical to OtherVNI
/// (in valuesIdentical). This is used with CR_Erase where the erased
/// copy is redundant, i.e. the source value is already the same as
/// the destination. In such cases the subranges need to be updated
/// properly. See comment at pruneSubRegValues for more info.
bool Identical = false;
Val() = default;
bool isAnalyzed() const { return WriteLanes.any(); }
};
/// One entry per value number in LI.
SmallVector<Val, 8> Vals;
/// Compute the bitmask of lanes actually written by DefMI.
/// Set Redef if there are any partial register definitions that depend on the
/// previous value of the register.
LaneBitmask computeWriteLanes(const MachineInstr *DefMI, bool &Redef) const;
/// Find the ultimate value that VNI was copied from.
std::pair<const VNInfo*,unsigned> followCopyChain(const VNInfo *VNI) const;
bool valuesIdentical(VNInfo *Value0, VNInfo *Value1, const JoinVals &Other) const;
/// Analyze ValNo in this live range, and set all fields of Vals[ValNo].
/// Return a conflict resolution when possible, but leave the hard cases as
/// CR_Unresolved.
/// Recursively calls computeAssignment() on this and Other, guaranteeing that
/// both OtherVNI and RedefVNI have been analyzed and mapped before returning.
/// The recursion always goes upwards in the dominator tree, making loops
/// impossible.
ConflictResolution analyzeValue(unsigned ValNo, JoinVals &Other);
/// Compute the value assignment for ValNo in RI.
/// This may be called recursively by analyzeValue(), but never for a ValNo on
/// the stack.
void computeAssignment(unsigned ValNo, JoinVals &Other);
/// Assuming ValNo is going to clobber some valid lanes in Other.LR, compute
/// the extent of the tainted lanes in the block.
///
/// Multiple values in Other.LR can be affected since partial redefinitions
/// can preserve previously tainted lanes.
///
/// 1 %dst = VLOAD <-- Define all lanes in %dst
/// 2 %src = FOO <-- ValNo to be joined with %dst:ssub0
/// 3 %dst:ssub1 = BAR <-- Partial redef doesn't clear taint in ssub0
/// 4 %dst:ssub0 = COPY %src <-- Conflict resolved, ssub0 wasn't read
///
/// For each ValNo in Other that is affected, add an (EndIndex, TaintedLanes)
/// entry to TaintedVals.
///
/// Returns false if the tainted lanes extend beyond the basic block.
bool
taintExtent(unsigned ValNo, LaneBitmask TaintedLanes, JoinVals &Other,
SmallVectorImpl<std::pair<SlotIndex, LaneBitmask>> &TaintExtent);
/// Return true if MI uses any of the given Lanes from Reg.
/// This does not include partial redefinitions of Reg.
bool usesLanes(const MachineInstr &MI, unsigned, unsigned, LaneBitmask) const;
/// Determine if ValNo is a copy of a value number in LR or Other.LR that will
/// be pruned:
///
/// %dst = COPY %src
/// %src = COPY %dst <-- This value to be pruned.
/// %dst = COPY %src <-- This value is a copy of a pruned value.
bool isPrunedValue(unsigned ValNo, JoinVals &Other);
public:
JoinVals(LiveRange &LR, unsigned Reg, unsigned SubIdx, LaneBitmask LaneMask,
SmallVectorImpl<VNInfo*> &newVNInfo, const CoalescerPair &cp,
LiveIntervals *lis, const TargetRegisterInfo *TRI, bool SubRangeJoin,
bool TrackSubRegLiveness)
: LR(LR), Reg(Reg), SubIdx(SubIdx), LaneMask(LaneMask),
SubRangeJoin(SubRangeJoin), TrackSubRegLiveness(TrackSubRegLiveness),
NewVNInfo(newVNInfo), CP(cp), LIS(lis), Indexes(LIS->getSlotIndexes()),
TRI(TRI), Assignments(LR.getNumValNums(), -1), Vals(LR.getNumValNums()) {}
/// Analyze defs in LR and compute a value mapping in NewVNInfo.
/// Returns false if any conflicts were impossible to resolve.
bool mapValues(JoinVals &Other);
/// Try to resolve conflicts that require all values to be mapped.
/// Returns false if any conflicts were impossible to resolve.
bool resolveConflicts(JoinVals &Other);
/// Prune the live range of values in Other.LR where they would conflict with
/// CR_Replace values in LR. Collect end points for restoring the live range
/// after joining.
void pruneValues(JoinVals &Other, SmallVectorImpl<SlotIndex> &EndPoints,
bool changeInstrs);
/// Removes subranges starting at copies that get removed. This sometimes
/// happens when undefined subranges are copied around. These ranges contain
/// no useful information and can be removed.
void pruneSubRegValues(LiveInterval &LI, LaneBitmask &ShrinkMask);
/// Pruning values in subranges can lead to removing segments in these
/// subranges started by IMPLICIT_DEFs. The corresponding segments in
/// the main range also need to be removed. This function will mark
/// the corresponding values in the main range as pruned, so that
/// eraseInstrs can do the final cleanup.
/// The parameter @p LI must be the interval whose main range is the
/// live range LR.
void pruneMainSegments(LiveInterval &LI, bool &ShrinkMainRange);
/// Erase any machine instructions that have been coalesced away.
/// Add erased instructions to ErasedInstrs.
/// Add foreign virtual registers to ShrinkRegs if their live range ended at
/// the erased instrs.
void eraseInstrs(SmallPtrSetImpl<MachineInstr*> &ErasedInstrs,
SmallVectorImpl<unsigned> &ShrinkRegs,
LiveInterval *LI = nullptr);
/// Remove liverange defs at places where implicit defs will be removed.
void removeImplicitDefs();
/// Get the value assignments suitable for passing to LiveInterval::join.
const int *getAssignments() const { return Assignments.data(); }
};
} // end anonymous namespace
LaneBitmask JoinVals::computeWriteLanes(const MachineInstr *DefMI, bool &Redef)
const {
LaneBitmask L;
for (const MachineOperand &MO : DefMI->operands()) {
if (!MO.isReg() || MO.getReg() != Reg || !MO.isDef())
continue;
L |= TRI->getSubRegIndexLaneMask(
TRI->composeSubRegIndices(SubIdx, MO.getSubReg()));
if (MO.readsReg())
Redef = true;
}
return L;
}
std::pair<const VNInfo*, unsigned> JoinVals::followCopyChain(
const VNInfo *VNI) const {
unsigned TrackReg = Reg;
while (!VNI->isPHIDef()) {
SlotIndex Def = VNI->def;
MachineInstr *MI = Indexes->getInstructionFromIndex(Def);
assert(MI && "No defining instruction");
if (!MI->isFullCopy())
return std::make_pair(VNI, TrackReg);
unsigned SrcReg = MI->getOperand(1).getReg();
if (!TargetRegisterInfo::isVirtualRegister(SrcReg))
return std::make_pair(VNI, TrackReg);
const LiveInterval &LI = LIS->getInterval(SrcReg);
const VNInfo *ValueIn;
// No subrange involved.
if (!SubRangeJoin || !LI.hasSubRanges()) {
LiveQueryResult LRQ = LI.Query(Def);
ValueIn = LRQ.valueIn();
} else {
// Query subranges. Ensure that all matching ones take us to the same def
// (allowing some of them to be undef).
ValueIn = nullptr;
for (const LiveInterval::SubRange &S : LI.subranges()) {
// Transform lanemask to a mask in the joined live interval.
LaneBitmask SMask = TRI->composeSubRegIndexLaneMask(SubIdx, S.LaneMask);
if ((SMask & LaneMask).none())
continue;
LiveQueryResult LRQ = S.Query(Def);
if (!ValueIn) {
ValueIn = LRQ.valueIn();
continue;
}
if (LRQ.valueIn() && ValueIn != LRQ.valueIn())
return std::make_pair(VNI, TrackReg);
}
}
if (ValueIn == nullptr) {
// Reaching an undefined value is legitimate, for example:
//
// 1 undef %0.sub1 = ... ;; %0.sub0 == undef
// 2 %1 = COPY %0 ;; %1 is defined here.
// 3 %0 = COPY %1 ;; Now %0.sub0 has a definition,
// ;; but it's equivalent to "undef".
return std::make_pair(nullptr, SrcReg);
}
VNI = ValueIn;
TrackReg = SrcReg;
}
return std::make_pair(VNI, TrackReg);
}
bool JoinVals::valuesIdentical(VNInfo *Value0, VNInfo *Value1,
const JoinVals &Other) const {
const VNInfo *Orig0;
unsigned Reg0;
std::tie(Orig0, Reg0) = followCopyChain(Value0);
if (Orig0 == Value1 && Reg0 == Other.Reg)
return true;
const VNInfo *Orig1;
unsigned Reg1;
std::tie(Orig1, Reg1) = Other.followCopyChain(Value1);
// If both values are undefined, and the source registers are the same
// register, the values are identical. Filter out cases where only one
// value is defined.
if (Orig0 == nullptr || Orig1 == nullptr)
return Orig0 == Orig1 && Reg0 == Reg1;
// The values are equal if they are defined at the same place and use the
// same register. Note that we cannot compare VNInfos directly as some of
// them might be from a copy created in mergeSubRangeInto() while the other
// is from the original LiveInterval.
return Orig0->def == Orig1->def && Reg0 == Reg1;
}
JoinVals::ConflictResolution
JoinVals::analyzeValue(unsigned ValNo, JoinVals &Other) {
Val &V = Vals[ValNo];
assert(!V.isAnalyzed() && "Value has already been analyzed!");
VNInfo *VNI = LR.getValNumInfo(ValNo);
if (VNI->isUnused()) {
V.WriteLanes = LaneBitmask::getAll();
return CR_Keep;
}
// Get the instruction defining this value, compute the lanes written.
const MachineInstr *DefMI = nullptr;
if (VNI->isPHIDef()) {
// Conservatively assume that all lanes in a PHI are valid.
LaneBitmask Lanes = SubRangeJoin ? LaneBitmask::getLane(0)
: TRI->getSubRegIndexLaneMask(SubIdx);
V.ValidLanes = V.WriteLanes = Lanes;
} else {
DefMI = Indexes->getInstructionFromIndex(VNI->def);
assert(DefMI != nullptr);
if (SubRangeJoin) {
// We don't care about the lanes when joining subregister ranges.
V.WriteLanes = V.ValidLanes = LaneBitmask::getLane(0);
if (DefMI->isImplicitDef()) {
V.ValidLanes = LaneBitmask::getNone();
V.ErasableImplicitDef = true;
}
} else {
bool Redef = false;
V.ValidLanes = V.WriteLanes = computeWriteLanes(DefMI, Redef);
// If this is a read-modify-write instruction, there may be more valid
// lanes than the ones written by this instruction.
// This only covers partial redef operands. DefMI may have normal use
// operands reading the register. They don't contribute valid lanes.
//
// This adds ssub1 to the set of valid lanes in %src:
//
// %src:ssub1 = FOO
//
// This leaves only ssub1 valid, making any other lanes undef:
//
// %src:ssub1<def,read-undef> = FOO %src:ssub2
//
// The <read-undef> flag on the def operand means that old lane values are
// not important.
if (Redef) {
V.RedefVNI = LR.Query(VNI->def).valueIn();
assert((TrackSubRegLiveness || V.RedefVNI) &&
"Instruction is reading nonexistent value");
if (V.RedefVNI != nullptr) {
computeAssignment(V.RedefVNI->id, Other);
V.ValidLanes |= Vals[V.RedefVNI->id].ValidLanes;
}
}
// An IMPLICIT_DEF writes undef values.
if (DefMI->isImplicitDef()) {
// We normally expect IMPLICIT_DEF values to be live only until the end
// of their block. If the value is really live longer and gets pruned in
// another block, this flag is cleared again.
V.ErasableImplicitDef = true;
V.ValidLanes &= ~V.WriteLanes;
}
}
}
// Find the value in Other that overlaps VNI->def, if any.
LiveQueryResult OtherLRQ = Other.LR.Query(VNI->def);
// It is possible that both values are defined by the same instruction, or
// the values are PHIs defined in the same block. When that happens, the two
// values should be merged into one, but not into any preceding value.
// The first value defined or visited gets CR_Keep, the other gets CR_Merge.
if (VNInfo *OtherVNI = OtherLRQ.valueDefined()) {
assert(SlotIndex::isSameInstr(VNI->def, OtherVNI->def) && "Broken LRQ");
// One value stays, the other is merged. Keep the earlier one, or the first
// one we see.
if (OtherVNI->def < VNI->def)
Other.computeAssignment(OtherVNI->id, *this);
else if (VNI->def < OtherVNI->def && OtherLRQ.valueIn()) {
// This is an early-clobber def overlapping a live-in value in the other
// register. Not mergeable.
V.OtherVNI = OtherLRQ.valueIn();
return CR_Impossible;
}
V.OtherVNI = OtherVNI;
Val &OtherV = Other.Vals[OtherVNI->id];
// Keep this value, check for conflicts when analyzing OtherVNI.
if (!OtherV.isAnalyzed())
return CR_Keep;
// Both sides have been analyzed now.
// Allow overlapping PHI values. Any real interference would show up in a
// predecessor, the PHI itself can't introduce any conflicts.
if (VNI->isPHIDef())
return CR_Merge;
if ((V.ValidLanes & OtherV.ValidLanes).any())
// Overlapping lanes can't be resolved.
return CR_Impossible;
else
return CR_Merge;
}
// No simultaneous def. Is Other live at the def?
V.OtherVNI = OtherLRQ.valueIn();
if (!V.OtherVNI)
// No overlap, no conflict.
return CR_Keep;
assert(!SlotIndex::isSameInstr(VNI->def, V.OtherVNI->def) && "Broken LRQ");
// We have overlapping values, or possibly a kill of Other.
// Recursively compute assignments up the dominator tree.
Other.computeAssignment(V.OtherVNI->id, *this);
Val &OtherV = Other.Vals[V.OtherVNI->id];
// Check if OtherV is an IMPLICIT_DEF that extends beyond its basic block.
// This shouldn't normally happen, but ProcessImplicitDefs can leave such
// IMPLICIT_DEF instructions behind, and there is nothing wrong with it
// technically.
//
// When it happens, treat that IMPLICIT_DEF as a normal value, and don't try
// to erase the IMPLICIT_DEF instruction.
if (OtherV.ErasableImplicitDef && DefMI &&
DefMI->getParent() != Indexes->getMBBFromIndex(V.OtherVNI->def)) {
LLVM_DEBUG(dbgs() << "IMPLICIT_DEF defined at " << V.OtherVNI->def
<< " extends into "
<< printMBBReference(*DefMI->getParent())
<< ", keeping it.\n");
OtherV.ErasableImplicitDef = false;
}
// Allow overlapping PHI values. Any real interference would show up in a
// predecessor, the PHI itself can't introduce any conflicts.
if (VNI->isPHIDef())
return CR_Replace;
// Check for simple erasable conflicts.
if (DefMI->isImplicitDef()) {
// We need the def for the subregister if there is nothing else live at the
// subrange at this point.
if (TrackSubRegLiveness
&& (V.WriteLanes & (OtherV.ValidLanes | OtherV.WriteLanes)).none())
return CR_Replace;
return CR_Erase;
}
// Include the non-conflict where DefMI is a coalescable copy that kills
// OtherVNI. We still want the copy erased and value numbers merged.
if (CP.isCoalescable(DefMI)) {
// Some of the lanes copied from OtherVNI may be undef, making them undef
// here too.
V.ValidLanes &= ~V.WriteLanes | OtherV.ValidLanes;
return CR_Erase;
}
// This may not be a real conflict if DefMI simply kills Other and defines
// VNI.
if (OtherLRQ.isKill() && OtherLRQ.endPoint() <= VNI->def)
return CR_Keep;
// Handle the case where VNI and OtherVNI can be proven to be identical:
//
// %other = COPY %ext
// %this = COPY %ext <-- Erase this copy
//
if (DefMI->isFullCopy() && !CP.isPartial() &&
valuesIdentical(VNI, V.OtherVNI, Other)) {
V.Identical = true;
return CR_Erase;
}
// If the lanes written by this instruction were all undef in OtherVNI, it is
// still safe to join the live ranges. This can't be done with a simple value
// mapping, though - OtherVNI will map to multiple values:
//
// 1 %dst:ssub0 = FOO <-- OtherVNI
// 2 %src = BAR <-- VNI
// 3 %dst:ssub1 = COPY killed %src <-- Eliminate this copy.
// 4 BAZ killed %dst
// 5 QUUX killed %src
//
// Here OtherVNI will map to itself in [1;2), but to VNI in [2;5). CR_Replace
// handles this complex value mapping.
if ((V.WriteLanes & OtherV.ValidLanes).none())
return CR_Replace;
// If the other live range is killed by DefMI and the live ranges are still
// overlapping, it must be because we're looking at an early clobber def:
//
// %dst<def,early-clobber> = ASM killed %src
//
// In this case, it is illegal to merge the two live ranges since the early
// clobber def would clobber %src before it was read.
if (OtherLRQ.isKill()) {
// This case where the def doesn't overlap the kill is handled above.
assert(VNI->def.isEarlyClobber() &&
"Only early clobber defs can overlap a kill");
return CR_Impossible;
}
// VNI is clobbering live lanes in OtherVNI, but there is still the
// possibility that no instructions actually read the clobbered lanes.
// If we're clobbering all the lanes in OtherVNI, at least one must be read.
// Otherwise Other.RI wouldn't be live here.
if ((TRI->getSubRegIndexLaneMask(Other.SubIdx) & ~V.WriteLanes).none())
return CR_Impossible;
// We need to verify that no instructions are reading the clobbered lanes. To
// save compile time, we'll only check that locally. Don't allow the tainted
// value to escape the basic block.
MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
if (OtherLRQ.endPoint() >= Indexes->getMBBEndIdx(MBB))
return CR_Impossible;
// There are still some things that could go wrong besides clobbered lanes
// being read, for example OtherVNI may be only partially redefined in MBB,
// and some clobbered lanes could escape the block. Save this analysis for
// resolveConflicts() when all values have been mapped. We need to know
// RedefVNI and WriteLanes for any later defs in MBB, and we can't compute
// that now - the recursive analyzeValue() calls must go upwards in the
// dominator tree.
return CR_Unresolved;
}
void JoinVals::computeAssignment(unsigned ValNo, JoinVals &Other) {
Val &V = Vals[ValNo];
if (V.isAnalyzed()) {
// Recursion should always move up the dominator tree, so ValNo is not
// supposed to reappear before it has been assigned.
assert(Assignments[ValNo] != -1 && "Bad recursion?");
return;
}
switch ((V.Resolution = analyzeValue(ValNo, Other))) {
case CR_Erase:
case CR_Merge:
// Merge this ValNo into OtherVNI.
assert(V.OtherVNI && "OtherVNI not assigned, can't merge.");
assert(Other.Vals[V.OtherVNI->id].isAnalyzed() && "Missing recursion");
Assignments[ValNo] = Other.Assignments[V.OtherVNI->id];
LLVM_DEBUG(dbgs() << "\t\tmerge " << printReg(Reg) << ':' << ValNo << '@'
<< LR.getValNumInfo(ValNo)->def << " into "
<< printReg(Other.Reg) << ':' << V.OtherVNI->id << '@'
<< V.OtherVNI->def << " --> @"
<< NewVNInfo[Assignments[ValNo]]->def << '\n');
break;
case CR_Replace:
case CR_Unresolved: {
// The other value is going to be pruned if this join is successful.
assert(V.OtherVNI && "OtherVNI not assigned, can't prune");
Val &OtherV = Other.Vals[V.OtherVNI->id];
// We cannot erase an IMPLICIT_DEF if we don't have valid values for all
// its lanes.
if ((OtherV.WriteLanes & ~V.ValidLanes).any() && TrackSubRegLiveness)
OtherV.ErasableImplicitDef = false;
OtherV.Pruned = true;
LLVM_FALLTHROUGH;
}
default:
// This value number needs to go in the final joined live range.
Assignments[ValNo] = NewVNInfo.size();
NewVNInfo.push_back(LR.getValNumInfo(ValNo));
break;
}
}
bool JoinVals::mapValues(JoinVals &Other) {
for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
computeAssignment(i, Other);
if (Vals[i].Resolution == CR_Impossible) {
LLVM_DEBUG(dbgs() << "\t\tinterference at " << printReg(Reg) << ':' << i
<< '@' << LR.getValNumInfo(i)->def << '\n');
return false;
}
}
return true;
}
bool JoinVals::
taintExtent(unsigned ValNo, LaneBitmask TaintedLanes, JoinVals &Other,
SmallVectorImpl<std::pair<SlotIndex, LaneBitmask>> &TaintExtent) {
VNInfo *VNI = LR.getValNumInfo(ValNo);
MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
SlotIndex MBBEnd = Indexes->getMBBEndIdx(MBB);
// Scan Other.LR from VNI.def to MBBEnd.
LiveInterval::iterator OtherI = Other.LR.find(VNI->def);
assert(OtherI != Other.LR.end() && "No conflict?");
do {
// OtherI is pointing to a tainted value. Abort the join if the tainted
// lanes escape the block.
SlotIndex End = OtherI->end;
if (End >= MBBEnd) {
LLVM_DEBUG(dbgs() << "\t\ttaints global " << printReg(Other.Reg) << ':'
<< OtherI->valno->id << '@' << OtherI->start << '\n');
return false;
}
LLVM_DEBUG(dbgs() << "\t\ttaints local " << printReg(Other.Reg) << ':'
<< OtherI->valno->id << '@' << OtherI->start << " to "
<< End << '\n');
// A dead def is not a problem.
if (End.isDead())
break;
TaintExtent.push_back(std::make_pair(End, TaintedLanes));
// Check for another def in the MBB.
if (++OtherI == Other.LR.end() || OtherI->start >= MBBEnd)
break;
// Lanes written by the new def are no longer tainted.
const Val &OV = Other.Vals[OtherI->valno->id];
TaintedLanes &= ~OV.WriteLanes;
if (!OV.RedefVNI)
break;
} while (TaintedLanes.any());
return true;
}
bool JoinVals::usesLanes(const MachineInstr &MI, unsigned Reg, unsigned SubIdx,
LaneBitmask Lanes) const {
if (MI.isDebugInstr())
return false;
for (const MachineOperand &MO : MI.operands()) {
if (!MO.isReg() || MO.isDef() || MO.getReg() != Reg)
continue;
if (!MO.readsReg())
continue;
unsigned S = TRI->composeSubRegIndices(SubIdx, MO.getSubReg());
if ((Lanes & TRI->getSubRegIndexLaneMask(S)).any())
return true;
}
return false;
}
bool JoinVals::resolveConflicts(JoinVals &Other) {
for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
Val &V = Vals[i];
assert(V.Resolution != CR_Impossible && "Unresolvable conflict");
if (V.Resolution != CR_Unresolved)
continue;
LLVM_DEBUG(dbgs() << "\t\tconflict at " << printReg(Reg) << ':' << i << '@'
<< LR.getValNumInfo(i)->def << '\n');
if (SubRangeJoin)
return false;
++NumLaneConflicts;
assert(V.OtherVNI && "Inconsistent conflict resolution.");
VNInfo *VNI = LR.getValNumInfo(i);
const Val &OtherV = Other.Vals[V.OtherVNI->id];
// VNI is known to clobber some lanes in OtherVNI. If we go ahead with the
// join, those lanes will be tainted with a wrong value. Get the extent of
// the tainted lanes.
LaneBitmask TaintedLanes = V.WriteLanes & OtherV.ValidLanes;
SmallVector<std::pair<SlotIndex, LaneBitmask>, 8> TaintExtent;
if (!taintExtent(i, TaintedLanes, Other, TaintExtent))
// Tainted lanes would extend beyond the basic block.
return false;
assert(!TaintExtent.empty() && "There should be at least one conflict.");
// Now look at the instructions from VNI->def to TaintExtent (inclusive).
MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
MachineBasicBlock::iterator MI = MBB->begin();
if (!VNI->isPHIDef()) {
MI = Indexes->getInstructionFromIndex(VNI->def);
// No need to check the instruction defining VNI for reads.
++MI;
}
assert(!SlotIndex::isSameInstr(VNI->def, TaintExtent.front().first) &&
"Interference ends on VNI->def. Should have been handled earlier");
MachineInstr *LastMI =
Indexes->getInstructionFromIndex(TaintExtent.front().first);
assert(LastMI && "Range must end at a proper instruction");
unsigned TaintNum = 0;
while (true) {
assert(MI != MBB->end() && "Bad LastMI");
if (usesLanes(*MI, Other.Reg, Other.SubIdx, TaintedLanes)) {
LLVM_DEBUG(dbgs() << "\t\ttainted lanes used by: " << *MI);
return false;
}
// LastMI is the last instruction to use the current value.
if (&*MI == LastMI) {
if (++TaintNum == TaintExtent.size())
break;
LastMI = Indexes->getInstructionFromIndex(TaintExtent[TaintNum].first);
assert(LastMI && "Range must end at a proper instruction");
TaintedLanes = TaintExtent[TaintNum].second;
}
++MI;
}
// The tainted lanes are unused.
V.Resolution = CR_Replace;
++NumLaneResolves;
}
return true;
}
bool JoinVals::isPrunedValue(unsigned ValNo, JoinVals &Other) {
Val &V = Vals[ValNo];
if (V.Pruned || V.PrunedComputed)
return V.Pruned;
if (V.Resolution != CR_Erase && V.Resolution != CR_Merge)
return V.Pruned;
// Follow copies up the dominator tree and check if any intermediate value
// has been pruned.
V.PrunedComputed = true;
V.Pruned = Other.isPrunedValue(V.OtherVNI->id, *this);
return V.Pruned;
}
void JoinVals::pruneValues(JoinVals &Other,
SmallVectorImpl<SlotIndex> &EndPoints,
bool changeInstrs) {
for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
SlotIndex Def = LR.getValNumInfo(i)->def;
switch (Vals[i].Resolution) {
case CR_Keep:
break;
case CR_Replace: {
// This value takes precedence over the value in Other.LR.
LIS->pruneValue(Other.LR, Def, &EndPoints);
// Check if we're replacing an IMPLICIT_DEF value. The IMPLICIT_DEF
// instructions are only inserted to provide a live-out value for PHI
// predecessors, so the instruction should simply go away once its value
// has been replaced.
Val &OtherV = Other.Vals[Vals[i].OtherVNI->id];
bool EraseImpDef = OtherV.ErasableImplicitDef &&
OtherV.Resolution == CR_Keep;
if (!Def.isBlock()) {
if (changeInstrs) {
// Remove <def,read-undef> flags. This def is now a partial redef.
// Also remove dead flags since the joined live range will
// continue past this instruction.
for (MachineOperand &MO :
Indexes->getInstructionFromIndex(Def)->operands()) {
if (MO.isReg() && MO.isDef() && MO.getReg() == Reg) {
if (MO.getSubReg() != 0 && MO.isUndef() && !EraseImpDef)
MO.setIsUndef(false);
MO.setIsDead(false);
}
}
}
// This value will reach instructions below, but we need to make sure
// the live range also reaches the instruction at Def.
if (!EraseImpDef)
EndPoints.push_back(Def);
}
LLVM_DEBUG(dbgs() << "\t\tpruned " << printReg(Other.Reg) << " at " << Def
<< ": " << Other.LR << '\n');
break;
}
case CR_Erase:
case CR_Merge:
if (isPrunedValue(i, Other)) {
// This value is ultimately a copy of a pruned value in LR or Other.LR.
// We can no longer trust the value mapping computed by
// computeAssignment(), the value that was originally copied could have
// been replaced.
LIS->pruneValue(LR, Def, &EndPoints);
LLVM_DEBUG(dbgs() << "\t\tpruned all of " << printReg(Reg) << " at "
<< Def << ": " << LR << '\n');
}
break;
case CR_Unresolved:
case CR_Impossible:
llvm_unreachable("Unresolved conflicts");
}
}
}
/// Consider the following situation when coalescing the copy between
/// %31 and %45 at 800. (The vertical lines represent live range segments.)
///
/// Main range Subrange 0004 (sub2)
/// %31 %45 %31 %45
/// 544 %45 = COPY %28 + +
/// | v1 | v1
/// 560B bb.1: + +
/// 624 = %45.sub2 | v2 | v2
/// 800 %31 = COPY %45 + + + +
/// | v0 | v0
/// 816 %31.sub1 = ... + |
/// 880 %30 = COPY %31 | v1 +
/// 928 %45 = COPY %30 | + +
/// | | v0 | v0 <--+
/// 992B ; backedge -> bb.1 | + + |
/// 1040 = %31.sub0 + |
/// This value must remain
/// live-out!
///
/// Assuming that %31 is coalesced into %45, the copy at 928 becomes
/// redundant, since it copies the value from %45 back into it. The
/// conflict resolution for the main range determines that %45.v0 is
/// to be erased, which is ok since %31.v1 is identical to it.
/// The problem happens with the subrange for sub2: it has to be live
/// on exit from the block, but since 928 was actually a point of
/// definition of %45.sub2, %45.sub2 was not live immediately prior
/// to that definition. As a result, when 928 was erased, the value v0
/// for %45.sub2 was pruned in pruneSubRegValues. Consequently, an
/// IMPLICIT_DEF was inserted as a "backedge" definition for %45.sub2,
/// providing an incorrect value to the use at 624.
///
/// Since the main-range values %31.v1 and %45.v0 were proved to be
/// identical, the corresponding values in subranges must also be the
/// same. A redundant copy is removed because it's not needed, and not
/// because it copied an undefined value, so any liveness that originated
/// from that copy cannot disappear. When pruning a value that started
/// at the removed copy, the corresponding identical value must be
/// extended to replace it.
void JoinVals::pruneSubRegValues(LiveInterval &LI, LaneBitmask &ShrinkMask) {
// Look for values being erased.
bool DidPrune = false;
for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
Val &V = Vals[i];
// We should trigger in all cases in which eraseInstrs() does something.
// match what eraseInstrs() is doing, print a message so
if (V.Resolution != CR_Erase &&
(V.Resolution != CR_Keep || !V.ErasableImplicitDef || !V.Pruned))
continue;
// Check subranges at the point where the copy will be removed.
SlotIndex Def = LR.getValNumInfo(i)->def;
SlotIndex OtherDef;
if (V.Identical)
OtherDef = V.OtherVNI->def;
// Print message so mismatches with eraseInstrs() can be diagnosed.
LLVM_DEBUG(dbgs() << "\t\tExpecting instruction removal at " << Def
<< '\n');
for (LiveInterval::SubRange &S : LI.subranges()) {
LiveQueryResult Q = S.Query(Def);
// If a subrange starts at the copy then an undefined value has been
// copied and we must remove that subrange value as well.
VNInfo *ValueOut = Q.valueOutOrDead();
if (ValueOut != nullptr && Q.valueIn() == nullptr) {
LLVM_DEBUG(dbgs() << "\t\tPrune sublane " << PrintLaneMask(S.LaneMask)
<< " at " << Def << "\n");
SmallVector<SlotIndex,8> EndPoints;
LIS->pruneValue(S, Def, &EndPoints);
DidPrune = true;
// Mark value number as unused.
ValueOut->markUnused();
if (V.Identical && S.Query(OtherDef).valueOut()) {
// If V is identical to V.OtherVNI (and S was live at OtherDef),
// then we can't simply prune V from S. V needs to be replaced
// with V.OtherVNI.
LIS->extendToIndices(S, EndPoints);
}
continue;
}
// If a subrange ends at the copy, then a value was copied but only
// partially used later. Shrink the subregister range appropriately.
if (Q.valueIn() != nullptr && Q.valueOut() == nullptr) {
LLVM_DEBUG(dbgs() << "\t\tDead uses at sublane "
<< PrintLaneMask(S.LaneMask) << " at " << Def
<< "\n");
ShrinkMask |= S.LaneMask;
}
}
}
if (DidPrune)
LI.removeEmptySubRanges();
}
/// Check if any of the subranges of @p LI contain a definition at @p Def.
static bool isDefInSubRange(LiveInterval &LI, SlotIndex Def) {
for (LiveInterval::SubRange &SR : LI.subranges()) {
if (VNInfo *VNI = SR.Query(Def).valueOutOrDead())
if (VNI->def == Def)
return true;
}
return false;
}
void JoinVals::pruneMainSegments(LiveInterval &LI, bool &ShrinkMainRange) {
assert(&static_cast<LiveRange&>(LI) == &LR);
for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
if (Vals[i].Resolution != CR_Keep)
continue;
VNInfo *VNI = LR.getValNumInfo(i);
if (VNI->isUnused() || VNI->isPHIDef() || isDefInSubRange(LI, VNI->def))
continue;
Vals[i].Pruned = true;
ShrinkMainRange = true;
}
}
void JoinVals::removeImplicitDefs() {
for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
Val &V = Vals[i];
if (V.Resolution != CR_Keep || !V.ErasableImplicitDef || !V.Pruned)
continue;
VNInfo *VNI = LR.getValNumInfo(i);
VNI->markUnused();
LR.removeValNo(VNI);
}
}
void JoinVals::eraseInstrs(SmallPtrSetImpl<MachineInstr*> &ErasedInstrs,
SmallVectorImpl<unsigned> &ShrinkRegs,
LiveInterval *LI) {
for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
// Get the def location before markUnused() below invalidates it.
SlotIndex Def = LR.getValNumInfo(i)->def;
switch (Vals[i].Resolution) {
case CR_Keep: {
// If an IMPLICIT_DEF value is pruned, it doesn't serve a purpose any
// longer. The IMPLICIT_DEF instructions are only inserted by
// PHIElimination to guarantee that all PHI predecessors have a value.
if (!Vals[i].ErasableImplicitDef || !Vals[i].Pruned)
break;
// Remove value number i from LR.
// For intervals with subranges, removing a segment from the main range
// may require extending the previous segment: for each definition of
// a subregister, there will be a corresponding def in the main range.
// That def may fall in the middle of a segment from another subrange.
// In such cases, removing this def from the main range must be
// complemented by extending the main range to account for the liveness
// of the other subrange.
VNInfo *VNI = LR.getValNumInfo(i);
SlotIndex Def = VNI->def;
// The new end point of the main range segment to be extended.
SlotIndex NewEnd;
if (LI != nullptr) {
LiveRange::iterator I = LR.FindSegmentContaining(Def);
assert(I != LR.end());
// Do not extend beyond the end of the segment being removed.
// The segment may have been pruned in preparation for joining
// live ranges.
NewEnd = I->end;
}
LR.removeValNo(VNI);
// Note that this VNInfo is reused and still referenced in NewVNInfo,
// make it appear like an unused value number.
VNI->markUnused();
if (LI != nullptr && LI->hasSubRanges()) {
assert(static_cast<LiveRange*>(LI) == &LR);
// Determine the end point based on the subrange information:
// minimum of (earliest def of next segment,
// latest end point of containing segment)
SlotIndex ED, LE;
for (LiveInterval::SubRange &SR : LI->subranges()) {
LiveRange::iterator I = SR.find(Def);
if (I == SR.end())
continue;
if (I->start > Def)
ED = ED.isValid() ? std::min(ED, I->start) : I->start;
else
LE = LE.isValid() ? std::max(LE, I->end) : I->end;
}
if (LE.isValid())
NewEnd = std::min(NewEnd, LE);
if (ED.isValid())
NewEnd = std::min(NewEnd, ED);
// We only want to do the extension if there was a subrange that
// was live across Def.
if (LE.isValid()) {
LiveRange::iterator S = LR.find(Def);
if (S != LR.begin())
std::prev(S)->end = NewEnd;
}
}
LLVM_DEBUG({
dbgs() << "\t\tremoved " << i << '@' << Def << ": " << LR << '\n';
if (LI != nullptr)
dbgs() << "\t\t LHS = " << *LI << '\n';
});
LLVM_FALLTHROUGH;
}
case CR_Erase: {
MachineInstr *MI = Indexes->getInstructionFromIndex(Def);
assert(MI && "No instruction to erase");
if (MI->isCopy()) {
unsigned Reg = MI->getOperand(1).getReg();
if (TargetRegisterInfo::isVirtualRegister(Reg) &&
Reg != CP.getSrcReg() && Reg != CP.getDstReg())
ShrinkRegs.push_back(Reg);
}
ErasedInstrs.insert(MI);
LLVM_DEBUG(dbgs() << "\t\terased:\t" << Def << '\t' << *MI);
LIS->RemoveMachineInstrFromMaps(*MI);
MI->eraseFromParent();
break;
}
default:
break;
}
}
}
void RegisterCoalescer::joinSubRegRanges(LiveRange &LRange, LiveRange &RRange,
LaneBitmask LaneMask,
const CoalescerPair &CP) {
SmallVector<VNInfo*, 16> NewVNInfo;
JoinVals RHSVals(RRange, CP.getSrcReg(), CP.getSrcIdx(), LaneMask,
NewVNInfo, CP, LIS, TRI, true, true);
JoinVals LHSVals(LRange, CP.getDstReg(), CP.getDstIdx(), LaneMask,
NewVNInfo, CP, LIS, TRI, true, true);
// Compute NewVNInfo and resolve conflicts (see also joinVirtRegs())
// We should be able to resolve all conflicts here as we could successfully do
// it on the mainrange already. There is however a problem when multiple
// ranges get mapped to the "overflow" lane mask bit which creates unexpected
// interferences.
if (!LHSVals.mapValues(RHSVals) || !RHSVals.mapValues(LHSVals)) {
// We already determined that it is legal to merge the intervals, so this
// should never fail.
llvm_unreachable("*** Couldn't join subrange!\n");
}
if (!LHSVals.resolveConflicts(RHSVals) ||
!RHSVals.resolveConflicts(LHSVals)) {
// We already determined that it is legal to merge the intervals, so this
// should never fail.
llvm_unreachable("*** Couldn't join subrange!\n");
}
// The merging algorithm in LiveInterval::join() can't handle conflicting
// value mappings, so we need to remove any live ranges that overlap a
// CR_Replace resolution. Collect a set of end points that can be used to
// restore the live range after joining.
SmallVector<SlotIndex, 8> EndPoints;
LHSVals.pruneValues(RHSVals, EndPoints, false);
RHSVals.pruneValues(LHSVals, EndPoints, false);
LHSVals.removeImplicitDefs();
RHSVals.removeImplicitDefs();
LRange.verify();
RRange.verify();
// Join RRange into LHS.
LRange.join(RRange, LHSVals.getAssignments(), RHSVals.getAssignments(),
NewVNInfo);
LLVM_DEBUG(dbgs() << "\t\tjoined lanes: " << PrintLaneMask(LaneMask)
<< ' ' << LRange << "\n");
if (EndPoints.empty())
return;
// Recompute the parts of the live range we had to remove because of
// CR_Replace conflicts.
LLVM_DEBUG({
dbgs() << "\t\trestoring liveness to " << EndPoints.size() << " points: ";
for (unsigned i = 0, n = EndPoints.size(); i != n; ++i) {
dbgs() << EndPoints[i];
if (i != n-1)
dbgs() << ',';
}
dbgs() << ": " << LRange << '\n';
});
LIS->extendToIndices(LRange, EndPoints);
}
void RegisterCoalescer::mergeSubRangeInto(LiveInterval &LI,
const LiveRange &ToMerge,
LaneBitmask LaneMask,
CoalescerPair &CP) {
BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator();
LI.refineSubRanges(Allocator, LaneMask,
[this,&Allocator,&ToMerge,&CP](LiveInterval::SubRange &SR) {
if (SR.empty()) {
SR.assign(ToMerge, Allocator);
} else {
// joinSubRegRange() destroys the merged range, so we need a copy.
LiveRange RangeCopy(ToMerge, Allocator);
joinSubRegRanges(SR, RangeCopy, SR.LaneMask, CP);
}
});
}
bool RegisterCoalescer::joinVirtRegs(CoalescerPair &CP) {
SmallVector<VNInfo*, 16> NewVNInfo;
LiveInterval &RHS = LIS->getInterval(CP.getSrcReg());
LiveInterval &LHS = LIS->getInterval(CP.getDstReg());
bool TrackSubRegLiveness = MRI->shouldTrackSubRegLiveness(*CP.getNewRC());
JoinVals RHSVals(RHS, CP.getSrcReg(), CP.getSrcIdx(), LaneBitmask::getNone(),
NewVNInfo, CP, LIS, TRI, false, TrackSubRegLiveness);
JoinVals LHSVals(LHS, CP.getDstReg(), CP.getDstIdx(), LaneBitmask::getNone(),
NewVNInfo, CP, LIS, TRI, false, TrackSubRegLiveness);
LLVM_DEBUG(dbgs() << "\t\tRHS = " << RHS << "\n\t\tLHS = " << LHS << '\n');
// First compute NewVNInfo and the simple value mappings.
// Detect impossible conflicts early.
if (!LHSVals.mapValues(RHSVals) || !RHSVals.mapValues(LHSVals))
return false;
// Some conflicts can only be resolved after all values have been mapped.
if (!LHSVals.resolveConflicts(RHSVals) || !RHSVals.resolveConflicts(LHSVals))
return false;
// All clear, the live ranges can be merged.
if (RHS.hasSubRanges() || LHS.hasSubRanges()) {
BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator();
// Transform lanemasks from the LHS to masks in the coalesced register and
// create initial subranges if necessary.
unsigned DstIdx = CP.getDstIdx();
if (!LHS.hasSubRanges()) {
LaneBitmask Mask = DstIdx == 0 ? CP.getNewRC()->getLaneMask()
: TRI->getSubRegIndexLaneMask(DstIdx);
// LHS must support subregs or we wouldn't be in this codepath.
assert(Mask.any());
LHS.createSubRangeFrom(Allocator, Mask, LHS);
} else if (DstIdx != 0) {
// Transform LHS lanemasks to new register class if necessary.
for (LiveInterval::SubRange &R : LHS.subranges()) {
LaneBitmask Mask = TRI->composeSubRegIndexLaneMask(DstIdx, R.LaneMask);
R.LaneMask = Mask;
}
}
LLVM_DEBUG(dbgs() << "\t\tLHST = " << printReg(CP.getDstReg()) << ' ' << LHS
<< '\n');
// Determine lanemasks of RHS in the coalesced register and merge subranges.
unsigned SrcIdx = CP.getSrcIdx();
if (!RHS.hasSubRanges()) {
LaneBitmask Mask = SrcIdx == 0 ? CP.getNewRC()->getLaneMask()
: TRI->getSubRegIndexLaneMask(SrcIdx);
mergeSubRangeInto(LHS, RHS, Mask, CP);
} else {
// Pair up subranges and merge.
for (LiveInterval::SubRange &R : RHS.subranges()) {
LaneBitmask Mask = TRI->composeSubRegIndexLaneMask(SrcIdx, R.LaneMask);
mergeSubRangeInto(LHS, R, Mask, CP);
}
}
LLVM_DEBUG(dbgs() << "\tJoined SubRanges " << LHS << "\n");
// Pruning implicit defs from subranges may result in the main range
// having stale segments.
LHSVals.pruneMainSegments(LHS, ShrinkMainRange);
LHSVals.pruneSubRegValues(LHS, ShrinkMask);
RHSVals.pruneSubRegValues(LHS, ShrinkMask);
}
// The merging algorithm in LiveInterval::join() can't handle conflicting
// value mappings, so we need to remove any live ranges that overlap a
// CR_Replace resolution. Collect a set of end points that can be used to
// restore the live range after joining.
SmallVector<SlotIndex, 8> EndPoints;
LHSVals.pruneValues(RHSVals, EndPoints, true);
RHSVals.pruneValues(LHSVals, EndPoints, true);
// Erase COPY and IMPLICIT_DEF instructions. This may cause some external
// registers to require trimming.
SmallVector<unsigned, 8> ShrinkRegs;
LHSVals.eraseInstrs(ErasedInstrs, ShrinkRegs, &LHS);
RHSVals.eraseInstrs(ErasedInstrs, ShrinkRegs);
while (!ShrinkRegs.empty())
shrinkToUses(&LIS->getInterval(ShrinkRegs.pop_back_val()));
// Join RHS into LHS.
LHS.join(RHS, LHSVals.getAssignments(), RHSVals.getAssignments(), NewVNInfo);
// Kill flags are going to be wrong if the live ranges were overlapping.
// Eventually, we should simply clear all kill flags when computing live
// ranges. They are reinserted after register allocation.
MRI->clearKillFlags(LHS.reg);
MRI->clearKillFlags(RHS.reg);
if (!EndPoints.empty()) {
// Recompute the parts of the live range we had to remove because of
// CR_Replace conflicts.
LLVM_DEBUG({
dbgs() << "\t\trestoring liveness to " << EndPoints.size() << " points: ";
for (unsigned i = 0, n = EndPoints.size(); i != n; ++i) {
dbgs() << EndPoints[i];
if (i != n-1)
dbgs() << ',';
}
dbgs() << ": " << LHS << '\n';
});
LIS->extendToIndices((LiveRange&)LHS, EndPoints);
}
return true;
}
bool RegisterCoalescer::joinIntervals(CoalescerPair &CP) {
return CP.isPhys() ? joinReservedPhysReg(CP) : joinVirtRegs(CP);
}
namespace {
/// Information concerning MBB coalescing priority.
struct MBBPriorityInfo {
MachineBasicBlock *MBB;
unsigned Depth;
bool IsSplit;
MBBPriorityInfo(MachineBasicBlock *mbb, unsigned depth, bool issplit)
: MBB(mbb), Depth(depth), IsSplit(issplit) {}
};
} // end anonymous namespace
/// C-style comparator that sorts first based on the loop depth of the basic
/// block (the unsigned), and then on the MBB number.
///
/// EnableGlobalCopies assumes that the primary sort key is loop depth.
static int compareMBBPriority(const MBBPriorityInfo *LHS,
const MBBPriorityInfo *RHS) {
// Deeper loops first
if (LHS->Depth != RHS->Depth)
return LHS->Depth > RHS->Depth ? -1 : 1;
// Try to unsplit critical edges next.
if (LHS->IsSplit != RHS->IsSplit)
return LHS->IsSplit ? -1 : 1;
// Prefer blocks that are more connected in the CFG. This takes care of
// the most difficult copies first while intervals are short.
unsigned cl = LHS->MBB->pred_size() + LHS->MBB->succ_size();
unsigned cr = RHS->MBB->pred_size() + RHS->MBB->succ_size();
if (cl != cr)
return cl > cr ? -1 : 1;
// As a last resort, sort by block number.
return LHS->MBB->getNumber() < RHS->MBB->getNumber() ? -1 : 1;
}
/// \returns true if the given copy uses or defines a local live range.
static bool isLocalCopy(MachineInstr *Copy, const LiveIntervals *LIS) {
if (!Copy->isCopy())
return false;
if (Copy->getOperand(1).isUndef())
return false;
unsigned SrcReg = Copy->getOperand(1).getReg();
unsigned DstReg = Copy->getOperand(0).getReg();
if (TargetRegisterInfo::isPhysicalRegister(SrcReg)
|| TargetRegisterInfo::isPhysicalRegister(DstReg))
return false;
return LIS->intervalIsInOneMBB(LIS->getInterval(SrcReg))
|| LIS->intervalIsInOneMBB(LIS->getInterval(DstReg));
}
bool RegisterCoalescer::
copyCoalesceWorkList(MutableArrayRef<MachineInstr*> CurrList) {
bool Progress = false;
for (unsigned i = 0, e = CurrList.size(); i != e; ++i) {
if (!CurrList[i])
continue;
// Skip instruction pointers that have already been erased, for example by
// dead code elimination.
if (ErasedInstrs.count(CurrList[i])) {
CurrList[i] = nullptr;
continue;
}
bool Again = false;
bool Success = joinCopy(CurrList[i], Again);
Progress |= Success;
if (Success || !Again)
CurrList[i] = nullptr;
}
return Progress;
}
/// Check if DstReg is a terminal node.
/// I.e., it does not have any affinity other than \p Copy.
static bool isTerminalReg(unsigned DstReg, const MachineInstr &Copy,
const MachineRegisterInfo *MRI) {
assert(Copy.isCopyLike());
// Check if the destination of this copy as any other affinity.
for (const MachineInstr &MI : MRI->reg_nodbg_instructions(DstReg))
if (&MI != &Copy && MI.isCopyLike())
return false;
return true;
}
bool RegisterCoalescer::applyTerminalRule(const MachineInstr &Copy) const {
assert(Copy.isCopyLike());
if (!UseTerminalRule)
return false;
unsigned DstReg, DstSubReg, SrcReg, SrcSubReg;
isMoveInstr(*TRI, &Copy, SrcReg, DstReg, SrcSubReg, DstSubReg);
// Check if the destination of this copy has any other affinity.
if (TargetRegisterInfo::isPhysicalRegister(DstReg) ||
// If SrcReg is a physical register, the copy won't be coalesced.
// Ignoring it may have other side effect (like missing
// rematerialization). So keep it.
TargetRegisterInfo::isPhysicalRegister(SrcReg) ||
!isTerminalReg(DstReg, Copy, MRI))
return false;
// DstReg is a terminal node. Check if it interferes with any other
// copy involving SrcReg.
const MachineBasicBlock *OrigBB = Copy.getParent();
const LiveInterval &DstLI = LIS->getInterval(DstReg);
for (const MachineInstr &MI : MRI->reg_nodbg_instructions(SrcReg)) {
// Technically we should check if the weight of the new copy is
// interesting compared to the other one and update the weight
// of the copies accordingly. However, this would only work if
// we would gather all the copies first then coalesce, whereas
// right now we interleave both actions.
// For now, just consider the copies that are in the same block.
if (&MI == &Copy || !MI.isCopyLike() || MI.getParent() != OrigBB)
continue;
unsigned OtherReg, OtherSubReg, OtherSrcReg, OtherSrcSubReg;
isMoveInstr(*TRI, &Copy, OtherSrcReg, OtherReg, OtherSrcSubReg,
OtherSubReg);
if (OtherReg == SrcReg)
OtherReg = OtherSrcReg;
// Check if OtherReg is a non-terminal.
if (TargetRegisterInfo::isPhysicalRegister(OtherReg) ||
isTerminalReg(OtherReg, MI, MRI))
continue;
// Check that OtherReg interfere with DstReg.
if (LIS->getInterval(OtherReg).overlaps(DstLI)) {
LLVM_DEBUG(dbgs() << "Apply terminal rule for: " << printReg(DstReg)
<< '\n');
return true;
}
}
return false;
}
void
RegisterCoalescer::copyCoalesceInMBB(MachineBasicBlock *MBB) {
LLVM_DEBUG(dbgs() << MBB->getName() << ":\n");
// Collect all copy-like instructions in MBB. Don't start coalescing anything
// yet, it might invalidate the iterator.
const unsigned PrevSize = WorkList.size();
if (JoinGlobalCopies) {
SmallVector<MachineInstr*, 2> LocalTerminals;
SmallVector<MachineInstr*, 2> GlobalTerminals;
// Coalesce copies bottom-up to coalesce local defs before local uses. They
// are not inherently easier to resolve, but slightly preferable until we
// have local live range splitting. In particular this is required by
// cmp+jmp macro fusion.
for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
MII != E; ++MII) {
if (!MII->isCopyLike())
continue;
bool ApplyTerminalRule = applyTerminalRule(*MII);
if (isLocalCopy(&(*MII), LIS)) {
if (ApplyTerminalRule)
LocalTerminals.push_back(&(*MII));
else
LocalWorkList.push_back(&(*MII));
} else {
if (ApplyTerminalRule)
GlobalTerminals.push_back(&(*MII));
else
WorkList.push_back(&(*MII));
}
}
// Append the copies evicted by the terminal rule at the end of the list.
LocalWorkList.append(LocalTerminals.begin(), LocalTerminals.end());
WorkList.append(GlobalTerminals.begin(), GlobalTerminals.end());
}
else {
SmallVector<MachineInstr*, 2> Terminals;
for (MachineInstr &MII : *MBB)
if (MII.isCopyLike()) {
if (applyTerminalRule(MII))
Terminals.push_back(&MII);
else
WorkList.push_back(&MII);
}
// Append the copies evicted by the terminal rule at the end of the list.
WorkList.append(Terminals.begin(), Terminals.end());
}
// Try coalescing the collected copies immediately, and remove the nulls.
// This prevents the WorkList from getting too large since most copies are
// joinable on the first attempt.
MutableArrayRef<MachineInstr*>
CurrList(WorkList.begin() + PrevSize, WorkList.end());
if (copyCoalesceWorkList(CurrList))
WorkList.erase(std::remove(WorkList.begin() + PrevSize, WorkList.end(),
nullptr), WorkList.end());
}
void RegisterCoalescer::coalesceLocals() {
copyCoalesceWorkList(LocalWorkList);
for (unsigned j = 0, je = LocalWorkList.size(); j != je; ++j) {
if (LocalWorkList[j])
WorkList.push_back(LocalWorkList[j]);
}
LocalWorkList.clear();
}
void RegisterCoalescer::joinAllIntervals() {
LLVM_DEBUG(dbgs() << "********** JOINING INTERVALS ***********\n");
assert(WorkList.empty() && LocalWorkList.empty() && "Old data still around.");
std::vector<MBBPriorityInfo> MBBs;
MBBs.reserve(MF->size());
for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E; ++I) {
MachineBasicBlock *MBB = &*I;
MBBs.push_back(MBBPriorityInfo(MBB, Loops->getLoopDepth(MBB),
JoinSplitEdges && isSplitEdge(MBB)));
}
array_pod_sort(MBBs.begin(), MBBs.end(), compareMBBPriority);
// Coalesce intervals in MBB priority order.
unsigned CurrDepth = std::numeric_limits<unsigned>::max();
for (unsigned i = 0, e = MBBs.size(); i != e; ++i) {
// Try coalescing the collected local copies for deeper loops.
if (JoinGlobalCopies && MBBs[i].Depth < CurrDepth) {
coalesceLocals();
CurrDepth = MBBs[i].Depth;
}
copyCoalesceInMBB(MBBs[i].MBB);
}
coalesceLocals();
// Joining intervals can allow other intervals to be joined. Iteratively join
// until we make no progress.
while (copyCoalesceWorkList(WorkList))
/* empty */ ;
}
void RegisterCoalescer::releaseMemory() {
ErasedInstrs.clear();
WorkList.clear();
DeadDefs.clear();
InflateRegs.clear();
}
bool RegisterCoalescer::runOnMachineFunction(MachineFunction &fn) {
MF = &fn;
MRI = &fn.getRegInfo();
const TargetSubtargetInfo &STI = fn.getSubtarget();
TRI = STI.getRegisterInfo();
TII = STI.getInstrInfo();
LIS = &getAnalysis<LiveIntervals>();
AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Loops = &getAnalysis<MachineLoopInfo>();
if (EnableGlobalCopies == cl::BOU_UNSET)
JoinGlobalCopies = STI.enableJoinGlobalCopies();
else
JoinGlobalCopies = (EnableGlobalCopies == cl::BOU_TRUE);
// The MachineScheduler does not currently require JoinSplitEdges. This will
// either be enabled unconditionally or replaced by a more general live range
// splitting optimization.
JoinSplitEdges = EnableJoinSplits;
LLVM_DEBUG(dbgs() << "********** SIMPLE REGISTER COALESCING **********\n"
<< "********** Function: " << MF->getName() << '\n');
if (VerifyCoalescing)
MF->verify(this, "Before register coalescing");
RegClassInfo.runOnMachineFunction(fn);
// Join (coalesce) intervals if requested.
if (EnableJoining)
joinAllIntervals();
// After deleting a lot of copies, register classes may be less constrained.
// Removing sub-register operands may allow GR32_ABCD -> GR32 and DPR_VFP2 ->
// DPR inflation.
array_pod_sort(InflateRegs.begin(), InflateRegs.end());
InflateRegs.erase(std::unique(InflateRegs.begin(), InflateRegs.end()),
InflateRegs.end());
LLVM_DEBUG(dbgs() << "Trying to inflate " << InflateRegs.size()
<< " regs.\n");
for (unsigned i = 0, e = InflateRegs.size(); i != e; ++i) {
unsigned Reg = InflateRegs[i];
if (MRI->reg_nodbg_empty(Reg))
continue;
if (MRI->recomputeRegClass(Reg)) {
LLVM_DEBUG(dbgs() << printReg(Reg) << " inflated to "
<< TRI->getRegClassName(MRI->getRegClass(Reg)) << '\n');
++NumInflated;
LiveInterval &LI = LIS->getInterval(Reg);
if (LI.hasSubRanges()) {
// If the inflated register class does not support subregisters anymore
// remove the subranges.
if (!MRI->shouldTrackSubRegLiveness(Reg)) {
LI.clearSubRanges();
} else {
#ifndef NDEBUG
LaneBitmask MaxMask = MRI->getMaxLaneMaskForVReg(Reg);
// If subranges are still supported, then the same subregs
// should still be supported.
for (LiveInterval::SubRange &S : LI.subranges()) {
assert((S.LaneMask & ~MaxMask).none());
}
#endif
}
}
}
}
LLVM_DEBUG(dump());
if (VerifyCoalescing)
MF->verify(this, "After register coalescing");
return true;
}
void RegisterCoalescer::print(raw_ostream &O, const Module* m) const {
LIS->print(O, m);
}
| {'repo_name': 'NVIDIA/MDL-SDK', 'stars': '243', 'repo_language': 'C++', 'file_name': 'DIASourceFile.h', 'mime_type': 'text/x-c++', 'hash': 4331508629900682092, 'source_dataset': 'data'} |
set(CMAKE_HOST_SYSTEM "Linux-4.4.0-78-generic")
set(CMAKE_HOST_SYSTEM_NAME "Linux")
set(CMAKE_HOST_SYSTEM_VERSION "4.4.0-78-generic")
set(CMAKE_HOST_SYSTEM_PROCESSOR "x86_64")
set(CMAKE_SYSTEM "Linux-4.4.0-78-generic")
set(CMAKE_SYSTEM_NAME "Linux")
set(CMAKE_SYSTEM_VERSION "4.4.0-78-generic")
set(CMAKE_SYSTEM_PROCESSOR "x86_64")
set(CMAKE_CROSSCOMPILING "FALSE")
set(CMAKE_SYSTEM_LOADED 1)
| {'repo_name': 'EricLYang/courseRepo', 'stars': '129', 'repo_language': 'C++', 'file_name': '_setup_util.py.stamp', 'mime_type': 'text/x-python', 'hash': 74588934202919856, 'source_dataset': 'data'} |
KafkaServer {
com.sun.security.auth.module.Krb5LoginModule required
useKeyTab=true
storeKey=true
keyTab="/vagrant/vagrant/keytabs/broker2.keytab"
principal="kafka/broker2.kafkafast@KAFKAFAST";
}; | {'repo_name': 'gerritjvv/kafka-fast', 'stars': '170', 'repo_language': 'Clojure', 'file_name': 'zookeeper.sh', 'mime_type': 'text/x-shellscript', 'hash': -2406472703954802304, 'source_dataset': 'data'} |
/**
* Copyright (c) 2012, Ben Fortuna
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* o Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* o Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* o Neither the name of Ben Fortuna nor the names of any other contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package net.fortuna.ical4j.model.property;
import java.text.ParseException;
import net.fortuna.ical4j.model.DateTime;
import net.fortuna.ical4j.model.ParameterList;
import net.fortuna.ical4j.model.PropertyFactoryImpl;
/**
* $Id$
*
* Created: [Apr 6, 2004]
*
* Defines a DTSTAMP iCalendar component property.
*
* <pre>
* 4.8.7.2 Date/Time Stamp
*
* Property Name: DTSTAMP
*
* Purpose: The property indicates the date/time that the instance of
* the iCalendar object was created.
*
* Value Type: DATE-TIME
*
* Property Parameters: Non-standard property parameters can be
* specified on this property.
*
* Conformance: This property MUST be included in the "VEVENT", "VTODO",
* "VJOURNAL" or "VFREEBUSY" calendar components.
*
* Description: The value MUST be specified in the UTC time format.
*
* This property is also useful to protocols such as [IMIP] that have
* inherent latency issues with the delivery of content. This property
* will assist in the proper sequencing of messages containing iCalendar
* objects.
*
* This property is different than the "CREATED" and "LAST-MODIFIED"
* properties. These two properties are used to specify when the
* particular calendar data in the calendar store was created and last
* modified. This is different than when the iCalendar object
* representation of the calendar service information was created or
* last modified.
*
* Format Definition: The property is defined by the following notation:
*
* dtstamp = "DTSTAMP" stmparam ":" date-time CRLF
*
* stmparam = *(";" xparam)
* </pre>
*
* @author Ben Fortuna
*/
public class DtStamp extends UtcProperty {
private static final long serialVersionUID = 7581197869433744070L;
/**
* Default constructor. Initialises the dateTime value to the time of instantiation.
*/
public DtStamp() {
super(DTSTAMP, PropertyFactoryImpl.getInstance());
}
/**
* @param aValue a string representation of a DTSTAMP value
* @throws ParseException if the specified value is not a valid representation
*/
public DtStamp(final String aValue) throws ParseException {
this(new ParameterList(), aValue);
}
/**
* @param aList a list of parameters for this component
* @param aValue a value string for this component
* @throws ParseException where the specified value string is not a valid date-time/date representation
*/
public DtStamp(final ParameterList aList, final String aValue)
throws ParseException {
super(DTSTAMP, aList, PropertyFactoryImpl.getInstance());
setValue(aValue);
}
/**
* @param aDate a date representing a date-time
*/
public DtStamp(final DateTime aDate) {
super(DTSTAMP, PropertyFactoryImpl.getInstance());
// time must be in UTC..
aDate.setUtc(true);
setDate(aDate);
}
/**
* @param aList a list of parameters for this component
* @param aDate a date representing a date-time
*/
public DtStamp(final ParameterList aList, final DateTime aDate) {
super(DTSTAMP, aList, PropertyFactoryImpl.getInstance());
// time must be in UTC..
aDate.setUtc(true);
setDate(aDate);
}
}
| {'repo_name': 'gggard/AndroidCaldavSyncAdapater', 'stars': '242', 'repo_language': 'Java', 'file_name': 'org.eclipse.jdt.core.prefs', 'mime_type': 'text/plain', 'hash': -7205393514761875311, 'source_dataset': 'data'} |
{
"name": "felixfbecker/advanced-json-rpc",
"description": "A more advanced JSONRPC implementation",
"type": "library",
"license": "ISC",
"authors": [
{
"name": "Felix Becker",
"email": "[email protected]"
}
],
"autoload": {
"psr-4": {
"AdvancedJsonRpc\\": "lib/"
}
},
"autoload-dev": {
"psr-4": {
"AdvancedJsonRpc\\Tests\\": "tests/"
}
},
"require": {
"php": ">=7.0",
"netresearch/jsonmapper": "^1.0 || ^2.0",
"phpdocumentor/reflection-docblock": "^4.0.0 || ^5.0.0"
},
"require-dev": {
"phpunit/phpunit": "^6.0.0"
},
"minimum-stability": "dev",
"prefer-stable": true
}
| {'repo_name': 'felixfbecker/php-advanced-json-rpc', 'stars': '123', 'repo_language': 'PHP', 'file_name': 'MethodCall.php', 'mime_type': 'text/x-php', 'hash': -2990557096108146610, 'source_dataset': 'data'} |
import { Component } from '@angular/core';
@Component({
selector: 'mail-app',
styleUrls: ['mail-app.component.scss'],
template: `
<div class="mail">
<router-outlet></router-outlet>
</div>
<div class="mail">
<router-outlet name="pane"></router-outlet>
</div>
`
})
export class MailAppComponent {}
| {'repo_name': 'UltimateAngular/angular-pro-src', 'stars': '239', 'repo_language': 'TypeScript', 'file_name': 'stock-inventory.component.ts', 'mime_type': 'text/x-java', 'hash': -4647332069448861678, 'source_dataset': 'data'} |
import { compile } from "../../src/lib/events/eventIfActorAtPosition";
test("Should be able to conditionally execute if actor is at a position", () => {
const mockactorSetActive = jest.fn();
const mockIfActorAtPosition = jest.fn();
const truePath = [{ command: "EVENT_END", id: "abc" }];
const falsePath = [{ command: "EVENT_END", id: "def" }];
compile(
{
actorId: "player",
x: 4,
y: 8,
true: truePath,
false: falsePath
},
{
actorSetActive: mockactorSetActive,
ifActorAtPosition: mockIfActorAtPosition
}
);
expect(mockactorSetActive).toBeCalledWith("player");
expect(mockIfActorAtPosition).toBeCalledWith(4, 8, truePath, falsePath);
});
| {'repo_name': 'chrismaltby/gb-studio', 'stars': '4863', 'repo_language': 'C', 'file_name': 'config.yml', 'mime_type': 'text/plain', 'hash': -7800556367464688197, 'source_dataset': 'data'} |
{# USES_VARIABLES { _queue } #}
{% extends 'common_group.py_' %}
{% block maincode %}
_spiking_synapses = _queue.peek()
if len(_spiking_synapses):
# scalar code
{# Note that we don't write to scalar variables conditionally. The scalar code
should therefore only include the calculation of scalar expressions
that are used below for writing to a vector variable #}
{{scalar_code|autoindent}}
# vector code
_idx = _spiking_synapses
_vectorisation_idx = _idx
{{vector_code|autoindent}}
# Advance the spike queue
_queue.advance()
{% endblock %}
| {'repo_name': 'brian-team/brian2', 'stars': '447', 'repo_language': 'Python', 'file_name': 'computation.rst', 'mime_type': 'text/plain', 'hash': -315547097802678315, 'source_dataset': 'data'} |
package openblocks.common.recipe;
import com.google.common.collect.HashMultiset;
import com.google.common.collect.Multiset;
import java.util.Iterator;
import javax.annotation.Nonnull;
import net.minecraft.inventory.InventoryCrafting;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.World;
import openblocks.OpenBlocks;
import openblocks.OpenBlocks.Blocks;
import openblocks.common.item.ItemImaginary;
import openblocks.common.item.ItemImaginary.PlacementMode;
import openmods.utils.CustomRecipeBase;
public class CrayonMixingRecipe extends CustomRecipeBase {
public CrayonMixingRecipe() {
super(OpenBlocks.location("crayons"));
}
@Override
public boolean matches(InventoryCrafting inv, World world) {
int count = 0;
for (int i = 0; i < inv.getSizeInventory(); i++) {
ItemStack stack = inv.getStackInSlot(i);
if (stack.isEmpty()) continue;
if (!ItemImaginary.isCrayon(stack))
return false;
if (ItemImaginary.getUses(stack) < ItemImaginary.CRAFTING_COST) continue;
count++;
}
return count > 1;
}
@Override
@Nonnull
public ItemStack getCraftingResult(InventoryCrafting inv) {
int count = 0;
float r = 0, g = 0, b = 0;
Multiset<ItemImaginary.PlacementMode> modes = HashMultiset.create();
for (int i = 0; i < inv.getSizeInventory(); i++) {
ItemStack stack = inv.getStackInSlot(i);
if (stack.isEmpty() || (ItemImaginary.getUses(stack) < ItemImaginary.CRAFTING_COST)) continue;
final NBTTagCompound tag = stack.getTagCompound();
if (tag != null) {
final Integer color = ItemImaginary.getColor(tag);
if (color == null) return ItemStack.EMPTY;
count++;
r += ((color >> 16) & 0xFF);
g += ((color >> 8) & 0xFF);
b += ((color >> 0) & 0xFF);
modes.add(ItemImaginary.getMode(tag));
}
}
if (count < 2) return ItemStack.EMPTY;
int color = (int)(r / count);
color = (color << 8) + (int)(g / count);
color = (color << 8) + (int)(b / count);
final Iterator<Multiset.Entry<PlacementMode>> iterator = modes.entrySet().iterator();
Multiset.Entry<PlacementMode> max = iterator.next();
while (iterator.hasNext()) {
Multiset.Entry<PlacementMode> tmp = iterator.next();
if (tmp.getCount() > max.getCount()) max = tmp;
}
return ItemImaginary.setupValues(new ItemStack(Blocks.imaginary), color, max.getElement(), count * 0.9f);
}
@Override
public boolean canFit(int width, int height) {
return width * height > 1;
}
}
| {'repo_name': 'OpenMods/OpenBlocks', 'stars': '277', 'repo_language': 'Java', 'file_name': 'gradle-wrapper.properties', 'mime_type': 'text/plain', 'hash': -5121969977686234102, 'source_dataset': 'data'} |
/*
* avenir: Predictive analytic based on Hadoop Map Reduce
* Author: Pranab Ghosh
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You may
* obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.avenir.regress;
/**
* @author pranab
*
*/
public class LogisticRegressor {
private double[] coefficients;
private double[] aggregates;
private double[] coeffDiff;
private double convergeThreshold;
private String posClassVal;
public LogisticRegressor() {
}
public LogisticRegressor(double[] coefficients) {
super();
this.coefficients = coefficients;
aggregates = new double[coefficients.length];
for ( int i = 0; i < aggregates.length; ++i) {
aggregates[i] = 0;
}
}
/**
* @param coefficients
* @param posClassVal
*/
public LogisticRegressor(double[] coefficients, String posClassVal) {
super();
this.coefficients = coefficients;
this.posClassVal = posClassVal;
aggregates = new double[coefficients.length];
for ( int i = 0; i < aggregates.length; ++i) {
aggregates[i] = 0;
}
}
/**
* @param values
* @param classValue
*/
public void aggregate(int[] values, String classValue) {
double sum = 0;
for (int i = 0; i < values.length; ++i) {
sum += values[i] * coefficients[i];
}
double classProbEst = 1.0 / (1.0 + Math.exp(-sum));
double classProbActual = classValue.equals(posClassVal) ? 1.0 : 0;
double classProbDiff = classProbActual - classProbEst;
for (int i = 0; i < values.length; ++i) {
aggregates[i] += values[i] * classProbDiff;
}
}
/**
* @return
*/
public double[] getAggregates() {
return aggregates;
}
/**
* @param aggregates
*/
public void setAggregates(double[] aggregates) {
this.aggregates = aggregates;
}
public void addAggregates(double[] aggregates) {
if (null == this.aggregates) {
this.aggregates = new double[aggregates.length];
for (int i = 0; i < this.aggregates.length; ++i) {
this.aggregates[i] = 0;
}
}
for (int i = 0; i < aggregates.length; ++i ) {
this.aggregates[i] += aggregates[i];
}
}
/**
*
*/
public void setCoefficientDiff() {
for (int i = 0; i < coefficients.length; ++i) {
coeffDiff[i] = ((aggregates[i] - coefficients[i]) * 100.0) / coefficients[i];
if (coeffDiff[i] < 0) {
coeffDiff[i] = - coeffDiff[i];
}
}
}
public double[] getCoefficients() {
return coefficients;
}
public void setCoefficients(double[] coefficients) {
this.coefficients = coefficients;
}
/**
* @param convergeThreshold
*/
public void setConvergeThreshold(double convergeThreshold) {
this.convergeThreshold = convergeThreshold;
}
/**
* @return
*/
public boolean isAllConverged() {
boolean converged = true;
if (null == coeffDiff) {
coeffDiff = new double[coefficients.length];
setCoefficientDiff();
}
for (int i = 0; i < coeffDiff.length; ++i) {
if (coeffDiff[i] > convergeThreshold) {
converged = false;
break;
}
}
return converged;
}
/**
* @return
*/
public boolean isAverageConverged() {
boolean converged = true;
if (null == coeffDiff) {
coeffDiff = new double[coefficients.length];
setCoefficientDiff();
}
double sum = 0;
for (int i = 0; i < coeffDiff.length; ++i) {
sum += coeffDiff[i];
}
sum /= coeffDiff.length;
converged = sum < convergeThreshold;
return converged;
}
}
| {'repo_name': 'pranab/avenir', 'stars': '139', 'repo_language': 'Java', 'file_name': 'plugins.sbt', 'mime_type': 'text/plain', 'hash': 1883931889730751679, 'source_dataset': 'data'} |
(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
define(['Behavioral/Visitor/AbstractTitleInfo'], function(AbstractTitleInfo) {
var GameInfo;
return GameInfo = (function(_super) {
__extends(GameInfo, _super);
function GameInfo(titleName) {
this.titleName = titleName;
}
GameInfo.prototype.accept = function(titleBlurbVisitor) {
return titleBlurbVisitor.visit(this);
};
return GameInfo;
})(AbstractTitleInfo);
});
}).call(this);
| {'repo_name': 'markmontymark/patterns', 'stars': '112', 'repo_language': 'Shell', 'file_name': 'Singleton.coffee', 'mime_type': 'text/plain', 'hash': -7673152863484241845, 'source_dataset': 'data'} |
<?xml version="1.0" encoding="utf-8"?>
<!--
/*
** Copyright 2011, The Android Open Source Project
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
-->
<!-- These resources are around just to allow their values to be customized
for different hardware and product builds. -->
<resources>
<!-- The maximum number of rows in the QuickSettings -->
<integer name="quick_settings_max_rows">2</integer>
<!-- The number of columns that the top level tiles span in the QuickSettings -->
<integer name="quick_settings_user_time_settings_tile_span">2</integer>
<!-- We have only space for one notification on phone landscape layouts. -->
<integer name="keyguard_max_notification_count">1</integer>
<!-- orientation of the dead zone when touches have recently occurred elsewhere on screen -->
<integer name="navigation_bar_deadzone_orientation">1</integer>
<!-- Max number of columns for quick controls area -->
<integer name="controls_max_columns">4</integer>
<!-- Max number of columns for power menu -->
<integer name="power_menu_max_columns">4</integer>
</resources>
| {'repo_name': 'aosp-mirror/platform_frameworks_base', 'stars': '9245', 'repo_language': 'Java', 'file_name': 'DatabaseCursorTest.java', 'mime_type': 'text/x-java', 'hash': 6059901872153064427, 'source_dataset': 'data'} |
#pragma vx_copyright "2020"
#pragma vx_title_pos -100, -80
#pragma vx_title_size -8, 80
#pragma vx_title "HELLO WORLD"
#pragma vx_music vx_music_1
#include "vectrex.h"
#include "bios.h"
int main()
{
while(1)
{
wait_retrace();
intensity(0x7f);
print_str_c( 0x10, -0x50, (char*)"HELLO WORLD!" );
intensity(0x3f);
print_str_c( -0x10, -0x50, (char*)"THIS IS CMOC" );
}
return 0;
}
| {'repo_name': 'sehugg/8bitworkshop', 'stars': '252', 'repo_language': 'JavaScript', 'file_name': 'platforms.md', 'mime_type': 'text/plain', 'hash': -2256529859983267585, 'source_dataset': 'data'} |
(* ::Package:: *)
(* :Title: ValidateModelQCDBGF *)
(*
This software is covered by the GNU General Public License 3.
Copyright (C) 1990-2020 Rolf Mertig
Copyright (C) 1997-2020 Frederik Orellana
Copyright (C) 2014-2020 Vladyslav Shtabovenko
*)
(* :Summary: Validates FeynArts model for QCD in background field
formalism *)
(* ------------------------------------------------------------------------ *)
(* ::Section:: *)
(*Load FeynCalc and FeynArts*)
If[ $FrontEnd === Null,
$FeynCalcStartupMessages = False;
Print["Validation of the FeynArts model for QCD in background field formalism"];
];
If[$Notebooks === False, $FeynCalcStartupMessages = False];
$LoadAddOns={"FeynArts"};
<<FeynCalc`
$FAVerbose = 0;
FCCheckVersion[9,3,1];
(* ::Section:: *)
(*Patch the generated models to work with FeynCalc*)
FAPatch[PatchModelsOnly->True];
(* ::Section:: *)
(*Compare vertices to FeynArts*)
top1To2 = CreateTopologies[0,1 -> 2];
top2To2 = CreateTopologies[0,2 -> 2];
compFu1To2[x_]:=FCFAConvert[CreateFeynAmp[x, Truncated -> True,PreFactor->1],
IncomingMomenta->{p1},OutgoingMomenta->{p2,p3},UndoChiralSplittings->True,
DropSumOver->True,List->False,SMP->True]//Contract;
compFu2To2[x_]:=FCFAConvert[CreateFeynAmp[x, Truncated -> True,PreFactor->1],
IncomingMomenta->{p1,p2},OutgoingMomenta->{p3,p4},UndoChiralSplittings->True,
DropSumOver->True,List->False,SMP->True]//Contract;
diagsFR[top_,in_,out_]:=InsertFields[top, in ->out,
InsertionLevel -> {Classes},Model -> FileNameJoin[{"QCDBGF","QCDBGF"}],
GenericModel->FileNameJoin[{"QCDBGF","QCDBGF"}]];
diagsFA[top_,in_,out_]:=InsertFields[top, in ->out,
InsertionLevel -> {Classes}, Model -> "SMQCD", GenericModel->Lorentz];
(* ::Subsection:: *)
(*QQG-coupling*)
particles={{F[3, {1}]},{F[3, {1}],V[5]}};
diff1=compFu1To2[diagsFR[top1To2,Sequence@@particles]]-compFu1To2[diagsFA[top1To2,Sequence@@particles]]
(* ::Subsection:: *)
(*GhGhG-coupling*)
particles={{U[5]},{U[5],V[5]}};
diff2=compFu1To2[diagsFR[top1To2,Sequence@@particles]]-compFu1To2[diagsFA[top1To2,Sequence@@particles]]
(* ::Subsection:: *)
(*GGG-coupling*)
particles={{V[5]},{V[5],V[5]}};
diff3=ExpandScalarProduct[compFu1To2[diagsFR[top1To2,Sequence@@particles]]-compFu1To2[diagsFA[top1To2,Sequence@@particles]]]//Simplify
(* ::Subsection:: *)
(*GGGG-coupling*)
particles={{V[5],V[5]},{V[5],V[5]}};
diff4=ExpandScalarProduct[compFu2To2[DiagramExtract[diagsFR[top2To2,Sequence@@particles],1]]-
compFu2To2[DiagramExtract[diagsFA[top2To2,Sequence@@particles],1]]]//FCCanonicalizeDummyIndices//Simplify
(* ::Subsection:: *)
(*GGGB-coupling*)
diff5=ExpandScalarProduct[compFu2To2[DiagramExtract[diagsFR[top2To2,{V[50],V[5]},{V[5],V[5]}],1]]-
compFu2To2[DiagramExtract[diagsFA[top2To2,{V[5],V[5]},{V[5],V[5]}],1]]]//FCCanonicalizeDummyIndices//Simplify
(* ::Subsection:: *)
(*GGB-Coupling*)
ggbDiag=InsertFields[top1To2, {V[50,{a}]} ->{V[5,{b}],V[5,{c}]},
InsertionLevel -> {Classes},Model -> FileNameJoin[{"QCDBGF","QCDBGF"}],
GenericModel->FileNameJoin[{"QCDBGF","QCDBGF"}]];
ggbAbbott=-(((FV[q, nu] + FV[-p + r, nu]*GaugeXi[G])*MT[la, mu]*SMP["g_s"]*SUNF[a, b, c])/GaugeXi[G]) + FV[-q + r, mu]*MT[la, nu]*SMP["g_s"]*SUNF[a, b, c] +
((FV[r, la] + FV[-p + q, la]*GaugeXi[G])*MT[mu, nu]*SMP["g_s"]*SUNF[a, b, c])/GaugeXi[G];
ggbVertexFR=FCFAConvert[CreateFeynAmp[ggbDiag, Truncated -> True,PreFactor->-1,GaugeRules->{}],
IncomingMomenta->{-p},OutgoingMomenta->{q,r},UndoChiralSplittings->True,
DropSumOver->True,List->False,SMP->True,LorentzIndexNames->{mu,nu,la}]//FCE//Collect2[#,MT,Factoring->FullSimplify]&//MomentumCombine
diff6=FCI[(ggbAbbott-ggbVertexFR)]
(* ::Subsection:: *)
(*GhGhB-coupling*)
ghghbDiag=InsertFields[top1To2, {U[5,{a}]} ->{U[5,{b}],V[50,{c}]},
InsertionLevel -> {Classes},Model -> FileNameJoin[{"QCDBGF","QCDBGF"}],
GenericModel->FileNameJoin[{"QCDBGF","QCDBGF"}]];
ghghbFR=FCFAConvert[CreateFeynAmp[ghghbDiag, Truncated -> True,PreFactor->-1,GaugeRules->{}],
IncomingMomenta->{-p},OutgoingMomenta->{-q,r},UndoChiralSplittings->True,
DropSumOver->True,List->False,SMP->True,LorentzIndexNames->{mu,nu,la}]//FCE//FCI//MomentumCombine
ghghbAbbott=FV[p + q, mu]*SMP["g_s"]*SUNF[a, b, c];
diff7=FCI[(ghghbAbbott-ghghbFR)]
(* ::Subsection:: *)
(*GGBB-Coupling*)
ggbbDiag=InsertFields[top2To2, {V[50,{a}],V[5,{d}]} ->{V[5,{b}],V[50,{c}]},
InsertionLevel -> {Classes},Model -> FileNameJoin[{"QCDBGF","QCDBGF"}],
GenericModel->FileNameJoin[{"QCDBGF","QCDBGF"}]];
ggbbAbbott=((-I)*(MT[la, rho]*MT[mu, nu] + GaugeXi[G]*(-(MT[la, nu]*MT[mu, rho]) + MT[la, mu]*MT[nu, rho]))*SMP["g_s"]^2*SUNF[a, d, x]*SUNF[b, c, x])/GaugeXi[G] +
I*(-(MT[la, rho]*MT[mu, nu]) + MT[la, nu]*MT[mu, rho])*SMP["g_s"]^2*SUNF[a, c, x]*SUNF[b, d, x] +
(I*(MT[la, nu]*MT[mu, rho] + GaugeXi[G]*(-(MT[la, rho]*MT[mu, nu]) + MT[la, mu]*MT[nu, rho]))*SMP["g_s"]^2*SUNF[a, b, x]*SUNF[c, d, x])/GaugeXi[G];
ggbbVertexFR=FCFAConvert[CreateFeynAmp[DiagramExtract[ggbbDiag,{1}], Truncated -> True,PreFactor->-1,GaugeRules->{}],
IncomingMomenta->{-p},OutgoingMomenta->{q,r},UndoChiralSplittings->True,
DropSumOver->True,List->False,SMP->True,LorentzIndexNames->{mu,nu,rho,la}]//FCE//FCCanonicalizeDummyIndices[#,SUNIndexNames->{x}]&//
Collect2[#,SUNF,Factoring->FullSimplify]&
diff8=FCI[(ggbbAbbott-ggbbVertexFR)]//FCCanonicalizeDummyIndices
(* ::Subsection:: *)
(*GhGhBG-Coupling*)
ghghbgDiag=InsertFields[top2To2, {U[5,{b}],V[50,{c}]} ->{U[5,{a}],V[5,{d}]},
InsertionLevel -> {Classes},Model -> FileNameJoin[{"QCDBGF","QCDBGF"}],
GenericModel->FileNameJoin[{"QCDBGF","QCDBGF"}]];
ghghbgAbbott=(-I)*MT[mu, nu]*SMP["g_s"]^2*SUNF[a, c, x]*SUNF[b, d, x];
ghghbgVertexFR=FCFAConvert[CreateFeynAmp[DiagramExtract[ghghbgDiag,{1}], Truncated -> True,PreFactor->-1,GaugeRules->{}],
IncomingMomenta->{-p},OutgoingMomenta->{q,r},UndoChiralSplittings->True,
DropSumOver->True,List->False,SMP->True,LorentzIndexNames->{mu,nu,rho,la}]//FCE//FCCanonicalizeDummyIndices[#,SUNIndexNames->{x}]&//
Collect2[#,SUNF,Factoring->FullSimplify]&
diff9=FCI[(ghghbgAbbott-ghghbgVertexFR)]
(* ::Subsection:: *)
(*GhGhBB-Coupling*)
ghghbbDiag=InsertFields[top2To2, {U[5,{b}],V[50,{c}]} ->{U[5,{a}],V[50,{d}]},
InsertionLevel -> {Classes},Model -> FileNameJoin[{"QCDBGF","QCDBGF"}],
GenericModel->FileNameJoin[{"QCDBGF","QCDBGF"}]];
ghghbbAbbott=(-I)*MT[mu, nu]*SMP["g_s"]^2*SUNF[a, d, x]*SUNF[b, c, x] - I*MT[mu, nu]*SMP["g_s"]^2*SUNF[a, c, x]*SUNF[b, d, x];
ghghbbVertexFR=FCFAConvert[CreateFeynAmp[DiagramExtract[ghghbbDiag,{1}], Truncated -> True,PreFactor->-1,GaugeRules->{}],
IncomingMomenta->{-p},OutgoingMomenta->{q,r},UndoChiralSplittings->True,
DropSumOver->True,List->False,SMP->True,LorentzIndexNames->{mu,nu,rho,la}]//FCE//FCCanonicalizeDummyIndices[#,SUNIndexNames->{x}]&//
Collect2[#,SUNF,Factoring->FullSimplify]&
diff10=FCI[(ghghbbAbbott-ghghbbVertexFR)]
(* ::Subsection:: *)
(*Check*)
Print["Check signs in the QCDBGF model: ",
If[{diff1,diff2,diff3,diff4,diff5,diff6,diff7,diff8,diff9,diff10}===Table[0,10], "CORRECT.", "!!! WRONG !!!"]];
| {'repo_name': 'FeynCalc/feyncalc', 'stars': '156', 'repo_language': 'Mathematica', 'file_name': 'CheckToTFI.m', 'mime_type': 'text/plain', 'hash': -6687218616850998486, 'source_dataset': 'data'} |
/*
* linux/arch/arm/mach-omap2/board-omap3logic.c
*
* Copyright (C) 2010 Li-Pro.Net
* Stephan Linz <[email protected]>
*
* Copyright (C) 2010 Logic Product Development, Inc.
* Peter Barada <[email protected]>
*
* Modified from Beagle, EVM, and RX51
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/delay.h>
#include <linux/err.h>
#include <linux/clk.h>
#include <linux/io.h>
#include <linux/gpio.h>
#include <linux/regulator/fixed.h>
#include <linux/regulator/machine.h>
#include <linux/i2c/twl.h>
#include <linux/mmc/host.h>
#include <mach/hardware.h>
#include <asm/mach-types.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include "mux.h"
#include "hsmmc.h"
#include "control.h"
#include "common-board-devices.h"
#include <plat/mux.h>
#include <plat/board.h>
#include "common.h"
#include <plat/gpmc-smsc911x.h>
#include <plat/gpmc.h>
#include <plat/sdrc.h>
#define OMAP3LOGIC_SMSC911X_CS 1
#define OMAP3530_LV_SOM_MMC_GPIO_CD 110
#define OMAP3530_LV_SOM_MMC_GPIO_WP 126
#define OMAP3530_LV_SOM_SMSC911X_GPIO_IRQ 152
#define OMAP3_TORPEDO_MMC_GPIO_CD 127
#define OMAP3_TORPEDO_SMSC911X_GPIO_IRQ 129
static struct regulator_consumer_supply omap3logic_vmmc1_supply[] = {
REGULATOR_SUPPLY("vmmc", "omap_hsmmc.0"),
};
/* VMMC1 for MMC1 pins CMD, CLK, DAT0..DAT3 (20 mA, plus card == max 220 mA) */
static struct regulator_init_data omap3logic_vmmc1 = {
.constraints = {
.name = "VMMC1",
.min_uV = 1850000,
.max_uV = 3150000,
.valid_modes_mask = REGULATOR_MODE_NORMAL
| REGULATOR_MODE_STANDBY,
.valid_ops_mask = REGULATOR_CHANGE_VOLTAGE
| REGULATOR_CHANGE_MODE
| REGULATOR_CHANGE_STATUS,
},
.num_consumer_supplies = ARRAY_SIZE(omap3logic_vmmc1_supply),
.consumer_supplies = omap3logic_vmmc1_supply,
};
static struct twl4030_gpio_platform_data omap3logic_gpio_data = {
.gpio_base = OMAP_MAX_GPIO_LINES,
.irq_base = TWL4030_GPIO_IRQ_BASE,
.irq_end = TWL4030_GPIO_IRQ_END,
.use_leds = true,
.pullups = BIT(1),
.pulldowns = BIT(2) | BIT(6) | BIT(7) | BIT(8)
| BIT(13) | BIT(15) | BIT(16) | BIT(17),
};
static struct twl4030_platform_data omap3logic_twldata = {
.irq_base = TWL4030_IRQ_BASE,
.irq_end = TWL4030_IRQ_END,
/* platform_data for children goes here */
.gpio = &omap3logic_gpio_data,
.vmmc1 = &omap3logic_vmmc1,
};
static int __init omap3logic_i2c_init(void)
{
omap3_pmic_init("twl4030", &omap3logic_twldata);
return 0;
}
static struct omap2_hsmmc_info __initdata board_mmc_info[] = {
{
.name = "external",
.mmc = 1,
.caps = MMC_CAP_4_BIT_DATA,
.gpio_cd = -EINVAL,
.gpio_wp = -EINVAL,
},
{} /* Terminator */
};
static void __init board_mmc_init(void)
{
if (machine_is_omap3530_lv_som()) {
/* OMAP3530 LV SOM board */
board_mmc_info[0].gpio_cd = OMAP3530_LV_SOM_MMC_GPIO_CD;
board_mmc_info[0].gpio_wp = OMAP3530_LV_SOM_MMC_GPIO_WP;
omap_mux_init_signal("gpio_110", OMAP_PIN_OUTPUT);
omap_mux_init_signal("gpio_126", OMAP_PIN_OUTPUT);
} else if (machine_is_omap3_torpedo()) {
/* OMAP3 Torpedo board */
board_mmc_info[0].gpio_cd = OMAP3_TORPEDO_MMC_GPIO_CD;
omap_mux_init_signal("gpio_127", OMAP_PIN_OUTPUT);
} else {
/* unsupported board */
printk(KERN_ERR "%s(): unknown machine type\n", __func__);
return;
}
omap_hsmmc_init(board_mmc_info);
}
static struct omap_smsc911x_platform_data __initdata board_smsc911x_data = {
.cs = OMAP3LOGIC_SMSC911X_CS,
.gpio_irq = -EINVAL,
.gpio_reset = -EINVAL,
};
/* TODO/FIXME (comment by Peter Barada, LogicPD):
* Fix the PBIAS voltage for Torpedo MMC1 pins that
* are used for other needs (IRQs, etc). */
static void omap3torpedo_fix_pbias_voltage(void)
{
u16 control_pbias_offset = OMAP343X_CONTROL_PBIAS_LITE;
u32 reg;
if (machine_is_omap3_torpedo())
{
/* Set the bias for the pin */
reg = omap_ctrl_readl(control_pbias_offset);
reg &= ~OMAP343X_PBIASLITEPWRDNZ1;
omap_ctrl_writel(reg, control_pbias_offset);
/* 100ms delay required for PBIAS configuration */
msleep(100);
reg |= OMAP343X_PBIASLITEVMODE1;
reg |= OMAP343X_PBIASLITEPWRDNZ1;
omap_ctrl_writel(reg | 0x300, control_pbias_offset);
}
}
static inline void __init board_smsc911x_init(void)
{
if (machine_is_omap3530_lv_som()) {
/* OMAP3530 LV SOM board */
board_smsc911x_data.gpio_irq =
OMAP3530_LV_SOM_SMSC911X_GPIO_IRQ;
omap_mux_init_signal("gpio_152", OMAP_PIN_INPUT);
} else if (machine_is_omap3_torpedo()) {
/* OMAP3 Torpedo board */
board_smsc911x_data.gpio_irq = OMAP3_TORPEDO_SMSC911X_GPIO_IRQ;
omap_mux_init_signal("gpio_129", OMAP_PIN_INPUT);
} else {
/* unsupported board */
printk(KERN_ERR "%s(): unknown machine type\n", __func__);
return;
}
gpmc_smsc911x_init(&board_smsc911x_data);
}
#ifdef CONFIG_OMAP_MUX
static struct omap_board_mux board_mux[] __initdata = {
{ .reg_offset = OMAP_MUX_TERMINATOR },
};
#endif
static struct regulator_consumer_supply dummy_supplies[] = {
REGULATOR_SUPPLY("vddvario", "smsc911x.0"),
REGULATOR_SUPPLY("vdd33a", "smsc911x.0"),
};
static void __init omap3logic_init(void)
{
regulator_register_fixed(0, dummy_supplies, ARRAY_SIZE(dummy_supplies));
omap3_mux_init(board_mux, OMAP_PACKAGE_CBB);
omap3torpedo_fix_pbias_voltage();
omap3logic_i2c_init();
omap_serial_init();
omap_sdrc_init(NULL, NULL);
board_mmc_init();
board_smsc911x_init();
/* Ensure SDRC pins are mux'd for self-refresh */
omap_mux_init_signal("sdrc_cke0", OMAP_PIN_OUTPUT);
omap_mux_init_signal("sdrc_cke1", OMAP_PIN_OUTPUT);
}
MACHINE_START(OMAP3_TORPEDO, "Logic OMAP3 Torpedo board")
.atag_offset = 0x100,
.reserve = omap_reserve,
.map_io = omap3_map_io,
.init_early = omap35xx_init_early,
.init_irq = omap3_init_irq,
.handle_irq = omap3_intc_handle_irq,
.init_machine = omap3logic_init,
.timer = &omap3_timer,
.restart = omap_prcm_restart,
MACHINE_END
MACHINE_START(OMAP3530_LV_SOM, "OMAP Logic 3530 LV SOM board")
.atag_offset = 0x100,
.reserve = omap_reserve,
.map_io = omap3_map_io,
.init_early = omap35xx_init_early,
.init_irq = omap3_init_irq,
.handle_irq = omap3_intc_handle_irq,
.init_machine = omap3logic_init,
.timer = &omap3_timer,
.restart = omap_prcm_restart,
MACHINE_END
| {'repo_name': 'SmartisanTech/SmartisanOS_Kernel_Source', 'stars': '411', 'repo_language': 'C', 'file_name': 'spear310.h', 'mime_type': 'text/x-c', 'hash': 4879065538386799319, 'source_dataset': 'data'} |
struct ftpds
/* struct for ftp_start() function */
{
int tnum;
unsigned short port;
bool gotinfo;
SOCKET sock;
};
bool ftp_connect(const char *ip, unsigned short port);
bool ftp_transfer();
unsigned int __stdcall ftp_start(void *param); | {'repo_name': 'Chiggins/malware_sources', 'stars': '187', 'repo_language': 'Pascal', 'file_name': 'entries', 'mime_type': 'text/xml', 'hash': 2713328116728181436, 'source_dataset': 'data'} |
#if defined(Hiro_Window)
@implementation CocoaWindow : NSWindow
-(id) initWith:(hiro::mWindow&)windowReference {
window = &windowReference;
NSUInteger style = NSTitledWindowMask | NSClosableWindowMask | NSMiniaturizableWindowMask;
if(window->state.resizable) style |= NSResizableWindowMask;
if(self = [super initWithContentRect:NSMakeRect(0, 0, 640, 480) styleMask:style backing:NSBackingStoreBuffered defer:YES]) {
[self setDelegate:self];
[self setReleasedWhenClosed:NO];
[self setAcceptsMouseMovedEvents:YES];
[self setTitle:@""];
NSBundle* bundle = [NSBundle mainBundle];
NSDictionary* dictionary = [bundle infoDictionary];
NSString* applicationName = [dictionary objectForKey:@"CFBundleDisplayName"];
string hiroName = hiro::Application::state().name ? hiro::Application::state().name : string{"hiro"};
if(applicationName == nil) applicationName = [NSString stringWithUTF8String:hiroName];
menuBar = [[NSMenu alloc] init];
NSMenuItem* item;
string text;
rootMenu = [[NSMenu alloc] init];
item = [[[NSMenuItem alloc] initWithTitle:@"" action:nil keyEquivalent:@""] autorelease];
[item setSubmenu:rootMenu];
[menuBar addItem:item];
item = [[[NSMenuItem alloc] initWithTitle:[NSString stringWithFormat:@"About %@ ...", applicationName] action:@selector(menuAbout) keyEquivalent:@""] autorelease];
[item setTarget:self];
[rootMenu addItem:item];
[rootMenu addItem:[NSMenuItem separatorItem]];
item = [[[NSMenuItem alloc] initWithTitle:@"Preferences ..." action:@selector(menuPreferences) keyEquivalent:@""] autorelease];
[item setTarget:self];
[rootMenu addItem:item];
string result = nall::execute("spctl", "--status").output.strip();
if(result != "assessments disabled") {
disableGatekeeper = [[[NSMenuItem alloc] initWithTitle:@"Disable Gatekeeper" action:@selector(menuDisableGatekeeper) keyEquivalent:@""] autorelease];
[disableGatekeeper setTarget:self];
[rootMenu addItem:disableGatekeeper];
}
[rootMenu addItem:[NSMenuItem separatorItem]];
NSMenu* servicesMenu = [[[NSMenu alloc] initWithTitle:@"Services"] autorelease];
item = [[[NSMenuItem alloc] initWithTitle:@"Services" action:nil keyEquivalent:@""] autorelease];
[item setTarget:self];
[item setSubmenu:servicesMenu];
[rootMenu addItem:item];
[rootMenu addItem:[NSMenuItem separatorItem]];
[NSApp setServicesMenu:servicesMenu];
item = [[[NSMenuItem alloc] initWithTitle:[NSString stringWithFormat:@"Hide %@", applicationName] action:@selector(hide:) keyEquivalent:@""] autorelease];
[item setTarget:NSApp];
[rootMenu addItem:item];
item = [[[NSMenuItem alloc] initWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@""] autorelease];
[item setTarget:NSApp];
[rootMenu addItem:item];
item = [[[NSMenuItem alloc] initWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""] autorelease];
[item setTarget:NSApp];
[rootMenu addItem:item];
[rootMenu addItem:[NSMenuItem separatorItem]];
item = [[[NSMenuItem alloc] initWithTitle:[NSString stringWithFormat:@"Quit %@", applicationName] action:@selector(menuQuit) keyEquivalent:@""] autorelease];
[item setTarget:self];
[rootMenu addItem:item];
statusBar = [[NSTextField alloc] initWithFrame:NSMakeRect(0, 0, 0, 0)];
[statusBar setAlignment:NSLeftTextAlignment];
[statusBar setBordered:YES];
[statusBar setBezeled:YES];
[statusBar setBezelStyle:NSTextFieldSquareBezel];
[statusBar setEditable:NO];
[statusBar setHidden:YES];
[[self contentView] addSubview:statusBar positioned:NSWindowBelow relativeTo:nil];
}
return self;
}
-(BOOL) canBecomeKeyWindow {
return YES;
}
-(BOOL) canBecomeMainWindow {
return YES;
}
-(void) windowDidBecomeMain:(NSNotification*)notification {
if(window->state.menuBar) {
[NSApp setMainMenu:menuBar];
}
}
-(void) windowDidMove:(NSNotification*)notification {
if(auto p = window->self()) p->moveEvent();
}
-(void) windowDidResize:(NSNotification*)notification {
if(auto p = window->self()) p->sizeEvent();
}
-(BOOL) windowShouldClose:(id)sender {
if(window->state.onClose) window->doClose();
else window->setVisible(false);
if(window->state.modal && !window->visible()) window->setModal(false);
return NO;
}
-(NSDragOperation) draggingEntered:(id<NSDraggingInfo>)sender {
return DropPathsOperation(sender);
}
-(BOOL) performDragOperation:(id<NSDraggingInfo>)sender {
auto paths = DropPaths(sender);
if(!paths) return NO;
window->doDrop(paths);
return YES;
}
-(NSMenu*) menuBar {
return menuBar;
}
-(void) menuAbout {
hiro::Application::Cocoa::doAbout();
}
-(void) menuPreferences {
hiro::Application::Cocoa::doPreferences();
}
//to hell with gatekeepers
-(void) menuDisableGatekeeper {
NSAlert* alert = [[[NSAlert alloc] init] autorelease];
[alert setMessageText:@"Disable Gatekeeper"];
AuthorizationRef authorization;
OSStatus status = AuthorizationCreate(nullptr, kAuthorizationEmptyEnvironment, kAuthorizationFlagDefaults, &authorization);
if(status == errAuthorizationSuccess) {
AuthorizationItem items = {kAuthorizationRightExecute, 0, nullptr, 0};
AuthorizationRights rights = {1, &items};
status = AuthorizationCopyRights(authorization, &rights, nullptr,
kAuthorizationFlagDefaults
| kAuthorizationFlagInteractionAllowed
| kAuthorizationFlagPreAuthorize
| kAuthorizationFlagExtendRights, nullptr);
if(status == errAuthorizationSuccess) {
{ char program[] = "/usr/sbin/spctl";
char* arguments[] = {"--master-disable", nullptr};
FILE* pipe = nullptr;
AuthorizationExecuteWithPrivileges(authorization, program, kAuthorizationFlagDefaults, arguments, &pipe);
}
{ char program[] = "/usr/bin/defaults";
char* arguments[] = {"write /Library/Preferences/com.apple.security GKAutoRearm -bool NO"};
FILE* pipe = nullptr;
AuthorizationExecuteWithPrivileges(authorization, program, kAuthorizationFlagDefaults, arguments, &pipe);
}
}
AuthorizationFree(authorization, kAuthorizationFlagDefaults);
}
string result = nall::execute("spctl", "--status").output.strip();
if(result == "assessments disabled") {
[alert setAlertStyle:NSInformationalAlertStyle];
[alert setInformativeText:@"Gatekeeper has been successfully disabled."];
[disableGatekeeper setHidden:YES];
} else {
[alert setAlertStyle:NSWarningAlertStyle];
[alert setInformativeText:@"Error: failed to disable Gatekeeper."];
}
[alert addButtonWithTitle:@"Ok"];
[alert runModal];
}
-(void) menuQuit {
hiro::Application::Cocoa::doQuit();
}
-(NSTextField*) statusBar {
return statusBar;
}
@end
namespace hiro {
auto pWindow::construct() -> void {
@autoreleasepool {
cocoaWindow = [[CocoaWindow alloc] initWith:self()];
static bool once = true;
if(once) {
once = false;
[NSApp setMainMenu:[cocoaWindow menuBar]];
}
}
}
auto pWindow::destruct() -> void {
@autoreleasepool {
[cocoaWindow release];
}
}
auto pWindow::append(sMenuBar menuBar) -> void {
}
auto pWindow::append(sSizable sizable) -> void {
sizable->setGeometry(self().geometry().setPosition());
statusBarReposition();
}
auto pWindow::append(sStatusBar statusBar) -> void {
statusBar->setEnabled(statusBar->enabled(true));
statusBar->setFont(statusBar->font(true));
statusBar->setText(statusBar->text());
statusBar->setVisible(statusBar->visible(true));
}
auto pWindow::focused() const -> bool {
@autoreleasepool {
return [cocoaWindow isMainWindow] == YES;
}
}
auto pWindow::frameMargin() const -> Geometry {
@autoreleasepool {
NSRect frame = [cocoaWindow frameRectForContentRect:NSMakeRect(0, 0, 640, 480)];
return {abs(frame.origin.x), (int)(frame.size.height - 480), (int)(frame.size.width - 640), abs(frame.origin.y)};
}
}
auto pWindow::handle() const -> uintptr_t {
return (uintptr_t)cocoaWindow;
}
auto pWindow::monitor() const -> uint {
//TODO
return 0;
}
auto pWindow::remove(sMenuBar menuBar) -> void {
}
auto pWindow::remove(sSizable sizable) -> void {
@autoreleasepool {
[[cocoaWindow contentView] setNeedsDisplay:YES];
}
}
auto pWindow::remove(sStatusBar statusBar) -> void {
@autoreleasepool {
[[cocoaWindow statusBar] setHidden:YES];
}
}
auto pWindow::setBackgroundColor(Color color) -> void {
@autoreleasepool {
[cocoaWindow
setBackgroundColor:[NSColor
colorWithCalibratedRed:color.red() / 255.0
green:color.green() / 255.0
blue:color.blue() / 255.0
alpha:color.alpha() / 255.0
]
];
}
}
auto pWindow::setDismissable(bool dismissable) -> void {
//todo: not implemented
}
auto pWindow::setDroppable(bool droppable) -> void {
@autoreleasepool {
if(droppable) {
[cocoaWindow registerForDraggedTypes:[NSArray arrayWithObject:NSFilenamesPboardType]];
} else {
[cocoaWindow unregisterDraggedTypes];
}
}
}
auto pWindow::setFocused() -> void {
@autoreleasepool {
[cocoaWindow makeKeyAndOrderFront:nil];
}
}
auto pWindow::setFullScreen(bool fullScreen) -> void {
@autoreleasepool {
if(fullScreen) {
windowedGeometry = state().geometry;
[NSApp setPresentationOptions:NSApplicationPresentationFullScreen];
[cocoaWindow setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary];
[cocoaWindow toggleFullScreen:nil];
state().geometry = _geometry();
} else {
[cocoaWindow toggleFullScreen:nil];
[cocoaWindow setCollectionBehavior:NSWindowCollectionBehaviorDefault];
[NSApp setPresentationOptions:NSApplicationPresentationDefault];
state().geometry = windowedGeometry;
}
}
}
auto pWindow::setGeometry(Geometry geometry) -> void {
lock();
@autoreleasepool {
[cocoaWindow
setFrame:[cocoaWindow
frameRectForContentRect:NSMakeRect(
geometry.x(), Desktop::size().height() - geometry.y() - geometry.height(),
geometry.width(), geometry.height() + statusBarHeight()
)
]
display:YES
];
if(auto& sizable = state().sizable) {
sizable->setGeometry(self().geometry().setPosition());
}
statusBarReposition();
}
unlock();
}
auto pWindow::setMaximized(bool maximized) -> void {
//todo
}
auto pWindow::setMaximumSize(Size size) -> void {
//todo
}
auto pWindow::setMinimized(bool minimized) -> void {
//todo
}
auto pWindow::setMinimumSize(Size size) -> void {
//todo
}
auto pWindow::setModal(bool modal) -> void {
@autoreleasepool {
if(modal == true) {
[NSApp runModalForWindow:cocoaWindow];
} else {
[NSApp stopModal];
NSEvent* event = [NSEvent otherEventWithType:NSApplicationDefined location:NSMakePoint(0, 0) modifierFlags:0 timestamp:0.0 windowNumber:0 context:nil subtype:0 data1:0 data2:0];
[NSApp postEvent:event atStart:true];
}
}
}
auto pWindow::setResizable(bool resizable) -> void {
@autoreleasepool {
NSUInteger style = NSTitledWindowMask | NSClosableWindowMask | NSMiniaturizableWindowMask;
if(resizable) style |= NSResizableWindowMask;
[cocoaWindow setStyleMask:style];
}
}
auto pWindow::setTitle(const string& text) -> void {
@autoreleasepool {
[cocoaWindow setTitle:[NSString stringWithUTF8String:text]];
}
}
auto pWindow::setVisible(bool visible) -> void {
@autoreleasepool {
if(visible) [cocoaWindow makeKeyAndOrderFront:nil];
else [cocoaWindow orderOut:nil];
}
}
auto pWindow::moveEvent() -> void {
if(!locked() && !self().fullScreen() && self().visible()) {
@autoreleasepool {
NSRect area = [cocoaWindow contentRectForFrameRect:[cocoaWindow frame]];
area.size.height -= statusBarHeight();
state().geometry.setX(area.origin.x);
state().geometry.setY(Desktop::size().height() - area.origin.y - area.size.height);
}
}
if(!locked()) self().doMove();
}
auto pWindow::sizeEvent() -> void {
if(!locked() && !self().fullScreen() && self().visible()) {
@autoreleasepool {
NSRect area = [cocoaWindow contentRectForFrameRect:[cocoaWindow frame]];
area.size.height -= statusBarHeight();
state().geometry.setWidth(area.size.width);
state().geometry.setHeight(area.size.height);
}
}
if(auto& sizable = state().sizable) {
sizable->setGeometry(self().geometry().setPosition());
}
statusBarReposition();
if(!locked()) self().doSize();
}
auto pWindow::statusBarHeight() -> uint {
if(auto& statusBar = state().statusBar) {
if(statusBar->visible()) {
return pFont::size(statusBar->font(true), " ").height() + 6;
}
}
return 0;
}
auto pWindow::statusBarReposition() -> void {
@autoreleasepool {
NSRect area = [cocoaWindow contentRectForFrameRect:[cocoaWindow frame]];
[[cocoaWindow statusBar] setFrame:NSMakeRect(0, 0, area.size.width, statusBarHeight())];
[[cocoaWindow contentView] setNeedsDisplay:YES];
}
}
auto pWindow::_append(mWidget& widget) -> void {
@autoreleasepool {
if(auto pWidget = widget.self()) {
[pWidget->cocoaView removeFromSuperview];
[[cocoaWindow contentView] addSubview:pWidget->cocoaView positioned:NSWindowAbove relativeTo:nil];
pWidget->setGeometry(widget.geometry());
[[cocoaWindow contentView] setNeedsDisplay:YES];
}
}
}
auto pWindow::_geometry() -> Geometry {
@autoreleasepool {
NSRect area = [cocoaWindow contentRectForFrameRect:[cocoaWindow frame]];
area.size.height -= statusBarHeight();
return {
(int)area.origin.x, (int)(Monitor::geometry(Monitor::primary()).height() - area.origin.y - area.size.height),
(int)area.size.width, (int)area.size.height
};
}
}
}
#endif
| {'repo_name': 'higan-emu/higan', 'stars': '245', 'repo_language': 'C++', 'file_name': 'icarus.plist', 'mime_type': 'text/xml', 'hash': -8614862383071647038, 'source_dataset': 'data'} |
===============
Support Library
===============
Abstract
========
This document provides some details on LLVM's Support Library, located in the
source at ``lib/Support`` and ``include/llvm/Support``. The library's purpose
is to shield LLVM from the differences between operating systems for the few
services LLVM needs from the operating system. Much of LLVM is written using
portability features of standard C++. However, in a few areas, system dependent
facilities are needed and the Support Library is the wrapper around those
system calls.
By centralizing LLVM's use of operating system interfaces, we make it possible
for the LLVM tool chain and runtime libraries to be more easily ported to new
platforms since (theoretically) only ``lib/Support`` needs to be ported. This
library also unclutters the rest of LLVM from #ifdef use and special cases for
specific operating systems. Such uses are replaced with simple calls to the
interfaces provided in ``include/llvm/Support``.
Note that the Support Library is not intended to be a complete operating system
wrapper (such as the Adaptive Communications Environment (ACE) or Apache
Portable Runtime (APR)), but only provides the functionality necessary to
support LLVM.
The Support Library was originally referred to as the System Library, written
by Reid Spencer who formulated the design based on similar work originating
from the eXtensible Programming System (XPS). Several people helped with the
effort; especially, Jeff Cohen and Henrik Bach on the Win32 port.
Keeping LLVM Portable
=====================
In order to keep LLVM portable, LLVM developers should adhere to a set of
portability rules associated with the Support Library. Adherence to these rules
should help the Support Library achieve its goal of shielding LLVM from the
variations in operating system interfaces and doing so efficiently. The
following sections define the rules needed to fulfill this objective.
Don't Include System Headers
----------------------------
Except in ``lib/Support``, no LLVM source code should directly ``#include`` a
system header. Care has been taken to remove all such ``#includes`` from LLVM
while ``lib/Support`` was being developed. Specifically this means that header
files like "``unistd.h``", "``windows.h``", "``stdio.h``", and "``string.h``"
are forbidden to be included by LLVM source code outside the implementation of
``lib/Support``.
To obtain system-dependent functionality, existing interfaces to the system
found in ``include/llvm/Support`` should be used. If an appropriate interface is
not available, it should be added to ``include/llvm/Support`` and implemented in
``lib/Support`` for all supported platforms.
Don't Expose System Headers
---------------------------
The Support Library must shield LLVM from **all** system headers. To obtain
system level functionality, LLVM source must
``#include "llvm/Support/Thing.h"`` and nothing else. This means that
``Thing.h`` cannot expose any system header files. This protects LLVM from
accidentally using system specific functionality and only allows it via
the ``lib/Support`` interface.
Use Standard C Headers
----------------------
The **standard** C headers (the ones beginning with "c") are allowed to be
exposed through the ``lib/Support`` interface. These headers and the things they
declare are considered to be platform agnostic. LLVM source files may include
them directly or obtain their inclusion through ``lib/Support`` interfaces.
Use Standard C++ Headers
------------------------
The **standard** C++ headers from the standard C++ library and standard
template library may be exposed through the ``lib/Support`` interface. These
headers and the things they declare are considered to be platform agnostic.
LLVM source files may include them or obtain their inclusion through
``lib/Support`` interfaces.
High Level Interface
--------------------
The entry points specified in the interface of ``lib/Support`` must be aimed at
completing some reasonably high level task needed by LLVM. We do not want to
simply wrap each operating system call. It would be preferable to wrap several
operating system calls that are always used in conjunction with one another by
LLVM.
For example, consider what is needed to execute a program, wait for it to
complete, and return its result code. On Unix, this involves the following
operating system calls: ``getenv``, ``fork``, ``execve``, and ``wait``. The
correct thing for ``lib/Support`` to provide is a function, say
``ExecuteProgramAndWait``, that implements the functionality completely. what
we don't want is wrappers for the operating system calls involved.
There must **not** be a one-to-one relationship between operating system
calls and the Support library's interface. Any such interface function will be
suspicious.
No Unused Functionality
-----------------------
There must be no functionality specified in the interface of ``lib/Support``
that isn't actually used by LLVM. We're not writing a general purpose operating
system wrapper here, just enough to satisfy LLVM's needs. And, LLVM doesn't
need much. This design goal aims to keep the ``lib/Support`` interface small and
understandable which should foster its actual use and adoption.
No Duplicate Implementations
----------------------------
The implementation of a function for a given platform must be written exactly
once. This implies that it must be possible to apply a function's
implementation to multiple operating systems if those operating systems can
share the same implementation. This rule applies to the set of operating
systems supported for a given class of operating system (e.g. Unix, Win32).
No Virtual Methods
------------------
The Support Library interfaces can be called quite frequently by LLVM. In order
to make those calls as efficient as possible, we discourage the use of virtual
methods. There is no need to use inheritance for implementation differences, it
just adds complexity. The ``#include`` mechanism works just fine.
No Exposed Functions
--------------------
Any functions defined by system libraries (i.e. not defined by ``lib/Support``)
must not be exposed through the ``lib/Support`` interface, even if the header
file for that function is not exposed. This prevents inadvertent use of system
specific functionality.
For example, the ``stat`` system call is notorious for having variations in the
data it provides. ``lib/Support`` must not declare ``stat`` nor allow it to be
declared. Instead it should provide its own interface to discovering
information about files and directories. Those interfaces may be implemented in
terms of ``stat`` but that is strictly an implementation detail. The interface
provided by the Support Library must be implemented on all platforms (even
those without ``stat``).
No Exposed Data
---------------
Any data defined by system libraries (i.e. not defined by ``lib/Support``) must
not be exposed through the ``lib/Support`` interface, even if the header file
for that function is not exposed. As with functions, this prevents inadvertent
use of data that might not exist on all platforms.
Minimize Soft Errors
--------------------
Operating system interfaces will generally provide error results for every
little thing that could go wrong. In almost all cases, you can divide these
error results into two groups: normal/good/soft and abnormal/bad/hard. That is,
some of the errors are simply information like "file not found", "insufficient
privileges", etc. while other errors are much harder like "out of space", "bad
disk sector", or "system call interrupted". We'll call the first group "*soft*"
errors and the second group "*hard*" errors.
``lib/Support`` must always attempt to minimize soft errors. This is a design
requirement because the minimization of soft errors can affect the granularity
and the nature of the interface. In general, if you find that you're wanting to
throw soft errors, you must review the granularity of the interface because it
is likely you're trying to implement something that is too low level. The rule
of thumb is to provide interface functions that **can't** fail, except when
faced with hard errors.
For a trivial example, suppose we wanted to add an "``OpenFileForWriting``"
function. For many operating systems, if the file doesn't exist, attempting to
open the file will produce an error. However, ``lib/Support`` should not simply
throw that error if it occurs because its a soft error. The problem is that the
interface function, ``OpenFileForWriting`` is too low level. It should be
``OpenOrCreateFileForWriting``. In the case of the soft "doesn't exist" error,
this function would just create it and then open it for writing.
This design principle needs to be maintained in ``lib/Support`` because it
avoids the propagation of soft error handling throughout the rest of LLVM.
Hard errors will generally just cause a termination for an LLVM tool so don't
be bashful about throwing them.
Rules of thumb:
#. Don't throw soft errors, only hard errors.
#. If you're tempted to throw a soft error, re-think the interface.
#. Handle internally the most common normal/good/soft error conditions
so the rest of LLVM doesn't have to.
No throw Specifications
-----------------------
None of the ``lib/Support`` interface functions may be declared with C++
``throw()`` specifications on them. This requirement makes sure that the
compiler does not insert additional exception handling code into the interface
functions. This is a performance consideration: ``lib/Support`` functions are
at the bottom of many call chains and as such can be frequently called. We
need them to be as efficient as possible. However, no routines in the system
library should actually throw exceptions.
Code Organization
-----------------
Implementations of the Support Library interface are separated by their general
class of operating system. Currently only Unix and Win32 classes are defined
but more could be added for other operating system classifications. To
distinguish which implementation to compile, the code in ``lib/Support`` uses
the ``LLVM_ON_UNIX`` and ``_WIN32`` ``#defines``. Each source file in
``lib/Support``, after implementing the generic (operating system independent)
functionality needs to include the correct implementation using a set of
``#if defined(LLVM_ON_XYZ)`` directives. For example, if we had
``lib/Support/Path.cpp``, we'd expect to see in that file:
.. code-block:: c++
#if defined(LLVM_ON_UNIX)
#include "Unix/Path.inc"
#endif
#if defined(_WIN32)
#include "Windows/Path.inc"
#endif
The implementation in ``lib/Support/Unix/Path.inc`` should handle all Unix
variants. The implementation in ``lib/Support/Windows/Path.inc`` should handle
all Windows variants. What this does is quickly inc the basic class
of operating system that will provide the implementation. The specific details
for a given platform must still be determined through the use of ``#ifdef``.
Consistent Semantics
--------------------
The implementation of a ``lib/Support`` interface can vary drastically between
platforms. That's okay as long as the end result of the interface function is
the same. For example, a function to create a directory is pretty straight
forward on all operating system. System V IPC on the other hand isn't even
supported on all platforms. Instead of "supporting" System V IPC,
``lib/Support`` should provide an interface to the basic concept of
inter-process communications. The implementations might use System V IPC if
that was available or named pipes, or whatever gets the job done effectively
for a given operating system. In all cases, the interface and the
implementation must be semantically consistent.
| {'repo_name': 'google/llvm-propeller', 'stars': '202', 'repo_language': 'C++', 'file_name': 'dbg-value-move-clone.mir', 'mime_type': 'text/plain', 'hash': 8312654352565538642, 'source_dataset': 'data'} |
/*
* Display a MSDOS directory
*
* Emmet P. Gray US Army, HQ III Corps & Fort Hood
* ...!uunet!uiucuxc!fthood!egray Attn: AFZF-DE-ENV
* Directorate of Engineering & Housing
* Environmental Management Office
* Fort Hood, TX 76544-5057
*/
#include <stdio.h>
#include "msdos.h"
int fd; /* the file descriptor for the floppy */
int dir_start; /* starting sector for directory */
int dir_len; /* length of directory (in sectors) */
int dir_entries; /* number of directory entries */
int dir_chain[25]; /* chain of sectors in directory */
int clus_size; /* cluster size (in sectors) */
int fat_len; /* length of FAT table (in sectors) */
int num_clus; /* number of available clusters */
unsigned char *fatbuf; /* the File Allocation Table */
char *mcwd; /* the current working directory */
main(argc, argv)
int argc;
char *argv[];
{
int i, entry, files, blocks, fargn, wide, faked;
long size;
char name[9], ext[4], *date, *time, *convdate(), *convtime();
char *strncpy(), newpath[MAX_PATH], *getname(), *getpath(), *pathname;
char *newfile, *filename, *unixname(), volume[12], *sep;
char *strcpy(), *strcat(), newname[MAX_PATH], *strncat();
void exit(), reset_dir(), free();
struct directory *dir, *search();
if (init(0)) {
fprintf(stderr, "mdir: Cannot initialize diskette\n");
exit(1);
}
/* find the volume label */
reset_dir();
volume[0] = '\0';
for (entry=0; entry<dir_entries; entry++) {
dir = search(entry);
/* if empty */
if (dir->name[0] == 0x0)
break;
/* if not volume label */
if (!(dir->attr & 0x08))
continue;
strncpy(volume, (char *) dir->name, 8);
volume[8] = '\0';
strncat(volume, (char *) dir->ext, 3);
volume[11] = '\0';
break;
}
if (volume[0] == '\0')
printf(" Volume in drive has no label\n");
else
printf(" Volume in drive is %s\n", volume);
fargn = 1;
wide = 0;
/* first argument number */
if (argc > 1) {
if (!strcmp(argv[1], "-w")) {
wide = 1;
fargn = 2;
}
}
/* fake an argument */
faked = 0;
if (argc == fargn) {
faked++;
argc++;
}
files = 0;
for (i=fargn; i<argc; i++) {
if (faked) {
filename = getname(".");
pathname = getpath(".");
}
else {
filename = getname(argv[i]);
pathname = getpath(argv[i]);
}
/* move to first guess subdirectory */
/* required by isdir() */
if (subdir(pathname)) {
free(filename);
free(pathname);
continue;
}
/* is filename really a subdirectory? */
if (isdir(filename)) {
strcpy(newpath, pathname);
if (strcmp(pathname,"/") && strcmp(pathname, "\\")) {
if (*pathname != '\0')
strcat(newpath, "/");
}
strcat(newpath, filename);
/* move to real subdirectory */
if (subdir(newpath)) {
free(filename);
free(pathname);
continue;
}
strcpy(newname, "*");
}
else {
strcpy(newpath, pathname);
strcpy(newname, filename);
}
if (*filename == '\0')
strcpy(newname, "*");
if (*newpath == '/' || *newpath == '\\')
printf(" Directory for %s\n\n", newpath);
else if (!strcmp(newpath, "."))
printf(" Directory for %s\n\n", mcwd);
else {
if (strlen(mcwd) == 1 || !strlen(newpath))
sep = "";
else
sep = "/";
printf(" Directory for %s%s%s\n\n", mcwd, sep, newpath);
}
for (entry=0; entry<dir_entries; entry++) {
dir = search(entry);
/* if empty */
if (dir->name[0] == 0x0)
break;
/* if erased */
if (dir->name[0] == 0xe5)
continue;
/* if a volume label */
if (dir->attr & 0x08)
continue;
strncpy(name, (char *) dir->name, 8);
strncpy(ext, (char *) dir->ext, 3);
name[8] = '\0';
ext[3] = '\0';
newfile = unixname(name, ext);
if (!match(newfile, newname)) {
free(newfile);
continue;
}
free(newfile);
files++;
if (wide && files != 1) {
if (!((files-1) % 5))
putchar('\n');
}
date = convdate(dir->date[1], dir->date[0]);
time = convtime(dir->time[1], dir->time[0]);
size = dir->size[2]*0x10000L + dir->size[1]*0x100 + dir->size[0];
/* is a subdirectory */
if (dir->attr & 0x10) {
if (wide)
printf("%-9.9s%-6.6s", name, ext);
else
printf("%8s %3s <DIR> %s %s\n", name, ext, date, time);
continue;
}
if (wide)
printf("%-9.9s%-6.6s", name, ext);
else
printf("%8s %3s %8d %s %s\n", name, ext, size, date, time);
}
if (argc > 2)
putchar('\n');
free(filename);
free(pathname);
}
blocks = getfree() * MSECSIZ;
if (!files)
printf("File \"%s\" not found\n", newname);
else
printf(" %3d File(s) %6ld bytes free\n", files, blocks);
close(fd);
exit(0);
}
/*
* Get the amount of free space on the diskette
*/
int
getfree()
{
register int i, total;
total = 0;
for (i=2; i<num_clus+2; i++) {
/* if getfat returns zero */
if (!getfat(i))
total += clus_size;
}
return(total);
}
| {'repo_name': 'jbruchon/elks', 'stars': '295', 'repo_language': 'C', 'file_name': 'boot_sect.S', 'mime_type': 'text/x-python', 'hash': 5241881463860328939, 'source_dataset': 'data'} |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleDocumentTypes</key>
<array>
<dict>
<key>CFBundleTypeExtensions</key>
<array>
<string>gltf</string>
</array>
<key>CFBundleTypeIconFile</key>
<string></string>
<key>CFBundleTypeName</key>
<string>glTF</string>
<key>CFBundleTypeOSTypes</key>
<array>
<string>????</string>
</array>
<key>CFBundleTypeRole</key>
<string>Viewer</string>
<key>NSDocumentClass</key>
<string>GLTFSCNDocument</string>
</dict>
<dict>
<key>CFBundleTypeExtensions</key>
<array>
<string>glb</string>
</array>
<key>CFBundleTypeName</key>
<string>glTF (Binary)</string>
<key>CFBundleTypeRole</key>
<string>Viewer</string>
<key>NSDocumentClass</key>
<string>GLTFSCNDocument</string>
</dict>
</array>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIconFile</key>
<string></string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>LSMinimumSystemVersion</key>
<string>$(MACOSX_DEPLOYMENT_TARGET)</string>
<key>NSHumanReadableCopyright</key>
<string>Copyright © 2018 Warren Moore. All rights reserved. glTF and the glTF logo are trademarks of the Khronos Group Inc.</string>
<key>NSMainStoryboardFile</key>
<string>Main</string>
<key>NSPrincipalClass</key>
<string>NSApplication</string>
<key>UTImportedTypeDeclarations</key>
<array>
<dict>
<key>UTTypeDescription</key>
<string>glTF</string>
<key>UTTypeIdentifier</key>
<string>org.khronos.gltf</string>
<key>UTTypeTagSpecification</key>
<dict>
<key>public.filename-extension</key>
<array>
<string>gltf</string>
</array>
<key>public.mime-type</key>
<array>
<string>model/gltf+json</string>
</array>
</dict>
</dict>
<dict>
<key>UTTypeDescription</key>
<string>glTF (Binary)</string>
<key>UTTypeIdentifier</key>
<string>org.khronos.gltf</string>
<key>UTTypeTagSpecification</key>
<dict>
<key>public.filename-extension</key>
<array>
<string>glb</string>
</array>
<key>public.mime-type</key>
<array>
<string>model/gltf-binary</string>
</array>
</dict>
</dict>
</array>
</dict>
</plist>
| {'repo_name': 'warrenm/GLTFKit', 'stars': '122', 'repo_language': 'Objective-C', 'file_name': 'IDEWorkspaceChecks.plist', 'mime_type': 'text/xml', 'hash': -4495493377916750545, 'source_dataset': 'data'} |
<navbar></navbar>
<heading></heading>
<section class="points">
<div class="img">
<img src="http://ogd73ba13.bkt.clouddn.com/80.png" alt="" />
</div>
</section>
| {'repo_name': 'DaoCloud/daochain', 'stars': '115', 'repo_language': 'JavaScript', 'file_name': '2_deploy_contracts.js', 'mime_type': 'text/plain', 'hash': -9050154167671397854, 'source_dataset': 'data'} |
<div class="ordered_block">
<div class="ordered_block_select">
<span>__name_box__</span>
<div class="input_wrapper input_wrapper_select bx-def-margin-sec-left clearfix">
<select class="form_input_select bx-def-font-inputs" name="__name_targets_box__" onchange="oCustomizer.reloadCustomizeBlock(this.value);">
<bx_repeat:targets><option value="__value__" __select__>__name__</option></bx_repeat:targets>
</select>
</div>
</div>
</div> | {'repo_name': 'boonex/dolphin.pro', 'stars': '118', 'repo_language': 'PHP', 'file_name': 'Compressor.php', 'mime_type': 'text/x-php', 'hash': 1273478331283876589, 'source_dataset': 'data'} |
/**
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. jclouds licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jclouds.scriptbuilder.functionloader;
import java.util.concurrent.atomic.AtomicReference;
import com.google.common.util.concurrent.Atomics;
/**
* Means to access the current {@link FunctionLoader} instance;
*/
public class CurrentFunctionLoader {
private static final AtomicReference<FunctionLoader> ref = Atomics.<FunctionLoader>newReference(
BasicFunctionLoader.INSTANCE);
public static FunctionLoader get() {
return ref.get();
}
public static FunctionLoader set(FunctionLoader loader) {
return ref.getAndSet(loader);
}
public static FunctionLoader reset() {
return ref.getAndSet(BasicFunctionLoader.INSTANCE);
}
}
| {'repo_name': 'jclouds/legacy-jclouds', 'stars': '477', 'repo_language': 'Java', 'file_name': 'archetype-metadata.xml', 'mime_type': 'text/xml', 'hash': 1338280399342905988, 'source_dataset': 'data'} |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//+-----------------------------------------------------------------------------
//
//
// $TAG ENGR
// $Module: win_mil_graphics_meta
// $Keywords:
//
// $Description:
// Contains class definition for the render target iterator used in the
// implementation of the meta render target primitive drawing functions.
//
// $ENDTAG
//
//------------------------------------------------------------------------------
#include "precomp.hpp"
//+-----------------------------------------------------------------------------
//
// Member:
// CMetaIterator::CMetaIterator
//
// Synopsis:
// ctor
//
//------------------------------------------------------------------------------
CMetaIterator::CMetaIterator(
__in_ecount(cRT) MetaData *prgMetaData,
UINT cRT,
UINT idxFirstEnabledRT,
bool fUseRTOffset,
__in_ecount_opt(1) CDisplaySet const *pDisplaySet,
__in_ecount_opt(1) CAliasedClip *pAliasedClip,
__deref_opt_inout_ecount(1) CMilRectF const **ppBoundsToAdjust,
__in_ecount_opt(1) CMultiOutSpaceMatrix<CoordinateSpace::LocalRendering> *pTransform,
__in_ecount_opt(1) CContextState *pContextState,
__in_ecount_opt(1) IWGXBitmapSource **ppIBitmapSource
) :
m_firstTransformAdjustor(
!fUseRTOffset ? NULL :
(pTransform != NULL) ? &static_cast<CMultiOutSpaceMatrix<CoordinateSpace::Variant> &>(*pTransform) :
(pContextState == NULL) ? NULL :
pContextState->In3D ? &static_cast<CMultiOutSpaceMatrix<CoordinateSpace::Variant> &>(pContextState->ViewportProjectionModifier3D) :
&static_cast<CMultiOutSpaceMatrix<CoordinateSpace::Variant> &>(pContextState->WorldToDevice)
),
m_boundsAdjustor(ppBoundsToAdjust),
m_aliasedClipAdjustor(
!fUseRTOffset ? NULL :
pContextState ? &pContextState->AliasedClip :
pAliasedClip
),
m_bitmapSourceAdjustor(ppIBitmapSource)
#if DBG_ANALYSIS
,
// If transform adjust is not needed only because of fUseRTOffset being
// false, then just change the Out space while iterating.
m_pDbgToPageOrDeviceTransform(
fUseRTOffset ? NULL :
(pTransform != NULL) ? &static_cast<CMultiOutSpaceMatrix<CoordinateSpace::Variant> &>(*pTransform) :
(pContextState == NULL) ? NULL :
pContextState->In3D ? &static_cast<CMultiOutSpaceMatrix<CoordinateSpace::Variant> &>(pContextState->ViewportProjectionModifier3D) :
&static_cast<CMultiOutSpaceMatrix<CoordinateSpace::Variant> &>(pContextState->WorldToDevice)
)
#endif
{
Assert(prgMetaData[idxFirstEnabledRT].fEnable);
Assert(idxFirstEnabledRT < cRT);
// Don't expect both a transform and context state
Assert(!pTransform || !pContextState);
// Don't expect both an aliased clip and context state
Assert(!pContextState || !pAliasedClip);
m_prgMetaData = prgMetaData;
m_cRT = cRT;
m_idxCurrent = idxFirstEnabledRT;
m_pContextState = pContextState;
m_pDisplaySet = pDisplaySet;
AssertMsg(m_pDisplaySet || !m_pContextState, "Must have display set when there is a ContextState");
m_pFirstTransformAdjustor = &m_firstTransformAdjustor;
m_pAliasedClipAdjustor = &m_aliasedClipAdjustor;
m_pBitmapSourceAdjustor = &m_bitmapSourceAdjustor;
#if DBG_ANALYSIS
if (m_pDbgToPageOrDeviceTransform)
{
m_pDbgToPageOrDeviceTransform->DbgChangeToSpace<CoordinateSpace::PageInPixels,CoordinateSpace::Device>();
}
#endif
}
//+-----------------------------------------------------------------------------
//
// Member:
// CMetaIterator::~CMetaIterator
//
// Synopsis:
// dtor
//
//------------------------------------------------------------------------------
CMetaIterator::~CMetaIterator()
{
#if DBG_ANALYSIS
if (m_pDbgToPageOrDeviceTransform)
{
m_pDbgToPageOrDeviceTransform->DbgChangeToSpace<CoordinateSpace::Device,CoordinateSpace::PageInPixels>();
}
#endif
}
//+-----------------------------------------------------------------------------
//
// Member:
// CMetaIterator::PrepareForIteration
//
// Synopsis:
// Calls BeginPrimitiveAdjust on all adjustors, gathering pointers to the
// objects that require adjustment
//
//------------------------------------------------------------------------------
HRESULT CMetaIterator::PrepareForIteration()
{
HRESULT hr = S_OK;
{
bool fRequiresAdjustment;
IFC(m_firstTransformAdjustor.BeginPrimitiveAdjust(
&fRequiresAdjustment
));
if (!fRequiresAdjustment)
{
m_pFirstTransformAdjustor = NULL;
}
}
m_fAdjustBounds = m_boundsAdjustor.BeginPrimitiveAdjust();
{
bool fRequiresAdjustment;
IFC(m_aliasedClipAdjustor.BeginPrimitiveAdjust(
&fRequiresAdjustment
));
if (!fRequiresAdjustment)
{
m_pAliasedClipAdjustor = NULL;
}
}
{
bool fRequiresAdjustment;
IFC(m_pBitmapSourceAdjustor->BeginPrimitiveAdjust(
&fRequiresAdjustment
));
if (!fRequiresAdjustment)
{
m_pBitmapSourceAdjustor = NULL;
}
}
Cleanup:
RRETURN(hr);
}
//+-----------------------------------------------------------------------------
//
// Member:
// CMetaIterator::SetupForNextInternalRT
//
// Synopsis:
// retrieves the next internal render target, performing any setup work
// necessary to draw to this render target
//
//------------------------------------------------------------------------------
HRESULT CMetaIterator::SetupForNextInternalRT(
__deref_out_ecount(1) IRenderTargetInternal **ppRTInternalNoAddRef
)
{
HRESULT hr = S_OK;
Assert(m_idxCurrent < m_cRT);
Assert(m_prgMetaData[m_idxCurrent].fEnable);
// Active internal render target found.
// Perform BeginDeviceAdjustment and remember this index
// such that post adjustment will occur
IFC(BeginDeviceAdjust(
m_idxCurrent
));
*ppRTInternalNoAddRef = m_prgMetaData[m_idxCurrent].pInternalRT;
Cleanup:
RRETURN(hr);
}
//+-----------------------------------------------------------------------------
//
// Member:
// CMetaIterator::BeginDeviceAdjust
//
// Synopsis:
// Performs the adjustment. Any data that is changed here should be
// restored in EndPrimitiveAdjust
//
//------------------------------------------------------------------------------
HRESULT CMetaIterator::BeginDeviceAdjust(
UINT idx
)
{
HRESULT hr = S_OK;
if (m_pFirstTransformAdjustor)
{
IFC(m_pFirstTransformAdjustor->BeginDeviceAdjust(
m_prgMetaData,
idx
));
}
if (m_fAdjustBounds)
{
m_boundsAdjustor.BeginDeviceAdjust(
m_prgMetaData,
idx
);
}
if (m_pAliasedClipAdjustor)
{
IFC(m_pAliasedClipAdjustor->BeginDeviceAdjust(
m_prgMetaData,
idx
));
}
if (m_pBitmapSourceAdjustor)
{
IFC(m_pBitmapSourceAdjustor->BeginDeviceAdjust(
m_prgMetaData,
idx
));
}
if (m_pContextState)
{
// let rendering objects to know which display is served
m_pContextState->GetDisplaySettingsFromDisplaySet(m_pDisplaySet, idx);
}
Cleanup:
RRETURN(hr);
}
| {'repo_name': 'dotnet/wpf', 'stars': '4556', 'repo_language': 'C#', 'file_name': 'Targets.h', 'mime_type': 'text/x-c', 'hash': -7837273135727366195, 'source_dataset': 'data'} |
/*
* Copyright (c) 2003-2012 Apple Inc. All rights reserved.
*
* @APPLE_OSREFERENCE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. The rights granted to you under the License
* may not be used to create, or enable the creation or redistribution of,
* unlawful or unlicensed copies of an Apple operating system, or to
* circumvent, violate, or enable the circumvention or violation of, any
* terms of an Apple operating system software license agreement.
*
* Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_OSREFERENCE_LICENSE_HEADER_END@
*/
#ifndef _PTHREAD_MUTEXATTR_T
#define _PTHREAD_MUTEXATTR_T
typedef __darwin_pthread_mutexattr_t pthread_mutexattr_t;
#endif /* _PTHREAD_MUTEXATTR_T */
| {'repo_name': 'theos/sdks', 'stars': '275', 'repo_language': 'Objective-C', 'file_name': 'TextInput_cs.tbd', 'mime_type': 'text/plain', 'hash': 4056137844923397370, 'source_dataset': 'data'} |
/*! normalize.css v2.1.3 | MIT License | git.io/normalize */
// ==========================================================================
// HTML5 display definitions
// ==========================================================================
//
// Correct `block` display not defined in IE 8/9.
//
article,
aside,
details,
figcaption,
figure,
footer,
header,
hgroup,
main,
nav,
section,
summary {
display: block;
}
//
// Correct `inline-block` display not defined in IE 8/9.
//
audio,
canvas,
video {
display: inline-block;
}
//
// Prevent modern browsers from displaying `audio` without controls.
// Remove excess height in iOS 5 devices.
//
audio:not([controls]) {
display: none;
height: 0;
}
//
// Address `[hidden]` styling not present in IE 8/9.
// Hide the `template` element in IE, Safari, and Firefox < 22.
//
[hidden],
template {
display: none;
}
// ==========================================================================
// Base
// ==========================================================================
//
// 1. Set default font family to sans-serif.
// 2. Prevent iOS text size adjust after orientation change, without disabling
// user zoom.
//
html {
font-family: sans-serif; // 1
-ms-text-size-adjust: 100%; // 2
-webkit-text-size-adjust: 100%; // 2
}
//
// Remove default margin.
//
body {
margin: 0;
}
// ==========================================================================
// Links
// ==========================================================================
//
// Remove the gray background color from active links in IE 10.
//
a {
background: transparent;
}
//
// Address `outline` inconsistency between Chrome and other browsers.
//
a:focus {
outline: thin dotted;
}
//
// Improve readability when focused and also mouse hovered in all browsers.
//
a:active,
a:hover {
outline: 0;
}
// ==========================================================================
// Typography
// ==========================================================================
//
// Address variable `h1` font-size and margin within `section` and `article`
// contexts in Firefox 4+, Safari 5, and Chrome.
//
h1 {
font-size: 2em;
margin: 0.67em 0;
}
//
// Address styling not present in IE 8/9, Safari 5, and Chrome.
//
abbr[title] {
border-bottom: 1px dotted;
}
//
// Address style set to `bolder` in Firefox 4+, Safari 5, and Chrome.
//
b,
strong {
font-weight: bold;
}
//
// Address styling not present in Safari 5 and Chrome.
//
dfn {
font-style: italic;
}
//
// Address differences between Firefox and other browsers.
//
hr {
-moz-box-sizing: content-box;
box-sizing: content-box;
height: 0;
}
//
// Address styling not present in IE 8/9.
//
mark {
background: #ff0;
color: #000;
}
//
// Correct font family set oddly in Safari 5 and Chrome.
//
code,
kbd,
pre,
samp {
font-family: monospace, serif;
font-size: 1em;
}
//
// Improve readability of pre-formatted text in all browsers.
//
pre {
white-space: pre-wrap;
}
//
// Set consistent quote types.
//
q {
quotes: "\201C" "\201D" "\2018" "\2019";
}
//
// Address inconsistent and variable font size in all browsers.
//
small {
font-size: 80%;
}
//
// Prevent `sub` and `sup` affecting `line-height` in all browsers.
//
sub,
sup {
font-size: 75%;
line-height: 0;
position: relative;
vertical-align: baseline;
}
sup {
top: -0.5em;
}
sub {
bottom: -0.25em;
}
// ==========================================================================
// Embedded content
// ==========================================================================
//
// Remove border when inside `a` element in IE 8/9.
//
img {
border: 0;
}
//
// Correct overflow displayed oddly in IE 9.
//
svg:not(:root) {
overflow: hidden;
}
// ==========================================================================
// Figures
// ==========================================================================
//
// Address margin not present in IE 8/9 and Safari 5.
//
figure {
margin: 0;
}
// ==========================================================================
// Forms
// ==========================================================================
//
// Define consistent border, margin, and padding.
//
fieldset {
border: 1px solid #c0c0c0;
margin: 0 2px;
padding: 0.35em 0.625em 0.75em;
}
//
// 1. Correct `color` not being inherited in IE 8/9.
// 2. Remove padding so people aren't caught out if they zero out fieldsets.
//
legend {
border: 0; // 1
padding: 0; // 2
}
//
// 1. Correct font family not being inherited in all browsers.
// 2. Correct font size not being inherited in all browsers.
// 3. Address margins set differently in Firefox 4+, Safari 5, and Chrome.
//
button,
input,
select,
textarea {
font-family: inherit; // 1
font-size: 100%; // 2
margin: 0; // 3
}
//
// Address Firefox 4+ setting `line-height` on `input` using `!important` in
// the UA stylesheet.
//
button,
input {
line-height: normal;
}
//
// Address inconsistent `text-transform` inheritance for `button` and `select`.
// All other form control elements do not inherit `text-transform` values.
// Correct `button` style inheritance in Chrome, Safari 5+, and IE 8+.
// Correct `select` style inheritance in Firefox 4+ and Opera.
//
button,
select {
text-transform: none;
}
//
// 1. Avoid the WebKit bug in Android 4.0.* where (2) destroys native `audio`
// and `video` controls.
// 2. Correct inability to style clickable `input` types in iOS.
// 3. Improve usability and consistency of cursor style between image-type
// `input` and others.
//
button,
html input[type="button"], // 1
input[type="reset"],
input[type="submit"] {
-webkit-appearance: button; // 2
cursor: pointer; // 3
}
//
// Re-set default cursor for disabled elements.
//
button[disabled],
html input[disabled] {
cursor: default;
}
//
// 1. Address box sizing set to `content-box` in IE 8/9/10.
// 2. Remove excess padding in IE 8/9/10.
//
input[type="checkbox"],
input[type="radio"] {
box-sizing: border-box; // 1
padding: 0; // 2
}
//
// 1. Address `appearance` set to `searchfield` in Safari 5 and Chrome.
// 2. Address `box-sizing` set to `border-box` in Safari 5 and Chrome
// (include `-moz` to future-proof).
//
input[type="search"] {
-webkit-appearance: textfield; // 1
-moz-box-sizing: content-box;
-webkit-box-sizing: content-box; // 2
box-sizing: content-box;
}
//
// Remove inner padding and search cancel button in Safari 5 and Chrome
// on OS X.
//
input[type="search"]::-webkit-search-cancel-button,
input[type="search"]::-webkit-search-decoration {
-webkit-appearance: none;
}
//
// Remove inner padding and border in Firefox 4+.
//
button::-moz-focus-inner,
input::-moz-focus-inner {
border: 0;
padding: 0;
}
//
// 1. Remove default vertical scrollbar in IE 8/9.
// 2. Improve readability and alignment in all browsers.
//
textarea {
overflow: auto; // 1
vertical-align: top; // 2
}
// ==========================================================================
// Tables
// ==========================================================================
//
// Remove most spacing between table cells.
//
table {
border-collapse: collapse;
border-spacing: 0;
}
| {'repo_name': 'ironbane/IronbaneServerLegacy', 'stars': '172', 'repo_language': 'JavaScript', 'file_name': 'tests.js', 'mime_type': 'text/plain', 'hash': 8459004796081784366, 'source_dataset': 'data'} |
package goworker
import (
"fmt"
"math/rand"
"os"
"strings"
"time"
)
type process struct {
Hostname string
Pid int
ID string
Queues []string
}
func newProcess(id string, queues []string) (*process, error) {
hostname, err := os.Hostname()
if err != nil {
return nil, err
}
return &process{
Hostname: hostname,
Pid: os.Getpid(),
ID: id,
Queues: queues,
}, nil
}
func (p *process) String() string {
return fmt.Sprintf("%s:%d-%s:%s", p.Hostname, p.Pid, p.ID, strings.Join(p.Queues, ","))
}
func (p *process) open(conn *RedisConn) error {
conn.Send("SADD", fmt.Sprintf("%sworkers", workerSettings.Namespace), p)
conn.Send("SET", fmt.Sprintf("%sstat:processed:%v", workerSettings.Namespace, p), "0")
conn.Send("SET", fmt.Sprintf("%sstat:failed:%v", workerSettings.Namespace, p), "0")
conn.Flush()
return nil
}
func (p *process) close(conn *RedisConn) error {
logger.Infof("%v shutdown", p)
conn.Send("SREM", fmt.Sprintf("%sworkers", workerSettings.Namespace), p)
conn.Send("DEL", fmt.Sprintf("%sstat:processed:%s", workerSettings.Namespace, p))
conn.Send("DEL", fmt.Sprintf("%sstat:failed:%s", workerSettings.Namespace, p))
conn.Flush()
return nil
}
func (p *process) start(conn *RedisConn) error {
conn.Send("SET", fmt.Sprintf("%sworker:%s:started", workerSettings.Namespace, p), time.Now().String())
conn.Flush()
return nil
}
func (p *process) finish(conn *RedisConn) error {
conn.Send("DEL", fmt.Sprintf("%sworker:%s", workerSettings.Namespace, p))
conn.Send("DEL", fmt.Sprintf("%sworker:%s:started", workerSettings.Namespace, p))
conn.Flush()
return nil
}
func (p *process) fail(conn *RedisConn) error {
conn.Send("INCR", fmt.Sprintf("%sstat:failed", workerSettings.Namespace))
conn.Send("INCR", fmt.Sprintf("%sstat:failed:%s", workerSettings.Namespace, p))
conn.Flush()
return nil
}
func (p *process) queues(strict bool) []string {
// If the queues order is strict then just return them.
if strict {
return p.Queues
}
// If not then we want to to shuffle the queues before returning them.
queues := make([]string, len(p.Queues))
for i, v := range rand.Perm(len(p.Queues)) {
queues[i] = p.Queues[v]
}
return queues
}
| {'repo_name': 'benmanns/goworker', 'stars': '2425', 'repo_language': 'Go', 'file_name': 'go.yml', 'mime_type': 'text/plain', 'hash': -873627425819689684, 'source_dataset': 'data'} |
### TEMPLATE.txt.tpl; coding: utf-8 ---
# Author(s): Christophe Prud'homme <[email protected]>
# Date: 2020-01-20
#
# Copyright (C) 2013-2020 Feel++ Consortium
#
# Distributed under the GPL(GNU Public License):
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#
#
##
## Archive generation using cpack
##
if (UNIX)
execute_process(
COMMAND uname -m
OUTPUT_VARIABLE FEELPP_SYSTEM_MACHINE
OUTPUT_STRIP_TRAILING_WHITESPACE
ERROR_VARIABLE FEELPP_SYSTEM_MACHINE_error
RESULT_VARIABLE FEELPP_SYSTEM_MACHINE_result)
endif()
SET(CPACK_PACKAGE_NAME "feelpp-toolboxes")
SET(CPACK_GENERATOR "TGZ")
SET(CPACK_PACKAGE_DESCRIPTION_SUMMARY "Feel++ Toolboxes")
SET(CPACK_PACKAGE_VENDOR "Christophe Prud'homme")
SET(CPACK_PACKAGE_DESCRIPTION_FILE "${CMAKE_SOURCE_DIR}/README.adoc")
SET(CPACK_RESOURCE_FILE_LICENSE "${CMAKE_SOURCE_DIR}/COPYING.adoc")
SET(CPACK_PACKAGE_VERSION_MAJOR "${FEELPP_VERSION_MAJOR}")
SET(CPACK_PACKAGE_VERSION_MINOR "${FEELPP_VERSION_MINOR}")
SET(CPACK_PACKAGE_VERSION_PATCH "${FEELPP_VERSION_MICRO}")
SET(CPACK_PACKAGE_INSTALL_DIRECTORY "feelpp-toolboxes")
SET(CPACK_SOURCE_GENERATOR "TGZ")
SET(CPACK_SOURCE_OUTPUT_CONFIG_FILE "CPackSourceConfig.cmake")
SET(CPACK_SYSTEM_NAME "${FEELPP_OS}-${FEELPP_SYSTEM_MACHINE}")
SET(CPACK_PACKAGE_NAME "feelpp-toolboxes")
SET(CPACK_PACKAGE_DESCRIPTION_SUMMARY "Feel++ Toolboxes")
SET(CPACK_SOURCE_PACKAGE_FILE_NAME "${CPACK_PACKAGE_NAME}-${FEELPP_VERSION_MAJOR}.${FEELPP_VERSION_MINOR}.${FEELPP_VERSION_MICRO}${FEELPP_VERSION_PRERELEASE}${FEELPP_VERSION_METADATA}")
SET(CPACK_SOURCE_STRIP_FILES "")
# The following components are regex's to match anywhere (unless anchored)
# in absolute path + filename to find files or directories to be excluded
# from source tarball.
set(CPACK_SOURCE_IGNORE_FILES
"/\\\\.git/;\\\\.gitignore;/\\\\.svn;"
"/.git;"
"/admin/;/Templates/;"
"/auto/;/ltxpng/;"
"/TAGS;/#.*;/.*~$;/*.log$;/.cvsignore;/.bzrignore;/work/;/autom4te.cache/"
)
include( CPack )
| {'repo_name': 'feelpp/feelpp', 'stars': '203', 'repo_language': 'C++', 'file_name': 'aneurysm.geo', 'mime_type': 'text/plain', 'hash': 2021732163507463082, 'source_dataset': 'data'} |
<template>
video[controls]
<video data-focus="video" width="1" height="1"></video>
<video data-focus="videoControls" controls width="1" height="1"></video>
</template>
| {'repo_name': 'salesforce/lwc', 'stars': '809', 'repo_language': 'JavaScript', 'file_name': 'config.yml', 'mime_type': 'text/plain', 'hash': -3519010752090783507, 'source_dataset': 'data'} |
<?php
/* vim: set shiftwidth=2 expandtab softtabstop=2: */
namespace Boris;
/**
* The Readline client is what the user spends their time entering text into.
*
* Input is collected and sent to {@link \Boris\EvalWorker} for processing.
*/
class ReadlineClient {
private $_socket;
private $_prompt;
private $_historyFile;
private $_clear = false;
/**
* Create a new ReadlineClient using $socket for communication.
*
* @param resource $socket
*/
public function __construct($socket) {
$this->_socket = $socket;
}
/**
* Start the client with an prompt and readline history path.
*
* This method never returns.
*
* @param string $prompt
* @param string $historyFile
*/
public function start($prompt, $historyFile) {
readline_read_history($historyFile);
declare(ticks = 1);
pcntl_signal(SIGCHLD, SIG_IGN);
pcntl_signal(SIGINT, array($this, 'clear'), true);
// wait for the worker to finish executing hooks
if (fread($this->_socket, 1) != EvalWorker::READY) {
throw new \RuntimeException('EvalWorker failed to start');
}
$parser = new ShallowParser();
$buf = '';
$lineno = 1;
for (;;) {
$this->_clear = false;
$line = readline(
sprintf(
'[%d] %s',
$lineno,
($buf == ''
? $prompt
: str_pad('*> ', strlen($prompt), ' ', STR_PAD_LEFT))
)
);
if ($this->_clear) {
$buf = '';
continue;
}
if (false === $line) {
$buf = 'exit(0);'; // ctrl-d acts like exit
}
if (strlen($line) > 0) {
readline_add_history($line);
}
$buf .= sprintf("%s\n", $line);
if ($statements = $parser->statements($buf)) {
++$lineno;
$buf = '';
foreach ($statements as $stmt) {
if (false === $written = fwrite($this->_socket, $stmt)) {
throw new \RuntimeException('Socket error: failed to write data');
}
if ($written > 0) {
$status = fread($this->_socket, 1);
if ($status == EvalWorker::EXITED) {
readline_write_history($historyFile);
echo "\n";
exit(0);
} elseif ($status == EvalWorker::FAILED) {
break;
}
}
}
}
}
}
/**
* Clear the input buffer.
*/
public function clear() {
// FIXME: I'd love to have this send \r to readline so it puts the user on a blank line
$this->_clear = true;
}
}
| {'repo_name': '5-say/laravel-4.1-quick-start-cn', 'stars': '144', 'repo_language': 'PHP', 'file_name': 'github.css', 'mime_type': 'text/plain', 'hash': 7954457642401566209, 'source_dataset': 'data'} |
/*
* Copyright (C) 2017 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "JSMarkingConstraintPrivate.h"
#include "APICast.h"
#include "JSCInlines.h"
#include "SimpleMarkingConstraint.h"
using namespace JSC;
namespace {
Atomic<unsigned> constraintCounter;
struct Marker : JSMarker {
SlotVisitor* visitor;
};
bool isMarked(JSMarkerRef markerRef, JSObjectRef objectRef)
{
if (!objectRef)
return true; // Null is an immortal object.
return static_cast<Marker*>(markerRef)->visitor->vm().heap.isMarked(toJS(objectRef));
}
void mark(JSMarkerRef markerRef, JSObjectRef objectRef)
{
if (!objectRef)
return;
static_cast<Marker*>(markerRef)->visitor->appendHiddenUnbarriered(toJS(objectRef));
}
} // anonymous namespace
void JSContextGroupAddMarkingConstraint(JSContextGroupRef group, JSMarkingConstraint constraintCallback, void *userData)
{
VM& vm = *toJS(group);
JSLockHolder locker(vm);
unsigned constraintIndex = constraintCounter.exchangeAdd(1);
// This is a guess. The algorithm should be correct no matter what we pick. This means
// that we expect this constraint to mark things even during a stop-the-world full GC, but
// we don't expect it to be able to mark anything at the very start of a GC before anything
// else gets marked.
ConstraintVolatility volatility = ConstraintVolatility::GreyedByMarking;
auto constraint = std::make_unique<SimpleMarkingConstraint>(
toCString("Amc", constraintIndex, "(", RawPointer(bitwise_cast<void*>(constraintCallback)), ")"),
toCString("API Marking Constraint #", constraintIndex, " (", RawPointer(bitwise_cast<void*>(constraintCallback)), ", ", RawPointer(userData), ")"),
[constraintCallback, userData]
(SlotVisitor& slotVisitor) {
Marker marker;
marker.IsMarked = isMarked;
marker.Mark = mark;
marker.visitor = &slotVisitor;
constraintCallback(&marker, userData);
},
volatility,
ConstraintConcurrency::Sequential);
vm.heap.addMarkingConstraint(WTFMove(constraint));
}
| {'repo_name': 'mbbill/JSC.js', 'stars': '279', 'repo_language': 'C++', 'file_name': 'updateGN.md', 'mime_type': 'text/plain', 'hash': 3802004939018551231, 'source_dataset': 'data'} |
<?php
/*
* This file is part of the Monolog package.
*
* (c) Jonathan A. Schweder <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog\Processor;
use Monolog\TestCase;
class MercurialProcessorTest extends TestCase
{
/**
* @covers Monolog\Processor\MercurialProcessor::__invoke
*/
public function testProcessor()
{
if (defined('PHP_WINDOWS_VERSION_BUILD')) {
exec("where hg 2>NUL", $output, $result);
} else {
exec("which hg 2>/dev/null >/dev/null", $output, $result);
}
if ($result != 0) {
$this->markTestSkipped('hg is missing');
return;
}
`hg init`;
$processor = new MercurialProcessor();
$record = $processor($this->getRecord());
$this->assertArrayHasKey('hg', $record['extra']);
$this->assertTrue(!is_array($record['extra']['hg']['branch']));
$this->assertTrue(!is_array($record['extra']['hg']['revision']));
}
}
| {'repo_name': 'woann/chat', 'stars': '208', 'repo_language': 'PHP', 'file_name': 'demo-1.js', 'mime_type': 'text/plain', 'hash': 2804170736226767632, 'source_dataset': 'data'} |
/*
* libqos driver framework
*
* Copyright (c) 2019 Red Hat, Inc.
*
* Author: Paolo Bonzini <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1 as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, see <http://www.gnu.org/licenses/>
*/
#include "qemu/osdep.h"
#include "libqtest.h"
#include "malloc.h"
#include "qgraph.h"
#include "i2c.h"
#define ARM_PAGE_SIZE 4096
#define N800_RAM_START 0x80000000
#define N800_RAM_END 0x88000000
typedef struct QN800Machine QN800Machine;
struct QN800Machine {
QOSGraphObject obj;
QGuestAllocator alloc;
OMAPI2C i2c_1;
};
static void *n800_get_driver(void *object, const char *interface)
{
QN800Machine *machine = object;
if (!g_strcmp0(interface, "memory")) {
return &machine->alloc;
}
fprintf(stderr, "%s not present in arm/n800\n", interface);
g_assert_not_reached();
}
static QOSGraphObject *n800_get_device(void *obj, const char *device)
{
QN800Machine *machine = obj;
if (!g_strcmp0(device, "omap_i2c")) {
return &machine->i2c_1.obj;
}
fprintf(stderr, "%s not present in arm/n800\n", device);
g_assert_not_reached();
}
static void n800_destructor(QOSGraphObject *obj)
{
QN800Machine *machine = (QN800Machine *) obj;
alloc_destroy(&machine->alloc);
}
static void *qos_create_machine_arm_n800(QTestState *qts)
{
QN800Machine *machine = g_new0(QN800Machine, 1);
alloc_init(&machine->alloc, 0,
N800_RAM_START,
N800_RAM_END,
ARM_PAGE_SIZE);
machine->obj.get_device = n800_get_device;
machine->obj.get_driver = n800_get_driver;
machine->obj.destructor = n800_destructor;
omap_i2c_init(&machine->i2c_1, qts, 0x48070000);
return &machine->obj;
}
static void n800_register_nodes(void)
{
QOSGraphEdgeOptions edge = {
.extra_device_opts = "bus=i2c-bus.0"
};
qos_node_create_machine("arm/n800", qos_create_machine_arm_n800);
qos_node_contains("arm/n800", "omap_i2c", &edge, NULL);
}
libqos_init(n800_register_nodes);
| {'repo_name': 'qemu/qemu', 'stars': '3749', 'repo_language': 'C', 'file_name': 'tcg-target.h', 'mime_type': 'text/x-c', 'hash': -8796631764087178052, 'source_dataset': 'data'} |
// Body
$body-bg: #f8fafc;
// Typography
$font-family-sans-serif: "Nunito", sans-serif;
$font-size-base: 0.9rem;
$line-height-base: 1.6;
// Colors
$blue: #3490dc;
$indigo: #6574cd;
$purple: #9561e2;
$pink: #f66D9b;
$red: #e3342f;
$orange: #f6993f;
$yellow: #ffed4a;
$green: #38c172;
$teal: #4dc0b5;
$cyan: #6cb2eb;
| {'repo_name': 'vanilophp/demo', 'stars': '104', 'repo_language': 'PHP', 'file_name': 'browserconfig.xml', 'mime_type': 'text/xml', 'hash': -5785948795256851934, 'source_dataset': 'data'} |
/*
Copyright (c) Facebook, Inc. and its affiliates.
All rights reserved.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree.
*/
package recorders_test
import (
"io/ioutil"
"testing"
"github.com/gosuri/uiprogress"
"github.com/pinterest/bender"
"github.com/stretchr/testify/suite"
"github.com/facebookincubator/fbender/recorders"
)
type ProgressBarRecorderTestSuite struct {
suite.Suite
progress *uiprogress.Progress
bar *uiprogress.Bar
recorder chan interface{}
progressRecorder bender.Recorder
}
func (s *ProgressBarRecorderTestSuite) SetupTest() {
s.progress = uiprogress.New()
s.progress.SetOut(ioutil.Discard)
s.progress.Start()
s.bar = s.progress.AddBar(10)
s.recorder = make(chan interface{}, 1)
s.progressRecorder = recorders.NewProgressBarRecorder(s.bar)
}
func (s *ProgressBarRecorderTestSuite) TearDownTest() {
s.progress.Stop()
}
func (s *ProgressBarRecorderTestSuite) recordSingleEvent(event interface{}) {
s.recorder <- event
close(s.recorder)
bender.Record(s.recorder, s.progressRecorder)
}
func (s *ProgressBarRecorderTestSuite) TestStartEvent() {
s.recordSingleEvent(new(bender.StartEvent))
s.Equal(0, s.bar.Current())
}
func (s *ProgressBarRecorderTestSuite) TestEndEvent() {
s.recordSingleEvent(new(bender.EndEvent))
s.Equal(0, s.bar.Current())
}
func (s *ProgressBarRecorderTestSuite) TestWaitEvent() {
s.recordSingleEvent(new(bender.WaitEvent))
s.Equal(0, s.bar.Current())
}
func (s *ProgressBarRecorderTestSuite) TestStartRequestEvent() {
s.recordSingleEvent(new(bender.StartRequestEvent))
s.Equal(0, s.bar.Current())
}
func (s *ProgressBarRecorderTestSuite) TestEndRequestEvent() {
s.recordSingleEvent(new(bender.EndRequestEvent))
s.Equal(1, s.bar.Current())
}
func TestProgressBarRecorderTestSuite(t *testing.T) {
suite.Run(t, new(ProgressBarRecorderTestSuite))
}
| {'repo_name': 'facebookincubator/fbender', 'stars': '218', 'repo_language': 'Go', 'file_name': 'runner.go', 'mime_type': 'text/plain', 'hash': 141111026470735036, 'source_dataset': 'data'} |
#ifndef HW_MCF_H
#define HW_MCF_H
/* Motorola ColdFire device prototypes. */
#include "target/m68k/cpu-qom.h"
/* mcf_uart.c */
uint64_t mcf_uart_read(void *opaque, hwaddr addr,
unsigned size);
void mcf_uart_write(void *opaque, hwaddr addr,
uint64_t val, unsigned size);
void *mcf_uart_init(qemu_irq irq, Chardev *chr);
void mcf_uart_mm_init(hwaddr base, qemu_irq irq, Chardev *chr);
/* mcf_intc.c */
qemu_irq *mcf_intc_init(struct MemoryRegion *sysmem,
hwaddr base,
M68kCPU *cpu);
/* mcf5206.c */
qemu_irq *mcf5206_init(struct MemoryRegion *sysmem,
uint32_t base, M68kCPU *cpu);
#endif
| {'repo_name': 'Comsecuris/luaqemu', 'stars': '109', 'repo_language': 'C', 'file_name': 'tcg-target.h', 'mime_type': 'text/x-c', 'hash': 2534683599699962367, 'source_dataset': 'data'} |
{
"name": "merge-descriptors",
"description": "Merge objects using descriptors",
"version": "1.0.1",
"author": {
"name": "Jonathan Ong",
"email": "[email protected]",
"url": "http://jongleberry.com",
"twitter": "https://twitter.com/jongleberry"
},
"contributors": [
"Douglas Christopher Wilson <[email protected]>",
"Mike Grabowski <[email protected]>"
],
"license": "MIT",
"repository": "component/merge-descriptors",
"devDependencies": {
"istanbul": "0.4.1",
"mocha": "1.21.5"
},
"files": [
"HISTORY.md",
"LICENSE",
"README.md",
"index.js"
],
"scripts": {
"test": "mocha --reporter spec --bail --check-leaks test/",
"test-ci": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/",
"test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/"
},
"_from": "[email protected]",
"_resolved": "http://registry.npm.taobao.org/merge-descriptors/download/merge-descriptors-1.0.1.tgz"
} | {'repo_name': 'htmlk/express', 'stars': '156', 'repo_language': 'JavaScript', 'file_name': 'index.jade', 'mime_type': 'text/plain', 'hash': 5767949179910395527, 'source_dataset': 'data'} |
/*
* ReactOS RosPerf - ReactOS GUI performance test program
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#ifndef ROSPERF_H_INCLUDED
#define ROSPERF_H_INCLUDED
typedef struct tagPERF_INFO
{
HWND Wnd;
unsigned Seconds;
unsigned Repeats;
COLORREF ForegroundColor;
COLORREF BackgroundColor;
HDC ForegroundDc;
HDC BackgroundDc;
INT WndWidth;
INT WndHeight;
} PERF_INFO, *PPERF_INFO;
typedef unsigned (*INITTESTPROC)(void **Context, PPERF_INFO PerfInfo, unsigned Reps);
typedef void (*TESTPROC)(void *Context, PPERF_INFO PerfInfo, unsigned Reps);
typedef void (*CLEANUPTESTPROC)(void *Context, PPERF_INFO PerfInfo);
typedef struct tagTEST
{
LPCWSTR Option;
LPCWSTR Label;
INITTESTPROC Init;
TESTPROC Proc;
CLEANUPTESTPROC PassCleanup;
CLEANUPTESTPROC Cleanup;
} TEST, *PTEST;
void GetTests(unsigned *TestCount, PTEST *Tests);
/* Tests */
unsigned NullInit(void **Context, PPERF_INFO PerfInfo, unsigned Reps);
void NullCleanup(void *Context, PPERF_INFO PerfInfo);
void FillProc(void *Context, PPERF_INFO PerfInfo, unsigned Reps);
void FillSmallProc(void *Context, PPERF_INFO PerfInfo, unsigned Reps);
void LinesHorizontalProc(void *Context, PPERF_INFO PerfInfo, unsigned Reps);
void LinesVerticalProc(void *Context, PPERF_INFO PerfInfo, unsigned Reps);
void LinesProc(void *Context, PPERF_INFO PerfInfo, unsigned Reps);
void TextProc(void *Context, PPERF_INFO PerfInfo, unsigned Reps);
unsigned AlphaBlendInit(void **Context, PPERF_INFO PerfInfo, unsigned Reps);
void AlphaBlendCleanup(void *Context, PPERF_INFO PerfInfo);
void AlphaBlendProc(void *Context, PPERF_INFO PerfInfo, unsigned Reps);
void GradientHorizontalProc(void *Context, PPERF_INFO PerfInfo, unsigned Reps);
void GradientVerticalProc(void *Context, PPERF_INFO PerfInfo, unsigned Reps);
void GradientProc(void *Context, PPERF_INFO PerfInfo, unsigned Reps);
void ScrollProc(void *Context, PPERF_INFO PerfInfo, unsigned Reps);
#endif /* ROSPERF_H_INCLUDED */
/* EOF */
| {'repo_name': 'reactos/reactos-deprecated-gitsvn-dont-use', 'stars': '307', 'repo_language': 'C', 'file_name': 'options.c', 'mime_type': 'text/x-c', 'hash': 4067390722506155609, 'source_dataset': 'data'} |
/******************************************************************************
* Copyright (C) 2017, Huada Semiconductor Co.,Ltd All rights reserved.
*
* This software is owned and published by:
* Huada Semiconductor Co.,Ltd ("HDSC").
*
* BY DOWNLOADING, INSTALLING OR USING THIS SOFTWARE, YOU AGREE TO BE BOUND
* BY ALL THE TERMS AND CONDITIONS OF THIS AGREEMENT.
*
* This software contains source code for use with HDSC
* components. This software is licensed by HDSC to be adapted only
* for use in systems utilizing HDSC components. HDSC shall not be
* responsible for misuse or illegal use of this software for devices not
* supported herein. HDSC is providing this software "AS IS" and will
* not be responsible for issues arising from incorrect user implementation
* of the software.
*
* Disclaimer:
* HDSC MAKES NO WARRANTY, EXPRESS OR IMPLIED, ARISING BY LAW OR OTHERWISE,
* REGARDING THE SOFTWARE (INCLUDING ANY ACOOMPANYING WRITTEN MATERIALS),
* ITS PERFORMANCE OR SUITABILITY FOR YOUR INTENDED USE, INCLUDING,
* WITHOUT LIMITATION, THE IMPLIED WARRANTY OF MERCHANTABILITY, THE IMPLIED
* WARRANTY OF FITNESS FOR A PARTICULAR PURPOSE OR USE, AND THE IMPLIED
* WARRANTY OF NONINFRINGEMENT.
* HDSC SHALL HAVE NO LIABILITY (WHETHER IN CONTRACT, WARRANTY, TORT,
* NEGLIGENCE OR OTHERWISE) FOR ANY DAMAGES WHATSOEVER (INCLUDING, WITHOUT
* LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS, BUSINESS INTERRUPTION,
* LOSS OF BUSINESS INFORMATION, OR OTHER PECUNIARY LOSS) ARISING FROM USE OR
* INABILITY TO USE THE SOFTWARE, INCLUDING, WITHOUT LIMITATION, ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL OR CONSEQUENTIAL DAMAGES OR LOSS OF DATA,
* SAVINGS OR PROFITS,
* EVEN IF Disclaimer HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
* YOU ASSUME ALL RESPONSIBILITIES FOR SELECTION OF THE SOFTWARE TO ACHIEVE YOUR
* INTENDED RESULTS, AND FOR THE INSTALLATION OF, USE OF, AND RESULTS OBTAINED
* FROM, THE SOFTWARE.
*
* This software may be replicated in part or whole for the licensed use,
* with the restriction that this Disclaimer and Copyright notice must be
* included with each copy of this software, whether used in part or whole,
* at all times.
*/
/*****************************************************************************/
/** \file rtc.h
**
** Headerfile for RTC functions
**
**
** History:
** - 2017-05-10 Cathy First Version
**
*****************************************************************************/
#ifndef __RTC_H__
#define __RTC_H__
/*****************************************************************************
* Include files
*****************************************************************************/
#include "ddl.h"
#include "interrupts_hc32l136.h"
#ifdef __cplusplus
extern "C"
{
#endif
/**
******************************************************************************
** \defgroup RtcGroup Real Time Clock (RTC)
**
******************************************************************************/
//@{
/******************************************************************************/
/* Global pre-processor symbols/macros ('#define') */
/******************************************************************************/
/******************************************************************************
* Global type definitions
******************************************************************************/
/**
******************************************************************************
** \brief rtc时钟源选择
*****************************************************************************/
typedef enum en_rtc_clk
{
RtcClk32768 = 0u, ///<外部32.768k
RtcClk32768_1 = 1u, ///<外部32.768k
RtcClk32 = 2u, ///<内部RC32
RtcClk32_1 = 3u, ///<内部RC32
RtcClkHxt128 = 4u, ///<外部晶振4M
RtcClkHxt256 = 5u, ///<外部晶振8M
RtcClkHxt512 = 6u, ///<外部晶振16M
RtcClkHxt1024 = 7u, ///<外部晶振32M
}en_rtc_clk_t;
/**
******************************************************************************
** \brief rtc周期中断方式选择
*****************************************************************************/
typedef enum en_rtc_cyc
{
RtcPrads = 0u, ///<月、天、时分秒
RtcPradx = 1u, ///<step 0.5s
}en_rtc_cyc_t;
/**
******************************************************************************
** \brief rtc 12h制或24h制方式选择
*****************************************************************************/
typedef enum en_rtc_ampm
{
Rtc12h = 0u, ///<12h
Rtc24h = 1u, ///<24h
}en_rtc_ampm_t;
/**
******************************************************************************
** \brief prds中断周期
*****************************************************************************/
typedef enum en_rtc_cycprds
{
Rtc_None = 0u, ///<无周期中断
Rtc_05S = 1u, ///<0.5S中断
Rtc_1S = 2u, ///<1s
Rtc_1Min = 3u, ///<1min
Rtc_1H = 4u, ///<1h
Rtc_1Day = 5u, ///<1d
Rtc_1Mon = 6u, ///<1月
Rtc_1Mon_1 = 7u, ///<1月
}en_rtc_cycprds_t;
/**
******************************************************************************
** \brief rtc周期中断总配置
*****************************************************************************/
typedef struct stc_rtc_cyc_sel
{
en_rtc_cyc_t enCyc_sel; ///<周期类型配置
en_rtc_cycprds_t enPrds_sel;///<周期配置
uint8_t u8Prdx;
}stc_rtc_cyc_sel_t;
/**
******************************************************************************
** \brief 闹钟源配置
*****************************************************************************/
typedef struct stc_rtc_alarmset
{
uint8_t u8Minute; ///<闹钟分钟
uint8_t u8Hour; ///<闹钟小时
uint8_t u8Week; ///<闹钟周
}stc_rtc_alarmset_t;
/**
******************************************************************************
** \brief 闹钟中断使能设置
*****************************************************************************/
typedef enum en_rtc_alarmirq
{
Rtc_AlarmInt_Disable = 0u,///<闹钟中断禁止
Rtc_AlarmInt_Enable = 1u,///<闹钟中断使能
}en_rtc_alarmirq_t;
/**
******************************************************************************
** \brief rtc 1hz补偿功能开启设置
*****************************************************************************/
typedef enum en_rtc_compen_en
{
Rtc_Comp_Disable = 0u,///<时钟补偿禁止
Rtc_Comp_Enable = 1u,///<时钟补偿使能
}en_rtc_compen_en_t;
/**
******************************************************************************
** \brief rtc计数功能使能设置
*****************************************************************************/
typedef enum en_rtc_count_en
{
Rtc_Count_Disable = 0u,///<计数禁止
Rtc_Count_Enable = 1u,///<计数使能
}en_rtc_count_en_t;
/**
******************************************************************************
** \brief rtc计数模式还是读写模式状态
*****************************************************************************/
typedef enum en_rtc_status
{
RtcRunStatus = 0u, ///<计数状态
RtcRdWStatus = 1u, ///<读写状态
}en_rtc_status_t;
/**
******************************************************************************
** \brief rtc 中断请求标志
*****************************************************************************/
typedef enum en_rtc_status_irq
{
RtcAlmf = 0u, ///<闹钟中断请求
RtcPrdf = 1u, ///<周期中断请求
}en_rtc_status_irq_t;
/**
******************************************************************************
** \brief rtc时钟年、月、日、时、分、秒读写结构
*****************************************************************************/
typedef struct stc_rtc_time
{
uint8_t u8Second; ///<秒
uint8_t u8Minute; ///<分
uint8_t u8Hour; ///<时
uint8_t u8DayOfWeek; ///<周
uint8_t u8Day; ///<日
uint8_t u8Month; ///<月
uint8_t u8Year; ///<年
} stc_rtc_time_t;
/**
******************************************************************************
** \brief rtc功能描述
******************************************************************************/
typedef enum en_rtc_func
{
RtcCount = 0u, ///< RTC计数使能
RtcAlarmEn = 1u, ///< RTC闹钟使能
Rtc_ComenEn = 2u, ///<RTC补偿使能
Rtc1HzOutEn = 3u, ///<使能1hz输出
}en_rtc_func_t;
/**
******************************************************************************
** \brief rtc 闹钟及周期中断处理函数
*****************************************************************************/
typedef struct stc_rtc_irq_cb
{
func_ptr_t pfnAlarmIrqCb; ///<闹钟中断服务函数
func_ptr_t pfnTimerIrqCb; ///<周期中断服务函数
}stc_rtc_irq_cb_t, stc_rtc_intern_cb_t;
/**
******************************************************************************
** \brief rtc 总体配置结构体
*****************************************************************************/
typedef struct stc_rtc_config
{
en_rtc_clk_t enClkSel; ///<时钟源配置
en_rtc_ampm_t enAmpmSel; ///<时制配置
stc_rtc_cyc_sel_t* pstcCycSel; ///<周期配置
stc_rtc_time_t* pstcTimeDate; ///<时间日期初值配置
stc_rtc_irq_cb_t* pstcIrqCb; ///<中断服务函数
boolean_t bTouchNvic; ///<NVIC中断配置
} stc_rtc_config_t;
//rtc 计数时钟源选择
en_result_t Rtc_SelClk(en_rtc_clk_t enClk);
//rtc 计数周期设置
en_result_t Rtc_SetCyc(stc_rtc_cyc_sel_t* pstcCyc);
//rtc ampm模式设置
en_result_t Rtc_SetAmPm(en_rtc_ampm_t enMode);
//rtc时制模式获取
boolean_t Rtc_GetHourMode(void);
//rtc 闹钟相关配置
en_result_t Rtc_SetAlarmTime(stc_rtc_alarmset_t* pstcAlarmTime);
en_result_t Rtc_GetAlarmTime(stc_rtc_alarmset_t* pstcAlarmTime);
//1hz 输出模式及补偿值设置
en_result_t Rtc_Set1HzMode(boolean_t bMode);
en_result_t Rtc_SetCompCr(uint16_t u16Cr);
//周计算
uint8_t Rtc_CalWeek(uint8_t* pu8Date);
//判断是否闰年
uint8_t Rtc_CheckLeapYear(uint8_t u8year);
//12时制上午或下午读取
boolean_t Rtc_RDAmPm(void);
//rtc 读写时间计数器
en_result_t Rtc_WriteDateTime(stc_rtc_time_t* pstcTimeDate,boolean_t bUpdateTime,
boolean_t bUpdateDate);
en_result_t Rtc_ReadDateTime(stc_rtc_time_t* pstcTimeDate);
//格式转换函数
uint8_t Change_DateTimeFormat(uint8_t u8sr);
//时间格式检查函数
en_result_t Rtc_CheckDateTimeFormat(uint8_t* pu8TimeDate,uint8_t u8Mode);
//数据大小判断函数
en_result_t Check_BCD_Format(uint8_t u8data, uint8_t u8limit_min, uint8_t u8limit_max);
//获取某年某月最大天数
uint8_t Get_Month_Max_Day(uint8_t u8month, uint8_t u8year);
//rtc 读取当前状态(读写状态或计数状态),中断请求状态、中断清除状态
en_result_t Rtc_EnAlarmIrq(en_rtc_alarmirq_t enIrqEn);
boolean_t Rtc_RDStatus(void);
boolean_t Rtc_GetIrqStatus(en_rtc_status_irq_t enIrqSel);
en_result_t Rtc_ClrIrqStatus(en_rtc_status_irq_t enIrqSel);
//rtc功能使能禁止函数
en_result_t Rtc_EnableFunc(en_rtc_func_t enFunc);
en_result_t Rtc_DisableFunc(en_rtc_func_t enFunc);
//rtc初始化、禁止函数
en_result_t Rtc_Init(stc_rtc_config_t* pstcRtcConfig);
en_result_t Rtc_DeInit(void);
//@} // RtcGroup
#ifdef __cplusplus
#endif
#endif /* __RTC_H__ */
/******************************************************************************
* EOF (not truncated)
*****************************************************************************/
| {'repo_name': 'Tencent/TencentOS-tiny', 'stars': '4417', 'repo_language': 'C', 'file_name': 'startup_stm32f102x6.s', 'mime_type': 'text/x-asm', 'hash': 6962957783878136410, 'source_dataset': 'data'} |
import claripy
import angr
import nose.tools
class A:
n = 0
def do_vault_identity(v_factory):
v = v_factory()
v.uuid_dedup.add(A)
assert len(v.keys()) == 0
a = A()
b = A()
b.n = 1
c = A()
c.n = 2
aid = v.store(a)
nose.tools.assert_equal(len(v.keys()), 1, msg="Current keys: %s" % v.keys())
bid = v.store(b)
assert len(v.keys()) == 2
cid = v.store(c)
assert len(v.keys()) == 3
aa = v.load(aid)
bb = v.load(bid)
cc = v.load(cid)
assert aa is a
assert bb is b
assert cc is c
bb.n = 1337
del bb
del b
import gc
gc.collect()
bbb = v.load(bid)
assert bbb.n == 1
def do_vault_noidentity(v_factory):
v = v_factory()
assert len(v.keys()) == 0
a = A()
b = A()
b.n = 1
c = A()
c.n = 2
aid = v.store(a)
nose.tools.assert_equal(len(v.keys()), 1, msg="Current keys: %s" % v.keys())
bid = v.store(b)
assert len(v.keys()) == 2
cid = v.store(c)
assert len(v.keys()) == 3
aa = v.load(aid)
bb = v.load(bid)
cc = v.load(cid)
assert aa is not a
assert bb is not b
assert cc is not c
v.store(aa)
assert len(v.keys()) == 4
v.store(bb)
assert len(v.keys()) == 5
v.store(cc)
assert len(v.keys()) == 6
def do_ast_vault(v_factory):
v = v_factory()
x = claripy.BVS("x", 32)
y = claripy.BVS("y", 32)
z = x + y
v.store(x)
assert len(v.keys()) == 1
zid = v.store(z)
assert len(v.keys()) == 3
zz = v.load(zid)
assert z is zz
zs = v.dumps(z)
zzz = v.loads(zs)
assert zzz is z
def test_vault():
yield do_vault_noidentity, angr.vaults.VaultDir
yield do_vault_noidentity, angr.vaults.VaultShelf
yield do_vault_noidentity, angr.vaults.VaultDict
yield do_vault_noidentity, angr.vaults.VaultDirShelf
yield do_vault_identity, angr.vaults.VaultDir
yield do_vault_identity, angr.vaults.VaultShelf
yield do_vault_identity, angr.vaults.VaultDict
# VaultDirShelf does not guarantee identity equivalence due to the absence of caching
# yield do_vault_identity, angr.vaults.VaultDirShelf
def test_ast_vault():
yield do_ast_vault, angr.vaults.VaultDir
yield do_ast_vault, angr.vaults.VaultShelf
yield do_ast_vault, angr.vaults.VaultDict
# VaultDirShelf does not guarantee identity equivalence due to the absence of caching
# yield do_ast_vault, angr.vaults.VaultDirShelf
def test_project():
v = angr.vaults.VaultDir()
p = angr.Project("/bin/false")
ps = v.store(p)
pp = v.load(ps)
assert p is pp
assert sum(1 for k in v.keys() if k.startswith('Project')) == 1
pstring = v.dumps(p)
assert sum(1 for k in v.keys() if k.startswith('Project')) == 1
pp2 = v.loads(pstring)
assert sum(1 for k in v.keys() if k.startswith('Project')) == 1
assert p is pp
p._asdf = 'fdsa'
del pp2
del pp
del p
import gc
gc.collect()
p = v.load(ps)
#assert not hasattr(p, '_asdf')
assert sum(1 for k in v.keys() if k.startswith('Project')) == 1
if __name__ == '__main__':
for _a,_b in test_vault():
_a(_b)
for _a,_b in test_ast_vault():
_a(_b)
test_project()
| {'repo_name': 'angr/angr', 'stars': '4326', 'repo_language': 'Python', 'file_name': 'log.c', 'mime_type': 'text/x-c', 'hash': -827851503503118424, 'source_dataset': 'data'} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!--
Copyright (c) 2008-2012 The Sakai Foundation
Licensed under the Educational Community License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.osedu.org/licenses/ECL-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:wicket="http://wicket.apache.org/dtds.data/wicket-xhtml1.3-strict.dtd"
xml:lang="en"
lang="en">
<body>
<wicket:panel>
<div class="mainSection editable">
<div class="mainSectionHeading"><span wicket:id="heading">[Contact Information]</span></div>
<a href="#" wicket:id="editButton" class="edit-button">
<span wicket:id="editButtonLabel">edit</span>
<span class="offscreen">
<wicket:message key="accessibility.edit.contact" />
</span>
</a>
<div class="mainSectionContent">
<!-- message if no fields filled in -->
<span wicket:id="noFieldsMessage" class="profile_instruction">No fields</span>
<table class="profileContent">
<!-- email -->
<tr wicket:id="emailContainer">
<td class="label" wicket:id="emailLabel">[emailLabel]</td>
<td class="content" wicket:id="email">[email]</td>
</tr>
<!-- homepage -->
<tr wicket:id="homepageContainer">
<td class="label" wicket:id="homepageLabel">[homepageLabel]</td>
<td class="content"><a wicket:id="homepage" href="#" target="_blank">[homepage]</a></td>
</tr>
<!-- work phone -->
<tr wicket:id="workphoneContainer">
<td class="label" wicket:id="workphoneLabel">[workphoneLabel]</td>
<td class="content" wicket:id="workphone">[workphone]</td>
</tr>
<!-- home phone -->
<tr wicket:id="homephoneContainer">
<td class="label" wicket:id="homephoneLabel">[homephoneLabel]</td>
<td class="content" wicket:id="homephone">[workphone]</td>
</tr>
<!-- mobile phone -->
<tr wicket:id="mobilephoneContainer">
<td class="label" wicket:id="mobilephoneLabel">[mobilephoneLabel]</td>
<td class="content" wicket:id="mobilephone">[mobilephone]</td>
</tr>
<!-- facsimile -->
<tr wicket:id="facsimileContainer">
<td class="label" wicket:id="facsimileLabel">[facsimileLabel]</td>
<td class="content" wicket:id="facsimile">[facsimile]</td>
</tr>
</table>
</div>
</div>
<!-- panel specific Javascript -->
<script type="text/javascript">
//force hide on init
$(".edit-button").addClass("offscreen");
//show the edit button when hovering over an editable section
$(document).ready(function(){
$(".editable").hover(
function () {
$(this).children(".edit-button").removeClass("offscreen");
},
function () {
$(this).children(".edit-button").addClass("offscreen");
}
);
});
</script>
</wicket:panel>
</body>
</html>
| {'repo_name': 'sakaiproject/sakai', 'stars': '631', 'repo_language': 'Java', 'file_name': 'reviewAssessment.jsp', 'mime_type': 'text/html', 'hash': 7184566954378323654, 'source_dataset': 'data'} |
{
"type": "ChangeListeners",
"category": "core",
"generics": [
{
"name": "Target",
"extends": "object"
},
{
"name": "Property",
"extends": "keyof Target"
}
],
"extends": {
"interface": "Listeners",
"generics": [
{
"interface": "PropertyChangedEvent",
"generics": ["Target", "Target[Property]"]
}
]
},
"description": "A convenience type that extends the `Listeners` type to perform some additional checks when handling change events.",
"constructor": {
"access": "public",
"parameters": [
{
"name": "target",
"type": "Target"
},
{
"name": "property",
"type": "Property"
}
]
}
} | {'repo_name': 'eclipsesource/tabris-js', 'stars': '1166', 'repo_language': 'JavaScript', 'file_name': 'Listeners.json', 'mime_type': 'text/plain', 'hash': -6711229314158265037, 'source_dataset': 'data'} |
#!/usr/bin/env python
# Copyright 2012-2015 RethinkDB, all rights reserved.
from __future__ import print_function
import os, random, socket, sys, time
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir, 'common')))
import driver, scenario_common, vcoptparse, utils
op = vcoptparse.OptParser()
scenario_common.prepare_option_parser_mode_flags(op)
_, command_prefix, serve_options = scenario_common.parse_mode_flags(op.parse(sys.argv))
def garbage(n):
return "".join(chr(random.randint(0, 255)) for i in range(n))
utils.print_with_time("Starting first server")
with driver.Process(name='./db1', command_prefix=command_prefix, extra_options=serve_options) as server:
server.check()
utils.print_with_time("Generating garbage traffic")
for i in range(30):
print(i + 1, end=' ')
sys.stdout.flush()
s = socket.socket()
s.connect((server.host, server.cluster_port))
s.send(garbage(random.randint(0, 500)))
time.sleep(3)
s.close()
server.check()
utils.print_with_time("Cleaning up first server")
utils.print_with_time("Starting second server")
with driver.Process(name='./db2', command_prefix=command_prefix, extra_options=serve_options) as server:
server.check()
utils.print_with_time("Opening and holding a connection")
s = socket.socket()
s.connect((server.host, server.cluster_port))
utils.print_with_time("Stopping the server")
server.check_and_stop()
s.close()
utils.print_with_time("Cleaning up second server")
utils.print_with_time("Done.")
# TODO: Corrupt actual traffic between two processes instead of generating complete garbage. This might be tricky.
| {'repo_name': 'rethinkdb/rethinkdb_rebirth', 'stars': '1040', 'repo_language': 'C++', 'file_name': 'protobuf_1-fix-build-errors.patch', 'mime_type': 'text/x-diff', 'hash': -961172739351579058, 'source_dataset': 'data'} |
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"fmt"
"log"
"net/http"
"os"
"path/filepath"
"strings"
"google.golang.org/api/googleapi"
prediction "google.golang.org/api/prediction/v1.6"
)
func init() {
scopes := []string{
prediction.DevstorageFullControlScope,
prediction.DevstorageReadOnlyScope,
prediction.DevstorageReadWriteScope,
prediction.PredictionScope,
}
registerDemo("prediction", strings.Join(scopes, " "), predictionMain)
}
type predictionType struct {
api *prediction.Service
projectNumber string
bucketName string
trainingFileName string
modelName string
}
// This example demonstrates calling the Prediction API.
// Training data is uploaded to a pre-created Google Cloud Storage Bucket and
// then the Prediction API is called to train a model based on that data.
// After a few minutes, the model should be completely trained and ready
// for prediction. At that point, text is sent to the model and the Prediction
// API attempts to classify the data, and the results are printed out.
//
// To get started, follow the instructions found in the "Hello Prediction!"
// Getting Started Guide located here:
// https://developers.google.com/prediction/docs/hello_world
//
// Example usage:
// go-api-demo -clientid="my-clientid" -secret="my-secret" prediction
// my-project-number my-bucket-name my-training-filename my-model-name
//
// Example output:
// Predict result: language=Spanish
// English Score: 0.000000
// French Score: 0.000000
// Spanish Score: 1.000000
// analyze: output feature text=&{157 English}
// analyze: output feature text=&{149 French}
// analyze: output feature text=&{100 Spanish}
// feature text count=406
func predictionMain(client *http.Client, argv []string) {
if len(argv) != 4 {
fmt.Fprintln(os.Stderr,
"Usage: prediction project_number bucket training_data model_name")
return
}
api, err := prediction.New(client)
if err != nil {
log.Fatalf("unable to create prediction API client: %v", err)
}
t := &predictionType{
api: api,
projectNumber: argv[0],
bucketName: argv[1],
trainingFileName: argv[2],
modelName: argv[3],
}
t.trainModel()
t.predictModel()
}
func (t *predictionType) trainModel() {
// First, check to see if our trained model already exists.
res, err := t.api.Trainedmodels.Get(t.projectNumber, t.modelName).Do()
if err != nil {
if ae, ok := err.(*googleapi.Error); ok && ae.Code != http.StatusNotFound {
log.Fatalf("error getting trained model: %v", err)
}
log.Printf("Training model not found, creating new model.")
res, err = t.api.Trainedmodels.Insert(t.projectNumber, &prediction.Insert{
Id: t.modelName,
StorageDataLocation: filepath.Join(t.bucketName, t.trainingFileName),
}).Do()
if err != nil {
log.Fatalf("unable to create trained model: %v", err)
}
}
if res.TrainingStatus != "DONE" {
// Wait for the trained model to finish training.
fmt.Printf("Training model. Please wait and re-run program after a few minutes.")
os.Exit(0)
}
}
func (t *predictionType) predictModel() {
// Model has now been trained. Predict with it.
input := &prediction.Input{
Input: &prediction.InputInput{
CsvInstance: []interface{}{
"Hola, con quien hablo",
},
},
}
res, err := t.api.Trainedmodels.Predict(t.projectNumber, t.modelName, input).Do()
if err != nil {
log.Fatalf("unable to get trained prediction: %v", err)
}
fmt.Printf("Predict result: language=%v\n", res.OutputLabel)
for _, m := range res.OutputMulti {
fmt.Printf("%v Score: %v\n", m.Label, m.Score)
}
// Now analyze the model.
an, err := t.api.Trainedmodels.Analyze(t.projectNumber, t.modelName).Do()
if err != nil {
log.Fatalf("unable to analyze trained model: %v", err)
}
for _, f := range an.DataDescription.OutputFeature.Text {
fmt.Printf("analyze: output feature text=%v\n", f)
}
for _, f := range an.DataDescription.Features {
fmt.Printf("feature text count=%v\n", f.Text.Count)
}
}
| {'repo_name': 'GoogleCloudPlatform/cloud-build-local', 'stars': '204', 'repo_language': 'Go', 'file_name': 'volume_test.go', 'mime_type': 'text/plain', 'hash': 843012607330427522, 'source_dataset': 'data'} |
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Tencent is pleased to support the open source community by making behaviac available.
//
// Copyright (C) 2015-2017 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at http://opensource.org/licenses/BSD-3-Clause
//
// Unless required by applicable law or agreed to in writing, software distributed under the License is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and limitations under the License.
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#ifndef _CORE_RANGE_H_
#define _CORE_RANGE_H_
#include "behaviac/common/rttibase.h"
template <class T>
class TRange
{
public:
BEHAVIAC_DECLARE_MEMORY_OPERATORS(TRange)
T start;
T end;
TRange()
{
start = 0;
end = 0;
};
TRange(const TRange& r)
{
start = r.start;
end = r.end;
};
TRange(T s, T e)
{
start = s;
end = e;
};
};
typedef TRange<float> Range;
BEHAVIAC_OVERRIDE_TYPE_NAME(Range);
#endif // #ifndef _CORE_RANGE_H_
| {'repo_name': 'Tencent/behaviac', 'stars': '1836', 'repo_language': 'C#', 'file_name': 'AssemblyInfo.cs', 'mime_type': 'text/plain', 'hash': -7542856998307528343, 'source_dataset': 'data'} |
package resources
import (
"io/ioutil"
"path/filepath"
"strings"
"github.com/jaypipes/pcidb"
"github.com/pkg/errors"
"golang.org/x/sys/unix"
"github.com/lxc/lxd/shared/api"
)
var sysClassNet = "/sys/class/net"
var netProtocols = map[uint64]string{
1: "ethernet",
19: "ATM",
32: "infiniband",
}
func networkAddDeviceInfo(devicePath string, pciDB *pcidb.PCIDB, uname unix.Utsname, card *api.ResourcesNetworkCard) error {
// SRIOV
if sysfsExists(filepath.Join(devicePath, "sriov_numvfs")) {
sriov := api.ResourcesNetworkCardSRIOV{}
// Get maximum and current VF count
vfMaximum, err := readUint(filepath.Join(devicePath, "sriov_totalvfs"))
if err != nil {
return errors.Wrapf(err, "Failed to read \"%s\"", filepath.Join(devicePath, "sriov_totalvfs"))
}
vfCurrent, err := readUint(filepath.Join(devicePath, "sriov_numvfs"))
if err != nil {
return errors.Wrapf(err, "Failed to read \"%s\"", filepath.Join(devicePath, "sriov_numvfs"))
}
sriov.MaximumVFs = vfMaximum
sriov.CurrentVFs = vfCurrent
// Add the SRIOV data to the card
card.SRIOV = &sriov
}
// NUMA node
if sysfsExists(filepath.Join(devicePath, "numa_node")) {
numaNode, err := readInt(filepath.Join(devicePath, "numa_node"))
if err != nil {
return errors.Wrapf(err, "Failed to read \"%s\"", filepath.Join(devicePath, "numa_node"))
}
if numaNode > 0 {
card.NUMANode = uint64(numaNode)
}
}
// Vendor and product
deviceVendorPath := filepath.Join(devicePath, "vendor")
if sysfsExists(deviceVendorPath) {
id, err := ioutil.ReadFile(deviceVendorPath)
if err != nil {
return errors.Wrapf(err, "Failed to read \"%s\"", deviceVendorPath)
}
card.VendorID = strings.TrimPrefix(strings.TrimSpace(string(id)), "0x")
}
deviceDevicePath := filepath.Join(devicePath, "device")
if sysfsExists(deviceDevicePath) {
id, err := ioutil.ReadFile(deviceDevicePath)
if err != nil {
return errors.Wrapf(err, "Failed to read \"%s\"", deviceDevicePath)
}
card.ProductID = strings.TrimPrefix(strings.TrimSpace(string(id)), "0x")
}
// Fill vendor and product names
if pciDB != nil {
vendor, ok := pciDB.Vendors[card.VendorID]
if ok {
card.Vendor = vendor.Name
for _, product := range vendor.Products {
if product.ID == card.ProductID {
card.Product = product.Name
break
}
}
}
}
// Driver information
driverPath := filepath.Join(devicePath, "driver")
if sysfsExists(driverPath) {
linkTarget, err := filepath.EvalSymlinks(driverPath)
if err != nil {
return errors.Wrapf(err, "Failed to track down \"%s\"", driverPath)
}
// Set the driver name
card.Driver = filepath.Base(linkTarget)
// Try to get the version, fallback to kernel version
out, err := ioutil.ReadFile(filepath.Join(driverPath, "module", "version"))
if err == nil {
card.DriverVersion = strings.TrimSpace(string(out))
} else {
card.DriverVersion = strings.TrimRight(string(uname.Release[:]), "\x00")
}
}
// Port information
netPath := filepath.Join(devicePath, "net")
if sysfsExists(netPath) {
card.Ports = []api.ResourcesNetworkCardPort{}
entries, err := ioutil.ReadDir(netPath)
if err != nil {
return errors.Wrapf(err, "Failed to list \"%s\"", netPath)
}
// Iterate and record port data
for _, entry := range entries {
interfacePath := filepath.Join(netPath, entry.Name())
info := &api.ResourcesNetworkCardPort{
ID: entry.Name(),
}
// Add type
if sysfsExists(filepath.Join(interfacePath, "type")) {
devType, err := readUint(filepath.Join(interfacePath, "type"))
if err != nil {
return errors.Wrapf(err, "Failed to read \"%s\"", filepath.Join(interfacePath, "type"))
}
protocol, ok := netProtocols[devType]
if !ok {
info.Protocol = "unknown"
}
info.Protocol = protocol
}
// Add MAC address
if info.Address == "" && sysfsExists(filepath.Join(interfacePath, "address")) {
address, err := ioutil.ReadFile(filepath.Join(interfacePath, "address"))
if err != nil {
return errors.Wrapf(err, "Failed to read \"%s\"", filepath.Join(interfacePath, "address"))
}
info.Address = strings.TrimSpace(string(address))
}
// Add port number
if sysfsExists(filepath.Join(interfacePath, "dev_port")) {
port, err := readUint(filepath.Join(interfacePath, "dev_port"))
if err != nil {
return errors.Wrapf(err, "Failed to read \"%s\"", filepath.Join(interfacePath, "dev_port"))
}
info.Port = port
}
// Add infiniband specific information
if info.Protocol == "infiniband" && sysfsExists(filepath.Join(devicePath, "infiniband")) {
infiniband := &api.ResourcesNetworkCardPortInfiniband{}
madPath := filepath.Join(devicePath, "infiniband_mad")
if sysfsExists(madPath) {
ibPort := info.Port + 1
entries, err := ioutil.ReadDir(madPath)
if err != nil {
return errors.Wrapf(err, "Failed to list \"%s\"", madPath)
}
for _, entry := range entries {
entryName := entry.Name()
currentPort, err := readUint(filepath.Join(madPath, entryName, "port"))
if err != nil {
return errors.Wrapf(err, "Failed to read \"%s\"", filepath.Join(madPath, entryName, "port"))
}
if currentPort != ibPort {
continue
}
if !sysfsExists(filepath.Join(madPath, entryName, "dev")) {
continue
}
dev, err := ioutil.ReadFile(filepath.Join(madPath, entryName, "dev"))
if err != nil {
return errors.Wrapf(err, "Failed to read \"%s\"", filepath.Join(madPath, entryName, "dev"))
}
if strings.HasPrefix(entryName, "issm") {
infiniband.IsSMName = entryName
infiniband.IsSMDevice = strings.TrimSpace(string(dev))
}
if strings.HasPrefix(entryName, "umad") {
infiniband.MADName = entryName
infiniband.MADDevice = strings.TrimSpace(string(dev))
}
}
}
verbsPath := filepath.Join(devicePath, "infiniband_verbs")
if sysfsExists(verbsPath) {
entries, err := ioutil.ReadDir(verbsPath)
if err != nil {
return errors.Wrapf(err, "Failed to list \"%s\"", verbsPath)
}
if len(entries) == 1 {
verbName := entries[0].Name()
infiniband.VerbName = verbName
if !sysfsExists(filepath.Join(verbsPath, verbName, "dev")) {
continue
}
dev, err := ioutil.ReadFile(filepath.Join(verbsPath, verbName, "dev"))
if err != nil {
return errors.Wrapf(err, "Failed to read \"%s\"", filepath.Join(verbsPath, verbName, "dev"))
}
infiniband.VerbDevice = strings.TrimSpace(string(dev))
}
}
info.Infiniband = infiniband
}
// Attempt to add ethtool details (ignore failures)
if sysfsExists(filepath.Join(devicePath, "physfn")) {
// Getting physical port info for VFs makes no sense
card.Ports = append(card.Ports, *info)
continue
}
ethtoolAddPortInfo(info)
card.Ports = append(card.Ports, *info)
}
if len(card.Ports) > 0 {
ethtoolAddCardInfo(card.Ports[0].ID, card)
}
}
return nil
}
// GetNetwork returns a filled api.ResourcesNetwork struct ready for use by LXD
func GetNetwork() (*api.ResourcesNetwork, error) {
network := api.ResourcesNetwork{}
network.Cards = []api.ResourcesNetworkCard{}
// Get uname for driver version
uname := unix.Utsname{}
err := unix.Uname(&uname)
if err != nil {
return nil, errors.Wrap(err, "Failed to get uname")
}
// Load PCI database
pciDB, err := pcidb.New()
if err != nil {
pciDB = nil
}
// Temporary variables
pciKnown := []string{}
pciVFs := map[string][]api.ResourcesNetworkCard{}
// Detect all Networks available through kernel network interface
if sysfsExists(sysClassNet) {
entries, err := ioutil.ReadDir(sysClassNet)
if err != nil {
return nil, errors.Wrapf(err, "Failed to list \"%s\"", sysClassNet)
}
// Iterate and add to our list
for _, entry := range entries {
entryName := entry.Name()
entryPath := filepath.Join(sysClassNet, entryName)
devicePath := filepath.Join(entryPath, "device")
// Only keep physical network devices
if !sysfsExists(filepath.Join(entryPath, "device")) {
continue
}
// Setup the entry
card := api.ResourcesNetworkCard{}
// PCI address
linkTarget, err := filepath.EvalSymlinks(devicePath)
if err != nil {
return nil, errors.Wrapf(err, "Failed to track down \"%s\"", devicePath)
}
if strings.Contains(linkTarget, "/pci") && sysfsExists(filepath.Join(devicePath, "subsystem")) {
virtio := strings.HasPrefix(filepath.Base(linkTarget), "virtio")
if virtio {
linkTarget = filepath.Dir(linkTarget)
}
subsystem, err := filepath.EvalSymlinks(filepath.Join(devicePath, "subsystem"))
if err != nil {
return nil, errors.Wrapf(err, "Failed to track down \"%s\"", filepath.Join(devicePath, "subsystem"))
}
if filepath.Base(subsystem) == "pci" || virtio {
card.PCIAddress = filepath.Base(linkTarget)
// Skip devices we already know about
if stringInSlice(card.PCIAddress, pciKnown) {
continue
}
pciKnown = append(pciKnown, card.PCIAddress)
}
}
// Add device information for PFs
err = networkAddDeviceInfo(devicePath, pciDB, uname, &card)
if err != nil {
return nil, errors.Wrapf(err, "Failed to add device information for \"%s\"", devicePath)
}
// Add to list
if sysfsExists(filepath.Join(devicePath, "physfn")) {
// Virtual functions need to be added to the parent
linkTarget, err := filepath.EvalSymlinks(filepath.Join(devicePath, "physfn"))
if err != nil {
return nil, errors.Wrapf(err, "Failed to track down \"%s\"", filepath.Join(devicePath, "physfn"))
}
parentAddress := filepath.Base(linkTarget)
_, ok := pciVFs[parentAddress]
if !ok {
pciVFs[parentAddress] = []api.ResourcesNetworkCard{}
}
pciVFs[parentAddress] = append(pciVFs[parentAddress], card)
} else {
network.Cards = append(network.Cards, card)
}
}
}
// Detect remaining Networks on PCI bus
if sysfsExists(sysBusPci) {
entries, err := ioutil.ReadDir(sysBusPci)
if err != nil {
return nil, errors.Wrapf(err, "Failed to list \"%s\"", sysBusPci)
}
// Iterate and add to our list
for _, entry := range entries {
entryName := entry.Name()
devicePath := filepath.Join(sysBusPci, entryName)
// Skip devices we already know about
if stringInSlice(entryName, pciKnown) {
continue
}
// Only care about identifiable devices
if !sysfsExists(filepath.Join(devicePath, "class")) {
continue
}
class, err := ioutil.ReadFile(filepath.Join(devicePath, "class"))
if err != nil {
return nil, errors.Wrapf(err, "Failed to read \"%s\"", filepath.Join(devicePath, "class"))
}
// Only care about VGA devices
if !strings.HasPrefix(string(class), "0x02") {
continue
}
// Start building up data
card := api.ResourcesNetworkCard{}
card.PCIAddress = entryName
// Add device information
err = networkAddDeviceInfo(devicePath, pciDB, uname, &card)
if err != nil {
return nil, errors.Wrapf(err, "Failed to add device information for \"%s\"", devicePath)
}
// Add to list
if sysfsExists(filepath.Join(devicePath, "physfn")) {
// Virtual functions need to be added to the parent
linkTarget, err := filepath.EvalSymlinks(filepath.Join(devicePath, "physfn"))
if err != nil {
return nil, errors.Wrapf(err, "Failed to track down \"%s\"", filepath.Join(devicePath, "physfn"))
}
parentAddress := filepath.Base(linkTarget)
_, ok := pciVFs[parentAddress]
if !ok {
pciVFs[parentAddress] = []api.ResourcesNetworkCard{}
}
pciVFs[parentAddress] = append(pciVFs[parentAddress], card)
} else {
network.Cards = append(network.Cards, card)
}
}
}
// Add SRIOV devices and count devices
network.Total = 0
for _, card := range network.Cards {
if card.SRIOV != nil {
card.SRIOV.VFs = pciVFs[card.PCIAddress]
network.Total += uint64(len(card.SRIOV.VFs))
}
network.Total++
}
return &network, nil
}
| {'repo_name': 'lxc/lxd', 'stars': '2641', 'repo_language': 'Go', 'file_name': 'cgo.go', 'mime_type': 'text/plain', 'hash': -1542225413834917322, 'source_dataset': 'data'} |
/* Test lgamma.
Copyright (C) 1997-2020 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<https://www.gnu.org/licenses/>. */
#include "libm-test-driver.c"
static const struct test_f_f1_data lgamma_test_data[] =
{
TEST_f_f1 (lgamma, plus_infty, plus_infty, 1, ERRNO_UNCHANGED),
TEST_f_f1 (lgamma, 0, plus_infty, 1, DIVIDE_BY_ZERO_EXCEPTION|ERRNO_ERANGE),
TEST_f_f1 (lgamma, minus_zero, plus_infty, -1, DIVIDE_BY_ZERO_EXCEPTION|ERRNO_ERANGE),
TEST_f_f1 (lgamma, qnan_value, qnan_value, IGNORE, NO_INEXACT_EXCEPTION|ERRNO_UNCHANGED),
TEST_f_f1 (lgamma, -qnan_value, qnan_value, IGNORE, NO_INEXACT_EXCEPTION|ERRNO_UNCHANGED),
TEST_f_f1 (lgamma, snan_value, qnan_value, IGNORE, INVALID_EXCEPTION),
TEST_f_f1 (lgamma, -snan_value, qnan_value, IGNORE, INVALID_EXCEPTION),
/* lgamma (x) == +inf plus divide by zero exception for integer x <= 0. */
TEST_f_f1 (lgamma, -3, plus_infty, IGNORE, DIVIDE_BY_ZERO_EXCEPTION|ERRNO_ERANGE),
TEST_f_f1 (lgamma, minus_infty, plus_infty, IGNORE, ERRNO_UNCHANGED),
TEST_f_f1 (lgamma, -max_value, plus_infty, IGNORE, DIVIDE_BY_ZERO_EXCEPTION|ERRNO_ERANGE),
AUTO_TESTS_f_f1 (lgamma),
};
static void
lgamma_test (void)
{
ALL_RM_TEST (lgamma, 0, lgamma_test_data, RUN_TEST_LOOP_f_f1, END, signgam);
}
static void
gamma_test (void)
{
#if !TEST_FLOATN
/* gamma uses the same test data as lgamma. */
ALL_RM_TEST (gamma, 0, lgamma_test_data, RUN_TEST_LOOP_f_f1, END, signgam);
#endif
}
static void
do_test (void)
{
lgamma_test ();
gamma_test ();
}
/*
* Local Variables:
* mode:c
* End:
*/
| {'repo_name': 'bminor/glibc', 'stars': '400', 'repo_language': 'C', 'file_name': 'check_fds.c', 'mime_type': 'text/x-c', 'hash': -2837127853900665696, 'source_dataset': 'data'} |
FROM buildpack-deps:jessie-scm
# gcc for cgo
RUN apt-get update && apt-get install -y --no-install-recommends \
g++ \
gcc \
libc6-dev \
make \
&& rm -rf /var/lib/apt/lists/*
COPY gimme /usr/local/bin/
ENV GOPATH /go
ENV PATH $GOPATH/bin:$PATH
RUN mkdir -p "$GOPATH/src" "$GOPATH/bin" && chmod -R 777 "$GOPATH"
WORKDIR $GOPATH
| {'repo_name': 'travis-ci/gimme', 'stars': '602', 'repo_language': 'Shell', 'file_name': 'source-linux', 'mime_type': 'text/plain', 'hash': -4122431006651740218, 'source_dataset': 'data'} |
package api_server
import (
"fmt"
"github.com/go-openapi/strfmt"
params "github.com/kubeflow/pipelines/backend/api/go_http_client/pipeline_upload_client/pipeline_upload_service"
model "github.com/kubeflow/pipelines/backend/api/go_http_client/pipeline_upload_model"
)
const (
FileForDefaultTest = "./samples/parameters.yaml"
FileForClientErrorTest = "./samples/hello-world.yaml"
ClientErrorString = "Error with client"
InvalidFakeRequest = "Invalid fake request, don't know how to handle '%s' in the fake client."
)
func getDefaultUploadedPipeline() *model.APIPipeline {
return &model.APIPipeline{
ID: "500",
CreatedAt: strfmt.NewDateTime(),
Name: "PIPELINE_NAME",
Description: "PIPELINE_DESCRIPTION",
Parameters: []*model.APIParameter{&model.APIParameter{
Name: "PARAM_NAME",
Value: "PARAM_VALUE",
}},
}
}
type PipelineUploadClientFake struct{}
func NewPipelineUploadClientFake() *PipelineUploadClientFake {
return &PipelineUploadClientFake{}
}
func (c *PipelineUploadClientFake) UploadFile(filePath string,
parameters *params.UploadPipelineParams) (*model.APIPipeline, error) {
switch filePath {
case FileForClientErrorTest:
return nil, fmt.Errorf(ClientErrorString)
default:
return getDefaultUploadedPipeline(), nil
}
}
// TODO(jingzhang36): add UploadPipelineVersion fake to be used in integration test
// after go_http_client and go_client are auto-generated from UploadPipelineVersion in PipelineUploadServer
| {'repo_name': 'kubeflow/pipelines', 'stars': '1655', 'repo_language': 'Python', 'file_name': 'test_kubernetes.py', 'mime_type': 'text/x-python', 'hash': -12119174626859657, 'source_dataset': 'data'} |
<Project Sdk="Microsoft.NET.Sdk">
<Import Project="..\..\Product.props" />
<PropertyGroup>
<RootNamespace>Microsoft.ApplicationInsights.Web</RootNamespace>
<AssemblyName>Microsoft.AI.Web</AssemblyName>
<DocumentationFile>$(OutputPath)\$(AssemblyName).XML</DocumentationFile>
<TargetFramework>net45</TargetFramework>
<Prefer32Bit>false</Prefer32Bit>
<DefineConstants>$(DefineConstants);ALLOW_AGGRESSIVE_INLIGNING_ATTRIBUTE</DefineConstants>
</PropertyGroup>
<PropertyGroup>
<!--Nupkg properties-->
<PackageId>Microsoft.ApplicationInsights.Web</PackageId>
<Title>Application Insights for Web Applications</Title>
<Description>Application Insights for .NET web applications. Privacy statement: https://go.microsoft.com/fwlink/?LinkId=512156</Description>
<PackageTags>Azure Monitoring Analytics ApplicationInsights Telemetry AppInsights</PackageTags>
</PropertyGroup>
<ItemGroup Condition=" '$(Configuration)' == 'Release' And $(OS) == 'Windows_NT'">
<!--Analyzers-->
<PackageReference Include="Desktop.Analyzers" Version="1.1.0">
<PrivateAssets>All</PrivateAssets>
</PackageReference>
<PackageReference Include="StyleCop.Analyzers" Version="1.1.118">
<PrivateAssets>All</PrivateAssets>
</PackageReference>
<PackageReference Include="Microsoft.CodeAnalysis.FxCopAnalyzers" Version="2.9.2">
<PrivateAssets>All</PrivateAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<!--Build Infrastructure-->
<PackageReference Include="MicroBuild.Core" Version="0.3.0">
<PrivateAssets>All</PrivateAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<!--Common Dependencies-->
<PackageReference Include="Microsoft.ApplicationInsights" Version="2.12.0-beta1" />
<PackageReference Include="Microsoft.AspNet.TelemetryCorrelation" Version="1.0.7" />
<PackageReference Include="System.Diagnostics.DiagnosticSource" Version="4.6.0" />
</ItemGroup>
<ItemGroup>
<!--Nuget Transforms (install.xdt, uninstall.xdt, config.transform): "nupkg\content\<framework>\*.*-->
<Content Include="net45\*" />
<Content Include="Microsoft.ApplicationInsights.Web.targets" PackagePath="build" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\WindowsServer\WindowsServer\WindowsServer.csproj" />
</ItemGroup>
<ItemGroup>
<!--Framework References-->
<Reference Include="Microsoft.CSharp" />
</ItemGroup>
<Import Project="..\Web.Shared.Net\Web.Shared.Net.projitems" Label="Shared" />
<Import Project="..\..\Common\Common.projitems" Label="Shared" />
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), 'Common.targets'))\Common.targets" />
</Project>
| {'repo_name': 'microsoft/ApplicationInsights-dotnet-server', 'stars': '129', 'repo_language': 'C#', 'file_name': 'FxCopSetup.ps1', 'mime_type': 'text/plain', 'hash': 7325770350309287836, 'source_dataset': 'data'} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"/>
<meta name="apple-mobile-web-app-capable" content="yes" />
<title>Mobile App With Dialog Boxes</title>
<link href="../../themes/iphone/iphone-app.css" rel="stylesheet">
<style>
.lnk {
font-size: 17px;
color: cyan;
text-decoration: none;
}
</style>
<script type="text/javascript" src="../../../../dojo/dojo.js" data-dojo-config="parseOnLoad: false"></script>
<script language="JavaScript" type="text/javascript">
dojo.require("dojox.mobile.app");
dojo.requireIf(!dojo.isWebKit, "dojox.mobile.app.compat");
var appInfo = {
id: "org.dojo.simpleApp",
title: "Mobile App With Dialog Boxes",
initialScene: "main"
};
dojo.ready(dojox.mobile.app.init);
</script>
</head>
<body>
</body>
</html> | {'repo_name': 'dojo/dojox', 'stars': '150', 'repo_language': 'JavaScript', 'file_name': 'TitleGroup.css', 'mime_type': 'text/plain', 'hash': 5013879928396062010, 'source_dataset': 'data'} |
<?xml version="1.0"?>
<ZopeData>
<record id="1" aka="AAAAAAAAAAE=">
<pickle>
<global name="Category" module="erp5.portal_type"/>
</pickle>
<pickle>
<dictionary>
<item>
<key> <string>_Add_portal_content_Permission</string> </key>
<value>
<tuple>
<string>Assignor</string>
<string>Manager</string>
</tuple>
</value>
</item>
<item>
<key> <string>_Add_portal_folders_Permission</string> </key>
<value>
<tuple>
<string>Assignor</string>
<string>Manager</string>
</tuple>
</value>
</item>
<item>
<key> <string>_Copy_or_Move_Permission</string> </key>
<value>
<tuple>
<string>Assignor</string>
<string>Manager</string>
</tuple>
</value>
</item>
<item>
<key> <string>_Delete_objects_Permission</string> </key>
<value>
<tuple>
<string>Assignor</string>
<string>Manager</string>
</tuple>
</value>
</item>
<item>
<key> <string>_Modify_portal_content_Permission</string> </key>
<value>
<tuple>
<string>Assignee</string>
<string>Assignor</string>
<string>Manager</string>
<string>Owner</string>
</tuple>
</value>
</item>
<item>
<key> <string>_count</string> </key>
<value>
<persistent> <string encoding="base64">AAAAAAAAAAI=</string> </persistent>
</value>
</item>
<item>
<key> <string>_folder_handler</string> </key>
<value> <string>CMFBTreeFolderHandler</string> </value>
</item>
<item>
<key> <string>_mt_index</string> </key>
<value>
<persistent> <string encoding="base64">AAAAAAAAAAM=</string> </persistent>
</value>
</item>
<item>
<key> <string>_tree</string> </key>
<value>
<persistent> <string encoding="base64">AAAAAAAAAAQ=</string> </persistent>
</value>
</item>
<item>
<key> <string>codification</string> </key>
<value> <string>HQ-MAN</string> </value>
</item>
<item>
<key> <string>default_reference</string> </key>
<value> <string>MAN</string> </value>
</item>
<item>
<key> <string>id</string> </key>
<value> <string>manager</string> </value>
</item>
<item>
<key> <string>int_index</string> </key>
<value> <int>0</int> </value>
</item>
<item>
<key> <string>portal_type</string> </key>
<value> <string>Category</string> </value>
</item>
<item>
<key> <string>short_title</string> </key>
<value> <string>Manager</string> </value>
</item>
<item>
<key> <string>title</string> </key>
<value> <string>Headquarters Manager</string> </value>
</item>
</dictionary>
</pickle>
</record>
<record id="2" aka="AAAAAAAAAAI=">
<pickle>
<global name="Length" module="BTrees.Length"/>
</pickle>
<pickle> <int>0</int> </pickle>
</record>
<record id="3" aka="AAAAAAAAAAM=">
<pickle>
<global name="OOBTree" module="BTrees.OOBTree"/>
</pickle>
<pickle>
<none/>
</pickle>
</record>
<record id="4" aka="AAAAAAAAAAQ=">
<pickle>
<global name="OOBTree" module="BTrees.OOBTree"/>
</pickle>
<pickle>
<none/>
</pickle>
</record>
</ZopeData>
| {'repo_name': 'Nexedi/erp5', 'stars': '116', 'repo_language': 'JavaScript', 'file_name': 'base_category_list.xml', 'mime_type': 'text/plain', 'hash': -4083966057720395866, 'source_dataset': 'data'} |
/* -------------------------------------------------------------------------- *
* OpenMM *
* -------------------------------------------------------------------------- *
* This is part of the OpenMM molecular simulation toolkit originating from *
* Simbios, the NIH National Center for Physics-Based Simulation of *
* Biological Structures at Stanford, funded under the NIH Roadmap for *
* Medical Research, grant U54 GM072970. See https://simtk.org. *
* *
* Portions copyright (c) 2010-2017 Stanford University and the Authors. *
* Authors: Peter Eastman *
* Contributors: *
* *
* Permission is hereby granted, free of charge, to any person obtaining a *
* copy of this software and associated documentation files (the "Software"), *
* to deal in the Software without restriction, including without limitation *
* the rights to use, copy, modify, merge, publish, distribute, sublicense, *
* and/or sell copies of the Software, and to permit persons to whom the *
* Software is furnished to do so, subject to the following conditions: *
* *
* The above copyright notice and this permission notice shall be included in *
* all copies or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *
* THE AUTHORS, CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, *
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR *
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE *
* USE OR OTHER DEALINGS IN THE SOFTWARE. *
* -------------------------------------------------------------------------- */
#include "openmm/internal/AssertionUtilities.h"
#include "openmm/HarmonicBondForce.h"
#include "openmm/System.h"
#include "openmm/VirtualSite.h"
#include "openmm/serialization/XmlSerializer.h"
#include <iostream>
#include <sstream>
using namespace OpenMM;
using namespace std;
void compareSystems(System& system, System& system2) {
ASSERT_EQUAL(system.getNumParticles(), system2.getNumParticles());
for (int i = 0; i < system.getNumParticles(); i++)
ASSERT_EQUAL(system.getParticleMass(i), system2.getParticleMass(i));
ASSERT_EQUAL(system.getNumConstraints(), system2.getNumConstraints());
for (int i = 0; i < system.getNumConstraints(); i++) {
int p1, p2, p3, p4;
double d1, d2;
system.getConstraintParameters(i, p1, p2, d1);
system2.getConstraintParameters(i, p3, p4, d2);
ASSERT_EQUAL(p1, p3);
ASSERT_EQUAL(p2, p4);
ASSERT_EQUAL(d1, d2);
}
Vec3 a, b, c;
Vec3 a2, b2, c2;
system.getDefaultPeriodicBoxVectors(a, b, c);
system2.getDefaultPeriodicBoxVectors(a2, b2, c2);
ASSERT_EQUAL_VEC(a, a2, 0);
ASSERT_EQUAL_VEC(b, b2, 0);
ASSERT_EQUAL_VEC(c, c2, 0);
for (int i = 0; i < system.getNumParticles(); i++)
ASSERT_EQUAL(system.isVirtualSite(i), system2.isVirtualSite(i));
const TwoParticleAverageSite& site5 = dynamic_cast<const TwoParticleAverageSite&>(system2.getVirtualSite(5));
ASSERT_EQUAL(0, site5.getParticle(0));
ASSERT_EQUAL(1, site5.getParticle(1));
ASSERT_EQUAL(0.3, site5.getWeight(0));
ASSERT_EQUAL(0.7, site5.getWeight(1));
const ThreeParticleAverageSite& site6 = dynamic_cast<const ThreeParticleAverageSite&>(system2.getVirtualSite(6));
ASSERT_EQUAL(2, site6.getParticle(0));
ASSERT_EQUAL(4, site6.getParticle(1));
ASSERT_EQUAL(3, site6.getParticle(2));
ASSERT_EQUAL(0.5, site6.getWeight(0));
ASSERT_EQUAL(0.2, site6.getWeight(1));
ASSERT_EQUAL(0.3, site6.getWeight(2));
const OutOfPlaneSite& site7 = dynamic_cast<const OutOfPlaneSite&>(system2.getVirtualSite(7));
ASSERT_EQUAL(0, site7.getParticle(0));
ASSERT_EQUAL(3, site7.getParticle(1));
ASSERT_EQUAL(1, site7.getParticle(2));
ASSERT_EQUAL(0.1, site7.getWeight12());
ASSERT_EQUAL(0.2, site7.getWeight13());
ASSERT_EQUAL(0.5, site7.getWeightCross());
const LocalCoordinatesSite& site8 = dynamic_cast<const LocalCoordinatesSite&>(system2.getVirtualSite(8));
ASSERT_EQUAL(4, site8.getNumParticles());
ASSERT_EQUAL(4, site8.getParticle(0));
ASSERT_EQUAL(3, site8.getParticle(1));
ASSERT_EQUAL(2, site8.getParticle(2));
ASSERT_EQUAL(1, site8.getParticle(3));
ASSERT_EQUAL(Vec3(-0.5, 1.0, 1.5), site8.getLocalPosition());
vector<double> wo, wx, wy;
site8.getOriginWeights(wo);
site8.getXWeights(wx);
site8.getYWeights(wy);
vector<double> woExpected = {0.1, 0.2, 0.3, 0.4};
vector<double> wxExpected = {-1.0, 0.4, 0.4, 0.2};
vector<double> wyExpected = {0.3, 0.7, 0.0, -1.0};
ASSERT_EQUAL_CONTAINERS(woExpected, wo);
ASSERT_EQUAL_CONTAINERS(wxExpected, wx);
ASSERT_EQUAL_CONTAINERS(wyExpected, wy);
ASSERT_EQUAL(system.getNumForces(), system2.getNumForces());
for (int i = 0; i < system.getNumForces(); i++)
ASSERT(typeid(system.getForce(i)) == typeid(system2.getForce(i)))
}
void testSerialization() {
// Create a System.
System system;
for (int i = 0; i < 5; i++)
system.addParticle(0.1*i+1);
for (int i = 0; i < 5; i++)
system.addParticle(0.0);
system.addConstraint(0, 1, 3.0);
system.addConstraint(1, 2, 2.5);
system.addConstraint(4, 1, 1.001);
system.setDefaultPeriodicBoxVectors(Vec3(5, 0, 0), Vec3(0, 4, 0), Vec3(0, 0, 1.5));
system.setVirtualSite(5, new TwoParticleAverageSite(0, 1, 0.3, 0.7));
system.setVirtualSite(6, new ThreeParticleAverageSite(2, 4, 3, 0.5, 0.2, 0.3));
system.setVirtualSite(7, new OutOfPlaneSite(0, 3, 1, 0.1, 0.2, 0.5));
system.setVirtualSite(8, new LocalCoordinatesSite({4, 3, 2, 1}, {0.1, 0.2, 0.3, 0.4}, {-1.0, 0.4, 0.4, 0.2}, {0.3, 0.7, 0.0, -1.0}, Vec3(-0.5, 1.0, 1.5)));
system.addForce(new HarmonicBondForce());
// Serialize and then deserialize it, then make sure the systems are identical.
stringstream buffer;
XmlSerializer::serialize<System>(&system, "System", buffer);
System* copy = XmlSerializer::deserialize<System>(buffer);
compareSystems(system, *copy);
delete copy;
// Now do the same thing but by calling clone().
copy = XmlSerializer::clone(system);
compareSystems(system, *copy);
delete copy;
}
int main() {
try {
testSerialization();
}
catch(const exception& e) {
cout << "exception: " << e.what() << endl;
return 1;
}
cout << "Done" << endl;
return 0;
}
| {'repo_name': 'openmm/openmm', 'stars': '665', 'repo_language': 'C++', 'file_name': 'DrudeForceImpl.h', 'mime_type': 'text/x-c++', 'hash': 8701150720720288502, 'source_dataset': 'data'} |
/////////////////////////////////////////////////////////////////////////////
// Name: wx/list.h
// Purpose: wxList, wxStringList classes
// Author: Julian Smart
// Modified by: VZ at 16/11/98: WX_DECLARE_LIST() and typesafe lists added
// Created: 29/01/98
// Copyright: (c) 1998 Julian Smart
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
/*
All this is quite ugly but serves two purposes:
1. Be almost 100% compatible with old, untyped, wxList class
2. Ensure compile-time type checking for the linked lists
The idea is to have one base class (wxListBase) working with "void *" data,
but to hide these untyped functions - i.e. make them protected, so they
can only be used from derived classes which have inline member functions
working with right types. This achieves the 2nd goal. As for the first one,
we provide a special derivation of wxListBase called wxList which looks just
like the old class.
*/
#ifndef _WX_LIST_H_
#define _WX_LIST_H_
// -----------------------------------------------------------------------------
// headers
// -----------------------------------------------------------------------------
#include "wx/defs.h"
#include "wx/object.h"
#include "wx/string.h"
#include "wx/vector.h"
#if wxUSE_STD_CONTAINERS
#include "wx/beforestd.h"
#include <algorithm>
#include <iterator>
#include <list>
#include "wx/afterstd.h"
#endif
// ----------------------------------------------------------------------------
// types
// ----------------------------------------------------------------------------
class WXDLLIMPEXP_FWD_BASE wxObjectListNode;
typedef wxObjectListNode wxNode;
#if wxUSE_STD_CONTAINERS
#define wxLIST_COMPATIBILITY
#define WX_DECLARE_LIST_3(elT, dummy1, liT, dummy2, decl) \
WX_DECLARE_LIST_WITH_DECL(elT, liT, decl)
#define WX_DECLARE_LIST_PTR_3(elT, dummy1, liT, dummy2, decl) \
WX_DECLARE_LIST_3(elT, dummy1, liT, dummy2, decl)
#define WX_DECLARE_LIST_2(elT, liT, dummy, decl) \
WX_DECLARE_LIST_WITH_DECL(elT, liT, decl)
#define WX_DECLARE_LIST_PTR_2(elT, liT, dummy, decl) \
WX_DECLARE_LIST_2(elT, liT, dummy, decl) \
#define WX_DECLARE_LIST_WITH_DECL(elT, liT, decl) \
WX_DECLARE_LIST_XO(elT*, liT, decl)
#if !defined(__VISUALC__) || __VISUALC__ >= 1300 // == !VC6
template<class T>
class wxList_SortFunction
{
public:
wxList_SortFunction(wxSortCompareFunction f) : m_f(f) { }
bool operator()(const T& i1, const T& i2)
{ return m_f((T*)&i1, (T*)&i2) < 0; }
private:
wxSortCompareFunction m_f;
};
#define WX_LIST_SORTFUNCTION( elT, f ) wxList_SortFunction<elT>(f)
#define WX_LIST_VC6_WORKAROUND(elT, liT, decl)
#else // if defined( __VISUALC__ ) && __VISUALC__ < 1300 // == VC6
#define WX_LIST_SORTFUNCTION( elT, f ) std::greater<elT>( f )
#define WX_LIST_VC6_WORKAROUND(elT, liT, decl) \
decl liT; \
\
/* Workaround for broken VC6 STL incorrectly requires a std::greater<> */ \
/* to be passed into std::list::sort() */ \
template <> \
struct std::greater<elT> \
{ \
private: \
wxSortCompareFunction m_CompFunc; \
public: \
greater( wxSortCompareFunction compfunc = NULL ) \
: m_CompFunc( compfunc ) {} \
bool operator()(const elT X, const elT Y) const \
{ \
return m_CompFunc ? \
( m_CompFunc( wxListCastElementToVoidPtr(X), \
wxListCastElementToVoidPtr(Y) ) < 0 ) : \
( X > Y ); \
} \
};
// helper for std::greater<elT> above:
template<typename T>
inline const void *wxListCastElementToVoidPtr(const T* ptr) { return ptr; }
inline const void *wxListCastElementToVoidPtr(const wxString& str)
{ return (const char*)str; }
#endif // VC6/!VC6
/*
Note 1: the outer helper class _WX_LIST_HELPER_##liT below is a workaround
for mingw 3.2.3 compiler bug that prevents a static function of liT class
from being exported into dll. A minimal code snippet reproducing the bug:
struct WXDLLIMPEXP_CORE Foo
{
static void Bar();
struct SomeInnerClass
{
friend class Foo; // comment this out to make it link
};
~Foo()
{
Bar();
}
};
The program does not link under mingw_gcc 3.2.3 producing undefined
reference to Foo::Bar() function
Note 2: the EmptyList is needed to allow having a NULL pointer-like
invalid iterator. We used to use just an uninitialized iterator object
instead but this fails with some debug/checked versions of STL, notably the
glibc version activated with _GLIBCXX_DEBUG, so we need to have a separate
invalid iterator.
*/
// the real wxList-class declaration
#define WX_DECLARE_LIST_XO(elT, liT, decl) \
decl _WX_LIST_HELPER_##liT \
{ \
typedef elT _WX_LIST_ITEM_TYPE_##liT; \
typedef std::list<elT> BaseListType; \
public: \
static BaseListType EmptyList; \
static void DeleteFunction( _WX_LIST_ITEM_TYPE_##liT X ); \
}; \
\
WX_LIST_VC6_WORKAROUND(elT, liT, decl) \
class liT : public std::list<elT> \
{ \
private: \
typedef std::list<elT> BaseListType; \
\
bool m_destroy; \
\
public: \
class compatibility_iterator \
{ \
private: \
/* Workaround for broken VC6 nested class name resolution */ \
typedef std::list<elT>::iterator iterator; \
friend class liT; \
\
iterator m_iter; \
liT * m_list; \
\
public: \
compatibility_iterator() \
: m_iter(_WX_LIST_HELPER_##liT::EmptyList.end()), m_list( NULL ) {} \
compatibility_iterator( liT* li, iterator i ) \
: m_iter( i ), m_list( li ) {} \
compatibility_iterator( const liT* li, iterator i ) \
: m_iter( i ), m_list( const_cast< liT* >( li ) ) {} \
\
compatibility_iterator* operator->() { return this; } \
const compatibility_iterator* operator->() const { return this; } \
\
bool operator==(const compatibility_iterator& i) const \
{ \
wxASSERT_MSG( m_list && i.m_list, \
wxT("comparing invalid iterators is illegal") ); \
return (m_list == i.m_list) && (m_iter == i.m_iter); \
} \
bool operator!=(const compatibility_iterator& i) const \
{ return !( operator==( i ) ); } \
operator bool() const \
{ return m_list ? m_iter != m_list->end() : false; } \
bool operator !() const \
{ return !( operator bool() ); } \
\
elT GetData() const \
{ return *m_iter; } \
void SetData( elT e ) \
{ *m_iter = e; } \
\
compatibility_iterator GetNext() const \
{ \
iterator i = m_iter; \
return compatibility_iterator( m_list, ++i ); \
} \
compatibility_iterator GetPrevious() const \
{ \
if ( m_iter == m_list->begin() ) \
return compatibility_iterator(); \
\
iterator i = m_iter; \
return compatibility_iterator( m_list, --i ); \
} \
int IndexOf() const \
{ \
return *this ? (int)std::distance( m_list->begin(), m_iter ) \
: wxNOT_FOUND; \
} \
}; \
public: \
liT() : m_destroy( false ) {} \
\
compatibility_iterator Find( const elT e ) const \
{ \
liT* _this = const_cast< liT* >( this ); \
return compatibility_iterator( _this, \
std::find( _this->begin(), _this->end(), e ) ); \
} \
\
bool IsEmpty() const \
{ return empty(); } \
size_t GetCount() const \
{ return size(); } \
int Number() const \
{ return static_cast< int >( GetCount() ); } \
\
compatibility_iterator Item( size_t idx ) const \
{ \
iterator i = const_cast< liT* >(this)->begin(); \
std::advance( i, idx ); \
return compatibility_iterator( this, i ); \
} \
elT operator[](size_t idx) const \
{ \
return Item(idx).GetData(); \
} \
\
compatibility_iterator GetFirst() const \
{ \
return compatibility_iterator( this, \
const_cast< liT* >(this)->begin() ); \
} \
compatibility_iterator GetLast() const \
{ \
iterator i = const_cast< liT* >(this)->end(); \
return compatibility_iterator( this, !empty() ? --i : i ); \
} \
bool Member( elT e ) const \
{ return Find( e ); } \
compatibility_iterator Nth( int n ) const \
{ return Item( n ); } \
int IndexOf( elT e ) const \
{ return Find( e ).IndexOf(); } \
\
compatibility_iterator Append( elT e ) \
{ \
push_back( e ); \
return GetLast(); \
} \
compatibility_iterator Insert( elT e ) \
{ \
push_front( e ); \
return compatibility_iterator( this, begin() ); \
} \
compatibility_iterator Insert(const compatibility_iterator & i, elT e)\
{ \
return compatibility_iterator( this, insert( i.m_iter, e ) ); \
} \
compatibility_iterator Insert( size_t idx, elT e ) \
{ \
return compatibility_iterator( this, \
insert( Item( idx ).m_iter, e ) ); \
} \
\
void DeleteContents( bool destroy ) \
{ m_destroy = destroy; } \
bool GetDeleteContents() const \
{ return m_destroy; } \
void Erase( const compatibility_iterator& i ) \
{ \
if ( m_destroy ) \
_WX_LIST_HELPER_##liT::DeleteFunction( i->GetData() ); \
erase( i.m_iter ); \
} \
bool DeleteNode( const compatibility_iterator& i ) \
{ \
if( i ) \
{ \
Erase( i ); \
return true; \
} \
return false; \
} \
bool DeleteObject( elT e ) \
{ \
return DeleteNode( Find( e ) ); \
} \
void Clear() \
{ \
if ( m_destroy ) \
std::for_each( begin(), end(), \
_WX_LIST_HELPER_##liT::DeleteFunction ); \
clear(); \
} \
/* Workaround for broken VC6 std::list::sort() see above */ \
void Sort( wxSortCompareFunction compfunc ) \
{ sort( WX_LIST_SORTFUNCTION( elT, compfunc ) ); } \
~liT() { Clear(); } \
\
/* It needs access to our EmptyList */ \
friend class compatibility_iterator; \
}
#define WX_DECLARE_LIST(elementtype, listname) \
WX_DECLARE_LIST_WITH_DECL(elementtype, listname, class)
#define WX_DECLARE_LIST_PTR(elementtype, listname) \
WX_DECLARE_LIST(elementtype, listname)
#define WX_DECLARE_EXPORTED_LIST(elementtype, listname) \
WX_DECLARE_LIST_WITH_DECL(elementtype, listname, class WXDLLIMPEXP_CORE)
#define WX_DECLARE_EXPORTED_LIST_PTR(elementtype, listname) \
WX_DECLARE_EXPORTED_LIST(elementtype, listname)
#define WX_DECLARE_USER_EXPORTED_LIST(elementtype, listname, usergoo) \
WX_DECLARE_LIST_WITH_DECL(elementtype, listname, class usergoo)
#define WX_DECLARE_USER_EXPORTED_LIST_PTR(elementtype, listname, usergoo) \
WX_DECLARE_USER_EXPORTED_LIST(elementtype, listname, usergoo)
// this macro must be inserted in your program after
// #include "wx/listimpl.cpp"
#define WX_DEFINE_LIST(name) "don't forget to include listimpl.cpp!"
#define WX_DEFINE_EXPORTED_LIST(name) WX_DEFINE_LIST(name)
#define WX_DEFINE_USER_EXPORTED_LIST(name) WX_DEFINE_LIST(name)
#else // if !wxUSE_STD_CONTAINERS
// undef it to get rid of old, deprecated functions
#define wxLIST_COMPATIBILITY
// -----------------------------------------------------------------------------
// key stuff: a list may be optionally keyed on integer or string key
// -----------------------------------------------------------------------------
union wxListKeyValue
{
long integer;
wxString *string;
};
// a struct which may contain both types of keys
//
// implementation note: on one hand, this class allows to have only one function
// for any keyed operation instead of 2 almost equivalent. OTOH, it's needed to
// resolve ambiguity which we would otherwise have with wxStringList::Find() and
// wxList::Find(const char *).
class WXDLLIMPEXP_BASE wxListKey
{
public:
// implicit ctors
wxListKey() : m_keyType(wxKEY_NONE)
{ }
wxListKey(long i) : m_keyType(wxKEY_INTEGER)
{ m_key.integer = i; }
wxListKey(const wxString& s) : m_keyType(wxKEY_STRING)
{ m_key.string = new wxString(s); }
wxListKey(const char *s) : m_keyType(wxKEY_STRING)
{ m_key.string = new wxString(s); }
wxListKey(const wchar_t *s) : m_keyType(wxKEY_STRING)
{ m_key.string = new wxString(s); }
// accessors
wxKeyType GetKeyType() const { return m_keyType; }
const wxString GetString() const
{ wxASSERT( m_keyType == wxKEY_STRING ); return *m_key.string; }
long GetNumber() const
{ wxASSERT( m_keyType == wxKEY_INTEGER ); return m_key.integer; }
// comparison
// Note: implementation moved to list.cpp to prevent BC++ inline
// expansion warning.
bool operator==(wxListKeyValue value) const ;
// dtor
~wxListKey()
{
if ( m_keyType == wxKEY_STRING )
delete m_key.string;
}
private:
wxKeyType m_keyType;
wxListKeyValue m_key;
};
// -----------------------------------------------------------------------------
// wxNodeBase class is a (base for) node in a double linked list
// -----------------------------------------------------------------------------
extern WXDLLIMPEXP_DATA_BASE(wxListKey) wxDefaultListKey;
class WXDLLIMPEXP_FWD_BASE wxListBase;
class WXDLLIMPEXP_BASE wxNodeBase
{
friend class wxListBase;
public:
// ctor
wxNodeBase(wxListBase *list = NULL,
wxNodeBase *previous = NULL,
wxNodeBase *next = NULL,
void *data = NULL,
const wxListKey& key = wxDefaultListKey);
virtual ~wxNodeBase();
// FIXME no check is done that the list is really keyed on strings
wxString GetKeyString() const { return *m_key.string; }
long GetKeyInteger() const { return m_key.integer; }
// Necessary for some existing code
void SetKeyString(const wxString& s) { m_key.string = new wxString(s); }
void SetKeyInteger(long i) { m_key.integer = i; }
#ifdef wxLIST_COMPATIBILITY
// compatibility methods, use Get* instead.
wxDEPRECATED( wxNode *Next() const );
wxDEPRECATED( wxNode *Previous() const );
wxDEPRECATED( wxObject *Data() const );
#endif // wxLIST_COMPATIBILITY
protected:
// all these are going to be "overloaded" in the derived classes
wxNodeBase *GetNext() const { return m_next; }
wxNodeBase *GetPrevious() const { return m_previous; }
void *GetData() const { return m_data; }
void SetData(void *data) { m_data = data; }
// get 0-based index of this node within the list or wxNOT_FOUND
int IndexOf() const;
virtual void DeleteData() { }
public:
// for wxList::iterator
void** GetDataPtr() const { return &(const_cast<wxNodeBase*>(this)->m_data); }
private:
// optional key stuff
wxListKeyValue m_key;
void *m_data; // user data
wxNodeBase *m_next, // next and previous nodes in the list
*m_previous;
wxListBase *m_list; // list we belong to
wxDECLARE_NO_COPY_CLASS(wxNodeBase);
};
// -----------------------------------------------------------------------------
// a double-linked list class
// -----------------------------------------------------------------------------
class WXDLLIMPEXP_FWD_BASE wxList;
class WXDLLIMPEXP_BASE wxListBase
{
friend class wxNodeBase; // should be able to call DetachNode()
friend class wxHashTableBase; // should be able to call untyped Find()
public:
// default ctor & dtor
wxListBase(wxKeyType keyType = wxKEY_NONE)
{ Init(keyType); }
virtual ~wxListBase();
// accessors
// count of items in the list
size_t GetCount() const { return m_count; }
// return true if this list is empty
bool IsEmpty() const { return m_count == 0; }
// operations
// delete all nodes
void Clear();
// instruct it to destroy user data when deleting nodes
void DeleteContents(bool destroy) { m_destroy = destroy; }
// query if to delete
bool GetDeleteContents() const
{ return m_destroy; }
// get the keytype
wxKeyType GetKeyType() const
{ return m_keyType; }
// set the keytype (required by the serial code)
void SetKeyType(wxKeyType keyType)
{ wxASSERT( m_count==0 ); m_keyType = keyType; }
#ifdef wxLIST_COMPATIBILITY
// compatibility methods from old wxList
wxDEPRECATED( int Number() const ); // use GetCount instead.
wxDEPRECATED( wxNode *First() const ); // use GetFirst
wxDEPRECATED( wxNode *Last() const ); // use GetLast
wxDEPRECATED( wxNode *Nth(size_t n) const ); // use Item
// kludge for typesafe list migration in core classes.
wxDEPRECATED( operator wxList&() const );
#endif // wxLIST_COMPATIBILITY
protected:
// all methods here are "overloaded" in derived classes to provide compile
// time type checking
// create a node for the list of this type
virtual wxNodeBase *CreateNode(wxNodeBase *prev, wxNodeBase *next,
void *data,
const wxListKey& key = wxDefaultListKey) = 0;
// ctors
// from an array
wxListBase(size_t count, void *elements[]);
// from a sequence of objects
wxListBase(void *object, ... /* terminate with NULL */);
protected:
void Assign(const wxListBase& list)
{ Clear(); DoCopy(list); }
// get list head/tail
wxNodeBase *GetFirst() const { return m_nodeFirst; }
wxNodeBase *GetLast() const { return m_nodeLast; }
// by (0-based) index
wxNodeBase *Item(size_t index) const;
// get the list item's data
void *operator[](size_t n) const
{
wxNodeBase *node = Item(n);
return node ? node->GetData() : NULL;
}
// operations
// append to end of list
wxNodeBase *Prepend(void *object)
{ return (wxNodeBase *)wxListBase::Insert(object); }
// append to beginning of list
wxNodeBase *Append(void *object);
// insert a new item at the beginning of the list
wxNodeBase *Insert(void *object)
{ return Insert(static_cast<wxNodeBase *>(NULL), object); }
// insert a new item at the given position
wxNodeBase *Insert(size_t pos, void *object)
{ return pos == GetCount() ? Append(object)
: Insert(Item(pos), object); }
// insert before given node or at front of list if prev == NULL
wxNodeBase *Insert(wxNodeBase *prev, void *object);
// keyed append
wxNodeBase *Append(long key, void *object);
wxNodeBase *Append(const wxString& key, void *object);
// removes node from the list but doesn't delete it (returns pointer
// to the node or NULL if it wasn't found in the list)
wxNodeBase *DetachNode(wxNodeBase *node);
// delete element from list, returns false if node not found
bool DeleteNode(wxNodeBase *node);
// finds object pointer and deletes node (and object if DeleteContents
// is on), returns false if object not found
bool DeleteObject(void *object);
// search (all return NULL if item not found)
// by data
wxNodeBase *Find(const void *object) const;
// by key
wxNodeBase *Find(const wxListKey& key) const;
// get 0-based index of object or wxNOT_FOUND
int IndexOf( void *object ) const;
// this function allows the sorting of arbitrary lists by giving
// a function to compare two list elements. The list is sorted in place.
void Sort(const wxSortCompareFunction compfunc);
// functions for iterating over the list
void *FirstThat(wxListIterateFunction func);
void ForEach(wxListIterateFunction func);
void *LastThat(wxListIterateFunction func);
// for STL interface, "last" points to one after the last node
// of the controlled sequence (NULL for the end of the list)
void Reverse();
void DeleteNodes(wxNodeBase* first, wxNodeBase* last);
private:
// common part of all ctors
void Init(wxKeyType keyType = wxKEY_NONE);
// helpers
// common part of copy ctor and assignment operator
void DoCopy(const wxListBase& list);
// common part of all Append()s
wxNodeBase *AppendCommon(wxNodeBase *node);
// free node's data and node itself
void DoDeleteNode(wxNodeBase *node);
size_t m_count; // number of elements in the list
bool m_destroy; // destroy user data when deleting list items?
wxNodeBase *m_nodeFirst, // pointers to the head and tail of the list
*m_nodeLast;
wxKeyType m_keyType; // type of our keys (may be wxKEY_NONE)
};
// -----------------------------------------------------------------------------
// macros for definition of "template" list type
// -----------------------------------------------------------------------------
// and now some heavy magic...
// declare a list type named 'name' and containing elements of type 'T *'
// (as a by product of macro expansion you also get wx##name##Node
// wxNode-derived type)
//
// implementation details:
// 1. We define _WX_LIST_ITEM_TYPE_##name typedef to save in it the item type
// for the list of given type - this allows us to pass only the list name
// to WX_DEFINE_LIST() even if it needs both the name and the type
//
// 2. We redefine all non-type-safe wxList functions with type-safe versions
// which don't take any space (everything is inline), but bring compile
// time error checking.
//
// 3. The macro which is usually used (WX_DECLARE_LIST) is defined in terms of
// a more generic WX_DECLARE_LIST_2 macro which, in turn, uses the most
// generic WX_DECLARE_LIST_3 one. The last macro adds a sometimes
// interesting capability to store polymorphic objects in the list and is
// particularly useful with, for example, "wxWindow *" list where the
// wxWindowBase pointers are put into the list, but wxWindow pointers are
// retrieved from it.
//
// 4. final hack is that WX_DECLARE_LIST_3 is defined in terms of
// WX_DECLARE_LIST_4 to allow defining classes without operator->() as
// it results in compiler warnings when this operator doesn't make sense
// (i.e. stored elements are not pointers)
// common part of WX_DECLARE_LIST_3 and WX_DECLARE_LIST_PTR_3
#define WX_DECLARE_LIST_4(T, Tbase, name, nodetype, classexp, ptrop) \
typedef int (*wxSortFuncFor_##name)(const T **, const T **); \
\
classexp nodetype : public wxNodeBase \
{ \
public: \
nodetype(wxListBase *list = NULL, \
nodetype *previous = NULL, \
nodetype *next = NULL, \
T *data = NULL, \
const wxListKey& key = wxDefaultListKey) \
: wxNodeBase(list, previous, next, data, key) { } \
\
nodetype *GetNext() const \
{ return (nodetype *)wxNodeBase::GetNext(); } \
nodetype *GetPrevious() const \
{ return (nodetype *)wxNodeBase::GetPrevious(); } \
\
T *GetData() const \
{ return (T *)wxNodeBase::GetData(); } \
void SetData(T *data) \
{ wxNodeBase::SetData(data); } \
\
protected: \
virtual void DeleteData(); \
\
DECLARE_NO_COPY_CLASS(nodetype) \
}; \
\
classexp name : public wxListBase \
{ \
public: \
typedef nodetype Node; \
classexp compatibility_iterator \
{ \
public: \
compatibility_iterator(Node *ptr = NULL) : m_ptr(ptr) { } \
\
Node *operator->() const { return m_ptr; } \
operator Node *() const { return m_ptr; } \
\
private: \
Node *m_ptr; \
}; \
\
name(wxKeyType keyType = wxKEY_NONE) : wxListBase(keyType) \
{ } \
name(const name& list) : wxListBase(list.GetKeyType()) \
{ Assign(list); } \
name(size_t count, T *elements[]) \
: wxListBase(count, (void **)elements) { } \
\
name& operator=(const name& list) \
{ if (&list != this) Assign(list); return *this; } \
\
nodetype *GetFirst() const \
{ return (nodetype *)wxListBase::GetFirst(); } \
nodetype *GetLast() const \
{ return (nodetype *)wxListBase::GetLast(); } \
\
nodetype *Item(size_t index) const \
{ return (nodetype *)wxListBase::Item(index); } \
\
T *operator[](size_t index) const \
{ \
nodetype *node = Item(index); \
return node ? (T*)(node->GetData()) : NULL; \
} \
\
nodetype *Append(Tbase *object) \
{ return (nodetype *)wxListBase::Append(object); } \
nodetype *Insert(Tbase *object) \
{ return (nodetype *)Insert(static_cast<nodetype *>(NULL), \
object); } \
nodetype *Insert(size_t pos, Tbase *object) \
{ return (nodetype *)wxListBase::Insert(pos, object); } \
nodetype *Insert(nodetype *prev, Tbase *object) \
{ return (nodetype *)wxListBase::Insert(prev, object); } \
\
nodetype *Append(long key, void *object) \
{ return (nodetype *)wxListBase::Append(key, object); } \
nodetype *Append(const wxChar *key, void *object) \
{ return (nodetype *)wxListBase::Append(key, object); } \
\
nodetype *DetachNode(nodetype *node) \
{ return (nodetype *)wxListBase::DetachNode(node); } \
bool DeleteNode(nodetype *node) \
{ return wxListBase::DeleteNode(node); } \
bool DeleteObject(Tbase *object) \
{ return wxListBase::DeleteObject(object); } \
void Erase(nodetype *it) \
{ DeleteNode(it); } \
\
nodetype *Find(const Tbase *object) const \
{ return (nodetype *)wxListBase::Find(object); } \
\
virtual nodetype *Find(const wxListKey& key) const \
{ return (nodetype *)wxListBase::Find(key); } \
\
bool Member(const Tbase *object) const \
{ return Find(object) != NULL; } \
\
int IndexOf(Tbase *object) const \
{ return wxListBase::IndexOf(object); } \
\
void Sort(wxSortCompareFunction func) \
{ wxListBase::Sort(func); } \
void Sort(wxSortFuncFor_##name func) \
{ Sort((wxSortCompareFunction)func); } \
\
protected: \
virtual wxNodeBase *CreateNode(wxNodeBase *prev, wxNodeBase *next, \
void *data, \
const wxListKey& key = wxDefaultListKey) \
{ \
return new nodetype(this, \
(nodetype *)prev, (nodetype *)next, \
(T *)data, key); \
} \
/* STL interface */ \
public: \
typedef size_t size_type; \
typedef int difference_type; \
typedef T* value_type; \
typedef Tbase* base_value_type; \
typedef value_type& reference; \
typedef const value_type& const_reference; \
typedef base_value_type& base_reference; \
typedef const base_value_type& const_base_reference; \
\
classexp iterator \
{ \
typedef name list; \
public: \
typedef nodetype Node; \
typedef iterator itor; \
typedef T* value_type; \
typedef value_type* ptr_type; \
typedef value_type& reference; \
\
Node* m_node; \
Node* m_init; \
public: \
typedef reference reference_type; \
typedef ptr_type pointer_type; \
\
iterator(Node* node, Node* init) : m_node(node), m_init(init) {}\
iterator() : m_node(NULL), m_init(NULL) { } \
reference_type operator*() const \
{ return *(pointer_type)m_node->GetDataPtr(); } \
ptrop \
itor& operator++() \
{ \
wxASSERT_MSG( m_node, wxT("uninitialized iterator") ); \
m_node = m_node->GetNext(); \
return *this; \
} \
const itor operator++(int) \
{ \
itor tmp = *this; \
wxASSERT_MSG( m_node, wxT("uninitialized iterator") ); \
m_node = m_node->GetNext(); \
return tmp; \
} \
itor& operator--() \
{ \
m_node = m_node ? m_node->GetPrevious() : m_init; \
return *this; \
} \
const itor operator--(int) \
{ \
itor tmp = *this; \
m_node = m_node ? m_node->GetPrevious() : m_init; \
return tmp; \
} \
bool operator!=(const itor& it) const \
{ return it.m_node != m_node; } \
bool operator==(const itor& it) const \
{ return it.m_node == m_node; } \
}; \
classexp const_iterator \
{ \
typedef name list; \
public: \
typedef nodetype Node; \
typedef T* value_type; \
typedef const value_type& const_reference; \
typedef const_iterator itor; \
typedef value_type* ptr_type; \
\
Node* m_node; \
Node* m_init; \
public: \
typedef const_reference reference_type; \
typedef const ptr_type pointer_type; \
\
const_iterator(Node* node, Node* init) \
: m_node(node), m_init(init) { } \
const_iterator() : m_node(NULL), m_init(NULL) { } \
const_iterator(const iterator& it) \
: m_node(it.m_node), m_init(it.m_init) { } \
reference_type operator*() const \
{ return *(pointer_type)m_node->GetDataPtr(); } \
ptrop \
itor& operator++() \
{ \
wxASSERT_MSG( m_node, wxT("uninitialized iterator") ); \
m_node = m_node->GetNext(); \
return *this; \
} \
const itor operator++(int) \
{ \
itor tmp = *this; \
wxASSERT_MSG( m_node, wxT("uninitialized iterator") ); \
m_node = m_node->GetNext(); \
return tmp; \
} \
itor& operator--() \
{ \
m_node = m_node ? m_node->GetPrevious() : m_init; \
return *this; \
} \
const itor operator--(int) \
{ \
itor tmp = *this; \
m_node = m_node ? m_node->GetPrevious() : m_init; \
return tmp; \
} \
bool operator!=(const itor& it) const \
{ return it.m_node != m_node; } \
bool operator==(const itor& it) const \
{ return it.m_node == m_node; } \
}; \
classexp reverse_iterator \
{ \
typedef name list; \
public: \
typedef nodetype Node; \
typedef T* value_type; \
typedef reverse_iterator itor; \
typedef value_type* ptr_type; \
typedef value_type& reference; \
\
Node* m_node; \
Node* m_init; \
public: \
typedef reference reference_type; \
typedef ptr_type pointer_type; \
\
reverse_iterator(Node* node, Node* init) \
: m_node(node), m_init(init) { } \
reverse_iterator() : m_node(NULL), m_init(NULL) { } \
reference_type operator*() const \
{ return *(pointer_type)m_node->GetDataPtr(); } \
ptrop \
itor& operator++() \
{ m_node = m_node->GetPrevious(); return *this; } \
const itor operator++(int) \
{ itor tmp = *this; m_node = m_node->GetPrevious(); return tmp; }\
itor& operator--() \
{ m_node = m_node ? m_node->GetNext() : m_init; return *this; } \
const itor operator--(int) \
{ \
itor tmp = *this; \
m_node = m_node ? m_node->GetNext() : m_init; \
return tmp; \
} \
bool operator!=(const itor& it) const \
{ return it.m_node != m_node; } \
bool operator==(const itor& it) const \
{ return it.m_node == m_node; } \
}; \
classexp const_reverse_iterator \
{ \
typedef name list; \
public: \
typedef nodetype Node; \
typedef T* value_type; \
typedef const_reverse_iterator itor; \
typedef value_type* ptr_type; \
typedef const value_type& const_reference; \
\
Node* m_node; \
Node* m_init; \
public: \
typedef const_reference reference_type; \
typedef const ptr_type pointer_type; \
\
const_reverse_iterator(Node* node, Node* init) \
: m_node(node), m_init(init) { } \
const_reverse_iterator() : m_node(NULL), m_init(NULL) { } \
const_reverse_iterator(const reverse_iterator& it) \
: m_node(it.m_node), m_init(it.m_init) { } \
reference_type operator*() const \
{ return *(pointer_type)m_node->GetDataPtr(); } \
ptrop \
itor& operator++() \
{ m_node = m_node->GetPrevious(); return *this; } \
const itor operator++(int) \
{ itor tmp = *this; m_node = m_node->GetPrevious(); return tmp; }\
itor& operator--() \
{ m_node = m_node ? m_node->GetNext() : m_init; return *this;}\
const itor operator--(int) \
{ \
itor tmp = *this; \
m_node = m_node ? m_node->GetNext() : m_init; \
return tmp; \
} \
bool operator!=(const itor& it) const \
{ return it.m_node != m_node; } \
bool operator==(const itor& it) const \
{ return it.m_node == m_node; } \
}; \
\
wxEXPLICIT name(size_type n, const_reference v = value_type()) \
{ assign(n, v); } \
name(const const_iterator& first, const const_iterator& last) \
{ assign(first, last); } \
iterator begin() { return iterator(GetFirst(), GetLast()); } \
const_iterator begin() const \
{ return const_iterator(GetFirst(), GetLast()); } \
iterator end() { return iterator(NULL, GetLast()); } \
const_iterator end() const { return const_iterator(NULL, GetLast()); }\
reverse_iterator rbegin() \
{ return reverse_iterator(GetLast(), GetFirst()); } \
const_reverse_iterator rbegin() const \
{ return const_reverse_iterator(GetLast(), GetFirst()); } \
reverse_iterator rend() { return reverse_iterator(NULL, GetFirst()); }\
const_reverse_iterator rend() const \
{ return const_reverse_iterator(NULL, GetFirst()); } \
void resize(size_type n, value_type v = value_type()) \
{ \
while (n < size()) \
pop_back(); \
while (n > size()) \
push_back(v); \
} \
size_type size() const { return GetCount(); } \
size_type max_size() const { return INT_MAX; } \
bool empty() const { return IsEmpty(); } \
reference front() { return *begin(); } \
const_reference front() const { return *begin(); } \
reference back() { iterator tmp = end(); return *--tmp; } \
const_reference back() const { const_iterator tmp = end(); return *--tmp; }\
void push_front(const_reference v = value_type()) \
{ Insert(GetFirst(), (const_base_reference)v); } \
void pop_front() { DeleteNode(GetFirst()); } \
void push_back(const_reference v = value_type()) \
{ Append((const_base_reference)v); } \
void pop_back() { DeleteNode(GetLast()); } \
void assign(const_iterator first, const const_iterator& last) \
{ \
clear(); \
for(; first != last; ++first) \
Append((const_base_reference)*first); \
} \
void assign(size_type n, const_reference v = value_type()) \
{ \
clear(); \
for(size_type i = 0; i < n; ++i) \
Append((const_base_reference)v); \
} \
iterator insert(const iterator& it, const_reference v) \
{ \
if ( it == end() ) \
{ \
Append((const_base_reference)v); \
/* \
note that this is the new end(), the old one was \
invalidated by the Append() call, and this is why we \
can't use the same code as in the normal case below \
*/ \
iterator itins(end()); \
return --itins; \
} \
else \
{ \
Insert(it.m_node, (const_base_reference)v); \
iterator itins(it); \
return --itins; \
} \
} \
void insert(const iterator& it, size_type n, const_reference v) \
{ \
for(size_type i = 0; i < n; ++i) \
insert(it, v); \
} \
void insert(const iterator& it, \
const_iterator first, const const_iterator& last) \
{ \
for(; first != last; ++first) \
insert(it, *first); \
} \
iterator erase(const iterator& it) \
{ \
iterator next = iterator(it.m_node->GetNext(), GetLast()); \
DeleteNode(it.m_node); return next; \
} \
iterator erase(const iterator& first, const iterator& last) \
{ \
iterator next = last; \
if ( next != end() ) \
++next; \
DeleteNodes(first.m_node, last.m_node); \
return next; \
} \
void clear() { Clear(); } \
void splice(const iterator& it, name& l, const iterator& first, const iterator& last)\
{ insert(it, first, last); l.erase(first, last); } \
void splice(const iterator& it, name& l) \
{ splice(it, l, l.begin(), l.end() ); } \
void splice(const iterator& it, name& l, const iterator& first) \
{ \
if ( it != first ) \
{ \
insert(it, *first); \
l.erase(first); \
} \
} \
void remove(const_reference v) \
{ DeleteObject((const_base_reference)v); } \
void reverse() \
{ Reverse(); } \
/* void swap(name& l) \
{ \
{ size_t t = m_count; m_count = l.m_count; l.m_count = t; } \
{ bool t = m_destroy; m_destroy = l.m_destroy; l.m_destroy = t; }\
{ wxNodeBase* t = m_nodeFirst; m_nodeFirst = l.m_nodeFirst; l.m_nodeFirst = t; }\
{ wxNodeBase* t = m_nodeLast; m_nodeLast = l.m_nodeLast; l.m_nodeLast = t; }\
{ wxKeyType t = m_keyType; m_keyType = l.m_keyType; l.m_keyType = t; }\
} */ \
}
#define WX_LIST_PTROP \
pointer_type operator->() const \
{ return (pointer_type)m_node->GetDataPtr(); }
#define WX_LIST_PTROP_NONE
#define WX_DECLARE_LIST_3(T, Tbase, name, nodetype, classexp) \
WX_DECLARE_LIST_4(T, Tbase, name, nodetype, classexp, WX_LIST_PTROP_NONE)
#define WX_DECLARE_LIST_PTR_3(T, Tbase, name, nodetype, classexp) \
WX_DECLARE_LIST_4(T, Tbase, name, nodetype, classexp, WX_LIST_PTROP)
#define WX_DECLARE_LIST_2(elementtype, listname, nodename, classexp) \
WX_DECLARE_LIST_3(elementtype, elementtype, listname, nodename, classexp)
#define WX_DECLARE_LIST_PTR_2(elementtype, listname, nodename, classexp) \
WX_DECLARE_LIST_PTR_3(elementtype, elementtype, listname, nodename, classexp)
#define WX_DECLARE_LIST(elementtype, listname) \
typedef elementtype _WX_LIST_ITEM_TYPE_##listname; \
WX_DECLARE_LIST_2(elementtype, listname, wx##listname##Node, class)
#define WX_DECLARE_LIST_PTR(elementtype, listname) \
typedef elementtype _WX_LIST_ITEM_TYPE_##listname; \
WX_DECLARE_LIST_PTR_2(elementtype, listname, wx##listname##Node, class)
#define WX_DECLARE_LIST_WITH_DECL(elementtype, listname, decl) \
typedef elementtype _WX_LIST_ITEM_TYPE_##listname; \
WX_DECLARE_LIST_2(elementtype, listname, wx##listname##Node, decl)
#define WX_DECLARE_EXPORTED_LIST(elementtype, listname) \
WX_DECLARE_LIST_WITH_DECL(elementtype, listname, class WXDLLIMPEXP_CORE)
#define WX_DECLARE_EXPORTED_LIST_PTR(elementtype, listname) \
typedef elementtype _WX_LIST_ITEM_TYPE_##listname; \
WX_DECLARE_LIST_PTR_2(elementtype, listname, wx##listname##Node, class WXDLLIMPEXP_CORE)
#define WX_DECLARE_USER_EXPORTED_LIST(elementtype, listname, usergoo) \
typedef elementtype _WX_LIST_ITEM_TYPE_##listname; \
WX_DECLARE_LIST_2(elementtype, listname, wx##listname##Node, class usergoo)
#define WX_DECLARE_USER_EXPORTED_LIST_PTR(elementtype, listname, usergoo) \
typedef elementtype _WX_LIST_ITEM_TYPE_##listname; \
WX_DECLARE_LIST_PTR_2(elementtype, listname, wx##listname##Node, class usergoo)
// this macro must be inserted in your program after
// #include "wx/listimpl.cpp"
#define WX_DEFINE_LIST(name) "don't forget to include listimpl.cpp!"
#define WX_DEFINE_EXPORTED_LIST(name) WX_DEFINE_LIST(name)
#define WX_DEFINE_USER_EXPORTED_LIST(name) WX_DEFINE_LIST(name)
#endif // !wxUSE_STD_CONTAINERS
// ============================================================================
// now we can define classes 100% compatible with the old ones
// ============================================================================
// ----------------------------------------------------------------------------
// commonly used list classes
// ----------------------------------------------------------------------------
#if defined(wxLIST_COMPATIBILITY)
// inline compatibility functions
#if !wxUSE_STD_CONTAINERS
// ----------------------------------------------------------------------------
// wxNodeBase deprecated methods
// ----------------------------------------------------------------------------
inline wxNode *wxNodeBase::Next() const { return (wxNode *)GetNext(); }
inline wxNode *wxNodeBase::Previous() const { return (wxNode *)GetPrevious(); }
inline wxObject *wxNodeBase::Data() const { return (wxObject *)GetData(); }
// ----------------------------------------------------------------------------
// wxListBase deprecated methods
// ----------------------------------------------------------------------------
inline int wxListBase::Number() const { return (int)GetCount(); }
inline wxNode *wxListBase::First() const { return (wxNode *)GetFirst(); }
inline wxNode *wxListBase::Last() const { return (wxNode *)GetLast(); }
inline wxNode *wxListBase::Nth(size_t n) const { return (wxNode *)Item(n); }
inline wxListBase::operator wxList&() const { return *(wxList*)this; }
#endif
// define this to make a lot of noise about use of the old wxList classes.
//#define wxWARN_COMPAT_LIST_USE
// ----------------------------------------------------------------------------
// wxList compatibility class: in fact, it's a list of wxObjects
// ----------------------------------------------------------------------------
WX_DECLARE_LIST_2(wxObject, wxObjectList, wxObjectListNode,
class WXDLLIMPEXP_BASE);
class WXDLLIMPEXP_BASE wxList : public wxObjectList
{
public:
#if defined(wxWARN_COMPAT_LIST_USE) && !wxUSE_STD_CONTAINERS
wxList() { }
wxDEPRECATED( wxList(int key_type) );
#elif !wxUSE_STD_CONTAINERS
wxList(int key_type = wxKEY_NONE);
#endif
// this destructor is required for Darwin
~wxList() { }
#if !wxUSE_STD_CONTAINERS
wxList& operator=(const wxList& list)
{ if (&list != this) Assign(list); return *this; }
// compatibility methods
void Sort(wxSortCompareFunction compfunc) { wxListBase::Sort(compfunc); }
#endif // !wxUSE_STD_CONTAINERS
#ifndef __VISUALC6__
template<typename T>
wxVector<T> AsVector() const
{
wxVector<T> vector(size());
size_t i = 0;
for ( const_iterator it = begin(); it != end(); ++it )
{
vector[i++] = static_cast<T>(*it);
}
return vector;
}
#endif // !__VISUALC6__
};
#if !wxUSE_STD_CONTAINERS
// -----------------------------------------------------------------------------
// wxStringList class for compatibility with the old code
// -----------------------------------------------------------------------------
WX_DECLARE_LIST_2(wxChar, wxStringListBase, wxStringListNode, class WXDLLIMPEXP_BASE);
class WXDLLIMPEXP_BASE wxStringList : public wxStringListBase
{
public:
// ctors and such
// default
#ifdef wxWARN_COMPAT_LIST_USE
wxStringList();
wxDEPRECATED( wxStringList(const wxChar *first ...) ); // FIXME-UTF8
#else
wxStringList();
wxStringList(const wxChar *first ...); // FIXME-UTF8
#endif
// copying the string list: the strings are copied, too (extremely
// inefficient!)
wxStringList(const wxStringList& other) : wxStringListBase() { DeleteContents(true); DoCopy(other); }
wxStringList& operator=(const wxStringList& other)
{
if (&other != this)
{
Clear();
DoCopy(other);
}
return *this;
}
// operations
// makes a copy of the string
wxNode *Add(const wxChar *s);
// Append to beginning of list
wxNode *Prepend(const wxChar *s);
bool Delete(const wxChar *s);
wxChar **ListToArray(bool new_copies = false) const;
bool Member(const wxChar *s) const;
// alphabetic sort
void Sort();
private:
void DoCopy(const wxStringList&); // common part of copy ctor and operator=
};
#else // if wxUSE_STD_CONTAINERS
WX_DECLARE_LIST_XO(wxString, wxStringListBase, class WXDLLIMPEXP_BASE);
class WXDLLIMPEXP_BASE wxStringList : public wxStringListBase
{
public:
compatibility_iterator Append(wxChar* s)
{ wxString tmp = s; delete[] s; return wxStringListBase::Append(tmp); }
compatibility_iterator Insert(wxChar* s)
{ wxString tmp = s; delete[] s; return wxStringListBase::Insert(tmp); }
compatibility_iterator Insert(size_t pos, wxChar* s)
{
wxString tmp = s;
delete[] s;
return wxStringListBase::Insert(pos, tmp);
}
compatibility_iterator Add(const wxChar* s)
{ push_back(s); return GetLast(); }
compatibility_iterator Prepend(const wxChar* s)
{ push_front(s); return GetFirst(); }
};
#endif // wxUSE_STD_CONTAINERS
#endif // wxLIST_COMPATIBILITY
// delete all list elements
//
// NB: the class declaration of the list elements must be visible from the
// place where you use this macro, otherwise the proper destructor may not
// be called (a decent compiler should give a warning about it, but don't
// count on it)!
#define WX_CLEAR_LIST(type, list) \
{ \
type::iterator it, en; \
for( it = (list).begin(), en = (list).end(); it != en; ++it ) \
delete *it; \
(list).clear(); \
}
// append all element of one list to another one
#define WX_APPEND_LIST(list, other) \
{ \
wxList::compatibility_iterator node = other->GetFirst(); \
while ( node ) \
{ \
(list)->push_back(node->GetData()); \
node = node->GetNext(); \
} \
}
#endif // _WX_LISTH__
| {'repo_name': 'fossephate/JoyCon-Driver', 'stars': '702', 'repo_language': 'C++', 'file_name': 'toolbar.h', 'mime_type': 'text/x-c++', 'hash': -933702449011750297, 'source_dataset': 'data'} |
'use strict';
var moment = require('moment-timezone');
CronDate.prototype.addYear = function() {
this._date.add(1, 'year');
};
CronDate.prototype.addMonth = function() {
this._date.add(1, 'month').startOf('month');
};
CronDate.prototype.addDay = function() {
this._date.add(1, 'day').startOf('day');
};
CronDate.prototype.addHour = function() {
var prev = this.getTime();
this._date.add(1, 'hour').startOf('hour');
if (this.getTime() <= prev) {
this._date.add(1, 'hour');
}
};
CronDate.prototype.addMinute = function() {
var prev = this.getTime();
this._date.add(1, 'minute').startOf('minute');
if (this.getTime() < prev) {
this._date.add(1, 'hour');
}
};
CronDate.prototype.addSecond = function() {
var prev = this.getTime();
this._date.add(1, 'second').startOf('second');
if (this.getTime() < prev) {
this._date.add(1, 'hour');
}
};
CronDate.prototype.subtractYear = function() {
this._date.subtract(1, 'year');
};
CronDate.prototype.subtractMonth = function() {
this._date.subtract(1, 'month').endOf('month');
};
CronDate.prototype.subtractDay = function() {
this._date.subtract(1, 'day').endOf('day');
};
CronDate.prototype.subtractHour = function() {
var prev = this.getTime();
this._date.subtract(1, 'hour').endOf('hour');
if (this.getTime() >= prev) {
this._date.subtract(1, 'hour');
}
};
CronDate.prototype.subtractMinute = function() {
var prev = this.getTime();
this._date.subtract(1, 'minute').endOf('minute');
if (this.getTime() > prev) {
this._date.subtract(1, 'hour');
}
};
CronDate.prototype.subtractSecond = function() {
var prev = this.getTime();
this._date.subtract(1, 'second').startOf('second');
if (this.getTime() > prev) {
this._date.subtract(1, 'hour');
}
};
CronDate.prototype.getDate = function() {
return this._date.date();
};
CronDate.prototype.getFullYear = function() {
return this._date.year();
};
CronDate.prototype.getDay = function() {
return this._date.day();
};
CronDate.prototype.getMonth = function() {
return this._date.month();
};
CronDate.prototype.getHours = function() {
return this._date.hours();
};
CronDate.prototype.getMinutes = function() {
return this._date.minute();
};
CronDate.prototype.getSeconds = function() {
return this._date.second();
};
CronDate.prototype.getMilliseconds = function() {
return this._date.millisecond();
};
CronDate.prototype.getTime = function() {
return this._date.valueOf();
};
CronDate.prototype.getUTCDate = function() {
return this._getUTC().date();
};
CronDate.prototype.getUTCFullYear = function() {
return this._getUTC().year();
};
CronDate.prototype.getUTCDay = function() {
return this._getUTC().day();
};
CronDate.prototype.getUTCMonth = function() {
return this._getUTC().month();
};
CronDate.prototype.getUTCHours = function() {
return this._getUTC().hours();
};
CronDate.prototype.getUTCMinutes = function() {
return this._getUTC().minute();
};
CronDate.prototype.getUTCSeconds = function() {
return this._getUTC().second();
};
CronDate.prototype.toISOString = function() {
return this._date.toISOString();
};
CronDate.prototype.toJSON = function() {
return this._date.toJSON();
};
CronDate.prototype.setDate = function(d) {
return this._date.date(d);
};
CronDate.prototype.setFullYear = function(y) {
return this._date.year(y);
};
CronDate.prototype.setDay = function(d) {
return this._date.day(d);
};
CronDate.prototype.setMonth = function(m) {
return this._date.month(m);
};
CronDate.prototype.setHours = function(h) {
return this._date.hour(h);
};
CronDate.prototype.setMinutes = function(m) {
return this._date.minute(m);
};
CronDate.prototype.setSeconds = function(s) {
return this._date.second(s);
};
CronDate.prototype.setMilliseconds = function(s) {
return this._date.millisecond(s);
};
CronDate.prototype.getTime = function() {
return this._date.valueOf();
};
CronDate.prototype._getUTC = function() {
return moment.utc(this._date);
};
CronDate.prototype.toString = function() {
return this._date.toString();
};
CronDate.prototype.toDate = function() {
return this._date.toDate();
};
function CronDate (timestamp, tz) {
if (timestamp instanceof CronDate) {
timestamp = timestamp._date;
}
if (!tz) {
this._date = moment(timestamp);
} else {
this._date = moment.tz(timestamp, tz);
}
}
module.exports = CronDate;
| {'repo_name': 'ILIAS-eLearning/ILIAS', 'stars': '206', 'repo_language': 'PHP', 'file_name': 'cron.php', 'mime_type': 'text/x-php', 'hash': 903816217341248443, 'source_dataset': 'data'} |
/*
* Copyright (C) 2015-2017 Netronome Systems, Inc.
*
* This software is dual licensed under the GNU General License Version 2,
* June 1991 as shown in the file COPYING in the top-level directory of this
* source tree or the BSD 2-Clause License provided below. You have the
* option to license this software under the complete terms of either license.
*
* The BSD 2-Clause License:
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* 1. Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* 2. Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/*
* nfp_arm.h
* Definitions for ARM-based registers and memory spaces
*/
#ifndef NFP_ARM_H
#define NFP_ARM_H
#define NFP_ARM_QUEUE(_q) (0x100000 + (0x800 * ((_q) & 0xff)))
#define NFP_ARM_IM 0x200000
#define NFP_ARM_EM 0x300000
#define NFP_ARM_GCSR 0x400000
#define NFP_ARM_MPCORE 0x800000
#define NFP_ARM_PL310 0xa00000
/* Register Type: BulkBARConfig */
#define NFP_ARM_GCSR_BULK_BAR(_bar) (0x0 + (0x4 * ((_bar) & 0x7)))
#define NFP_ARM_GCSR_BULK_BAR_TYPE (0x1 << 31)
#define NFP_ARM_GCSR_BULK_BAR_TYPE_BULK (0x0)
#define NFP_ARM_GCSR_BULK_BAR_TYPE_EXPA (0x80000000)
#define NFP_ARM_GCSR_BULK_BAR_TGT(_x) (((_x) & 0xf) << 27)
#define NFP_ARM_GCSR_BULK_BAR_TGT_of(_x) (((_x) >> 27) & 0xf)
#define NFP_ARM_GCSR_BULK_BAR_TOK(_x) (((_x) & 0x3) << 25)
#define NFP_ARM_GCSR_BULK_BAR_TOK_of(_x) (((_x) >> 25) & 0x3)
#define NFP_ARM_GCSR_BULK_BAR_LEN (0x1 << 24)
#define NFP_ARM_GCSR_BULK_BAR_LEN_32BIT (0x0)
#define NFP_ARM_GCSR_BULK_BAR_LEN_64BIT (0x1000000)
#define NFP_ARM_GCSR_BULK_BAR_ADDR(_x) ((_x) & 0x7ff)
#define NFP_ARM_GCSR_BULK_BAR_ADDR_of(_x) ((_x) & 0x7ff)
/* Register Type: ExpansionBARConfig */
#define NFP_ARM_GCSR_EXPA_BAR(_bar) (0x20 + (0x4 * ((_bar) & 0xf)))
#define NFP_ARM_GCSR_EXPA_BAR_TYPE (0x1 << 31)
#define NFP_ARM_GCSR_EXPA_BAR_TYPE_EXPA (0x0)
#define NFP_ARM_GCSR_EXPA_BAR_TYPE_EXPL (0x80000000)
#define NFP_ARM_GCSR_EXPA_BAR_TGT(_x) (((_x) & 0xf) << 27)
#define NFP_ARM_GCSR_EXPA_BAR_TGT_of(_x) (((_x) >> 27) & 0xf)
#define NFP_ARM_GCSR_EXPA_BAR_TOK(_x) (((_x) & 0x3) << 25)
#define NFP_ARM_GCSR_EXPA_BAR_TOK_of(_x) (((_x) >> 25) & 0x3)
#define NFP_ARM_GCSR_EXPA_BAR_LEN (0x1 << 24)
#define NFP_ARM_GCSR_EXPA_BAR_LEN_32BIT (0x0)
#define NFP_ARM_GCSR_EXPA_BAR_LEN_64BIT (0x1000000)
#define NFP_ARM_GCSR_EXPA_BAR_ACT(_x) (((_x) & 0x1f) << 19)
#define NFP_ARM_GCSR_EXPA_BAR_ACT_of(_x) (((_x) >> 19) & 0x1f)
#define NFP_ARM_GCSR_EXPA_BAR_ACT_DERIVED (0)
#define NFP_ARM_GCSR_EXPA_BAR_ADDR(_x) ((_x) & 0x7fff)
#define NFP_ARM_GCSR_EXPA_BAR_ADDR_of(_x) ((_x) & 0x7fff)
/* Register Type: ExplicitBARConfig0_Reg */
#define NFP_ARM_GCSR_EXPL0_BAR(_bar) (0x60 + (0x4 * ((_bar) & 0x7)))
#define NFP_ARM_GCSR_EXPL0_BAR_ADDR(_x) ((_x) & 0x3ffff)
#define NFP_ARM_GCSR_EXPL0_BAR_ADDR_of(_x) ((_x) & 0x3ffff)
/* Register Type: ExplicitBARConfig1_Reg */
#define NFP_ARM_GCSR_EXPL1_BAR(_bar) (0x80 + (0x4 * ((_bar) & 0x7)))
#define NFP_ARM_GCSR_EXPL1_BAR_POSTED (0x1 << 31)
#define NFP_ARM_GCSR_EXPL1_BAR_SIGNAL_REF(_x) (((_x) & 0x7f) << 24)
#define NFP_ARM_GCSR_EXPL1_BAR_SIGNAL_REF_of(_x) (((_x) >> 24) & 0x7f)
#define NFP_ARM_GCSR_EXPL1_BAR_DATA_MASTER(_x) (((_x) & 0xff) << 16)
#define NFP_ARM_GCSR_EXPL1_BAR_DATA_MASTER_of(_x) (((_x) >> 16) & 0xff)
#define NFP_ARM_GCSR_EXPL1_BAR_DATA_REF(_x) ((_x) & 0x3fff)
#define NFP_ARM_GCSR_EXPL1_BAR_DATA_REF_of(_x) ((_x) & 0x3fff)
/* Register Type: ExplicitBARConfig2_Reg */
#define NFP_ARM_GCSR_EXPL2_BAR(_bar) (0xa0 + (0x4 * ((_bar) & 0x7)))
#define NFP_ARM_GCSR_EXPL2_BAR_TGT(_x) (((_x) & 0xf) << 28)
#define NFP_ARM_GCSR_EXPL2_BAR_TGT_of(_x) (((_x) >> 28) & 0xf)
#define NFP_ARM_GCSR_EXPL2_BAR_ACT(_x) (((_x) & 0x1f) << 23)
#define NFP_ARM_GCSR_EXPL2_BAR_ACT_of(_x) (((_x) >> 23) & 0x1f)
#define NFP_ARM_GCSR_EXPL2_BAR_LEN(_x) (((_x) & 0x1f) << 18)
#define NFP_ARM_GCSR_EXPL2_BAR_LEN_of(_x) (((_x) >> 18) & 0x1f)
#define NFP_ARM_GCSR_EXPL2_BAR_BYTE_MASK(_x) (((_x) & 0xff) << 10)
#define NFP_ARM_GCSR_EXPL2_BAR_BYTE_MASK_of(_x) (((_x) >> 10) & 0xff)
#define NFP_ARM_GCSR_EXPL2_BAR_TOK(_x) (((_x) & 0x3) << 8)
#define NFP_ARM_GCSR_EXPL2_BAR_TOK_of(_x) (((_x) >> 8) & 0x3)
#define NFP_ARM_GCSR_EXPL2_BAR_SIGNAL_MASTER(_x) ((_x) & 0xff)
#define NFP_ARM_GCSR_EXPL2_BAR_SIGNAL_MASTER_of(_x) ((_x) & 0xff)
/* Register Type: PostedCommandSignal */
#define NFP_ARM_GCSR_EXPL_POST(_bar) (0xc0 + (0x4 * ((_bar) & 0x7)))
#define NFP_ARM_GCSR_EXPL_POST_SIG_B(_x) (((_x) & 0x7f) << 25)
#define NFP_ARM_GCSR_EXPL_POST_SIG_B_of(_x) (((_x) >> 25) & 0x7f)
#define NFP_ARM_GCSR_EXPL_POST_SIG_B_BUS (0x1 << 24)
#define NFP_ARM_GCSR_EXPL_POST_SIG_B_BUS_PULL (0x0)
#define NFP_ARM_GCSR_EXPL_POST_SIG_B_BUS_PUSH (0x1000000)
#define NFP_ARM_GCSR_EXPL_POST_SIG_A(_x) (((_x) & 0x7f) << 17)
#define NFP_ARM_GCSR_EXPL_POST_SIG_A_of(_x) (((_x) >> 17) & 0x7f)
#define NFP_ARM_GCSR_EXPL_POST_SIG_A_BUS (0x1 << 16)
#define NFP_ARM_GCSR_EXPL_POST_SIG_A_BUS_PULL (0x0)
#define NFP_ARM_GCSR_EXPL_POST_SIG_A_BUS_PUSH (0x10000)
#define NFP_ARM_GCSR_EXPL_POST_SIG_B_RCVD (0x1 << 7)
#define NFP_ARM_GCSR_EXPL_POST_SIG_B_VALID (0x1 << 6)
#define NFP_ARM_GCSR_EXPL_POST_SIG_A_RCVD (0x1 << 5)
#define NFP_ARM_GCSR_EXPL_POST_SIG_A_VALID (0x1 << 4)
#define NFP_ARM_GCSR_EXPL_POST_CMD_COMPLETE (0x1)
/* Register Type: MPCoreBaseAddress */
#define NFP_ARM_GCSR_MPCORE_BASE 0x00e0
#define NFP_ARM_GCSR_MPCORE_BASE_ADDR(_x) (((_x) & 0x7ffff) << 13)
#define NFP_ARM_GCSR_MPCORE_BASE_ADDR_of(_x) (((_x) >> 13) & 0x7ffff)
/* Register Type: PL310BaseAddress */
#define NFP_ARM_GCSR_PL310_BASE 0x00e4
#define NFP_ARM_GCSR_PL310_BASE_ADDR(_x) (((_x) & 0xfffff) << 12)
#define NFP_ARM_GCSR_PL310_BASE_ADDR_of(_x) (((_x) >> 12) & 0xfffff)
/* Register Type: MPCoreConfig */
#define NFP_ARM_GCSR_MP0_CFG 0x00e8
#define NFP_ARM_GCSR_MP0_CFG_SPI_BOOT (0x1 << 14)
#define NFP_ARM_GCSR_MP0_CFG_ENDIAN(_x) (((_x) & 0x3) << 12)
#define NFP_ARM_GCSR_MP0_CFG_ENDIAN_of(_x) (((_x) >> 12) & 0x3)
#define NFP_ARM_GCSR_MP0_CFG_ENDIAN_LITTLE (0)
#define NFP_ARM_GCSR_MP0_CFG_ENDIAN_BIG (1)
#define NFP_ARM_GCSR_MP0_CFG_RESET_VECTOR (0x1 << 8)
#define NFP_ARM_GCSR_MP0_CFG_RESET_VECTOR_LO (0x0)
#define NFP_ARM_GCSR_MP0_CFG_RESET_VECTOR_HI (0x100)
#define NFP_ARM_GCSR_MP0_CFG_OUTCLK_EN(_x) (((_x) & 0xf) << 4)
#define NFP_ARM_GCSR_MP0_CFG_OUTCLK_EN_of(_x) (((_x) >> 4) & 0xf)
#define NFP_ARM_GCSR_MP0_CFG_ARMID(_x) ((_x) & 0xf)
#define NFP_ARM_GCSR_MP0_CFG_ARMID_of(_x) ((_x) & 0xf)
/* Register Type: MPCoreIDCacheDataError */
#define NFP_ARM_GCSR_MP0_CACHE_ERR 0x00ec
#define NFP_ARM_GCSR_MP0_CACHE_ERR_MP0_D7 (0x1 << 15)
#define NFP_ARM_GCSR_MP0_CACHE_ERR_MP0_D6 (0x1 << 14)
#define NFP_ARM_GCSR_MP0_CACHE_ERR_MP0_D5 (0x1 << 13)
#define NFP_ARM_GCSR_MP0_CACHE_ERR_MP0_D4 (0x1 << 12)
#define NFP_ARM_GCSR_MP0_CACHE_ERR_MP0_D3 (0x1 << 11)
#define NFP_ARM_GCSR_MP0_CACHE_ERR_MP0_D2 (0x1 << 10)
#define NFP_ARM_GCSR_MP0_CACHE_ERR_MP0_D1 (0x1 << 9)
#define NFP_ARM_GCSR_MP0_CACHE_ERR_MP0_D0 (0x1 << 8)
#define NFP_ARM_GCSR_MP0_CACHE_ERR_MP0_I7 (0x1 << 7)
#define NFP_ARM_GCSR_MP0_CACHE_ERR_MP0_I6 (0x1 << 6)
#define NFP_ARM_GCSR_MP0_CACHE_ERR_MP0_I5 (0x1 << 5)
#define NFP_ARM_GCSR_MP0_CACHE_ERR_MP0_I4 (0x1 << 4)
#define NFP_ARM_GCSR_MP0_CACHE_ERR_MP0_I3 (0x1 << 3)
#define NFP_ARM_GCSR_MP0_CACHE_ERR_MP0_I2 (0x1 << 2)
#define NFP_ARM_GCSR_MP0_CACHE_ERR_MP0_I1 (0x1 << 1)
#define NFP_ARM_GCSR_MP0_CACHE_ERR_MP0_I0 (0x1)
/* Register Type: ARMDFT */
#define NFP_ARM_GCSR_DFT 0x0100
#define NFP_ARM_GCSR_DFT_DBG_REQ (0x1 << 20)
#define NFP_ARM_GCSR_DFT_DBG_EN (0x1 << 19)
#define NFP_ARM_GCSR_DFT_WFE_EVT_TRG (0x1 << 18)
#define NFP_ARM_GCSR_DFT_ETM_WFI_RDY (0x1 << 17)
#define NFP_ARM_GCSR_DFT_ETM_PWR_ON (0x1 << 16)
#define NFP_ARM_GCSR_DFT_BIST_FAIL_of(_x) (((_x) >> 8) & 0xf)
#define NFP_ARM_GCSR_DFT_BIST_DONE_of(_x) (((_x) >> 4) & 0xf)
#define NFP_ARM_GCSR_DFT_BIST_RUN(_x) ((_x) & 0x7)
#define NFP_ARM_GCSR_DFT_BIST_RUN_of(_x) ((_x) & 0x7)
/* Gasket CSRs */
/* NOTE: These cannot be remapped, and are always at this location.
*/
#define NFP_ARM_GCSR_START (0xd6000000 + NFP_ARM_GCSR)
#define NFP_ARM_GCSR_SIZE SZ_64K
/* BAR CSRs
*/
#define NFP_ARM_GCSR_BULK_BITS 11
#define NFP_ARM_GCSR_EXPA_BITS 15
#define NFP_ARM_GCSR_EXPL_BITS 18
#define NFP_ARM_GCSR_BULK_SHIFT (40 - 11)
#define NFP_ARM_GCSR_EXPA_SHIFT (40 - 15)
#define NFP_ARM_GCSR_EXPL_SHIFT (40 - 18)
#define NFP_ARM_GCSR_BULK_SIZE (1 << NFP_ARM_GCSR_BULK_SHIFT)
#define NFP_ARM_GCSR_EXPA_SIZE (1 << NFP_ARM_GCSR_EXPA_SHIFT)
#define NFP_ARM_GCSR_EXPL_SIZE (1 << NFP_ARM_GCSR_EXPL_SHIFT)
#define NFP_ARM_GCSR_EXPL2_CSR(target, action, length, \
byte_mask, token, signal_master) \
(NFP_ARM_GCSR_EXPL2_BAR_TGT(target) | \
NFP_ARM_GCSR_EXPL2_BAR_ACT(action) | \
NFP_ARM_GCSR_EXPL2_BAR_LEN(length) | \
NFP_ARM_GCSR_EXPL2_BAR_BYTE_MASK(byte_mask) | \
NFP_ARM_GCSR_EXPL2_BAR_TOK(token) | \
NFP_ARM_GCSR_EXPL2_BAR_SIGNAL_MASTER(signal_master))
#define NFP_ARM_GCSR_EXPL1_CSR(posted, signal_ref, data_master, data_ref) \
(((posted) ? NFP_ARM_GCSR_EXPL1_BAR_POSTED : 0) | \
NFP_ARM_GCSR_EXPL1_BAR_SIGNAL_REF(signal_ref) | \
NFP_ARM_GCSR_EXPL1_BAR_DATA_MASTER(data_master) | \
NFP_ARM_GCSR_EXPL1_BAR_DATA_REF(data_ref))
#define NFP_ARM_GCSR_EXPL0_CSR(address) \
NFP_ARM_GCSR_EXPL0_BAR_ADDR((address) >> NFP_ARM_GCSR_EXPL_SHIFT)
#define NFP_ARM_GCSR_EXPL_POST_EXPECT_A(sig_ref, is_push, is_required) \
(NFP_ARM_GCSR_EXPL_POST_SIG_A(sig_ref) | \
((is_push) ? NFP_ARM_GCSR_EXPL_POST_SIG_A_BUS_PUSH : \
NFP_ARM_GCSR_EXPL_POST_SIG_A_BUS_PULL) | \
((is_required) ? NFP_ARM_GCSR_EXPL_POST_SIG_A_VALID : 0))
#define NFP_ARM_GCSR_EXPL_POST_EXPECT_B(sig_ref, is_push, is_required) \
(NFP_ARM_GCSR_EXPL_POST_SIG_B(sig_ref) | \
((is_push) ? NFP_ARM_GCSR_EXPL_POST_SIG_B_BUS_PUSH : \
NFP_ARM_GCSR_EXPL_POST_SIG_B_BUS_PULL) | \
((is_required) ? NFP_ARM_GCSR_EXPL_POST_SIG_B_VALID : 0))
#define NFP_ARM_GCSR_EXPA_CSR(mode, target, token, is_64, action, address) \
(((mode) ? NFP_ARM_GCSR_EXPA_BAR_TYPE_EXPL : \
NFP_ARM_GCSR_EXPA_BAR_TYPE_EXPA) | \
NFP_ARM_GCSR_EXPA_BAR_TGT(target) | \
NFP_ARM_GCSR_EXPA_BAR_TOK(token) | \
((is_64) ? NFP_ARM_GCSR_EXPA_BAR_LEN_64BIT : \
NFP_ARM_GCSR_EXPA_BAR_LEN_32BIT) | \
NFP_ARM_GCSR_EXPA_BAR_ACT(action) | \
NFP_ARM_GCSR_EXPA_BAR_ADDR((address) >> NFP_ARM_GCSR_EXPA_SHIFT))
#define NFP_ARM_GCSR_BULK_CSR(mode, target, token, is_64, address) \
(((mode) ? NFP_ARM_GCSR_BULK_BAR_TYPE_EXPA : \
NFP_ARM_GCSR_BULK_BAR_TYPE_BULK) | \
NFP_ARM_GCSR_BULK_BAR_TGT(target) | \
NFP_ARM_GCSR_BULK_BAR_TOK(token) | \
((is_64) ? NFP_ARM_GCSR_BULK_BAR_LEN_64BIT : \
NFP_ARM_GCSR_BULK_BAR_LEN_32BIT) | \
NFP_ARM_GCSR_BULK_BAR_ADDR((address) >> NFP_ARM_GCSR_BULK_SHIFT))
/* MP Core CSRs */
#define NFP_ARM_MPCORE_SIZE SZ_128K
/* PL320 CSRs */
#define NFP_ARM_PCSR_SIZE SZ_64K
#endif /* NFP_ARM_H */
| {'repo_name': 'sslab-gatech/janus', 'stars': '122', 'repo_language': 'C', 'file_name': 'spectrum_span.h', 'mime_type': 'text/x-c', 'hash': -5127438585979809665, 'source_dataset': 'data'} |
#ifndef _ZQ_GRAPH_CUT_H_
#define _ZQ_GRAPH_CUT_H_
#pragma once
/******************************/
/* The following code is copied from the lib graphcut.
/* block.h
/* graph.h
/* graph.cpp
/* maxflow.cpp
/*
/**********************************/
#include <string.h>
#include <stdlib.h>
#include <assert.h>
namespace ZQ
{
/* block.h */
/*
Template classes Block and DBlock
Implement adding and deleting items of the same type in blocks.
If there there are many items then using Block or DBlock
is more efficient than using 'new' and 'delete' both in terms
of memory and time since
(1) On some systems there is some minimum amount of memory
that 'new' can allocate (e.g., 64), so if items are
small that a lot of memory is wasted.
(2) 'new' and 'delete' are designed for items of varying size.
If all items has the same size, then an algorithm for
adding and deleting can be made more efficient.
(3) All Block and DBlock functions are inline, so there are
no extra function calls.
Differences between Block and DBlock:
(1) DBlock allows both adding and deleting items,
whereas Block allows only adding items.
(2) Block has an additional operation of scanning
items added so far (in the order in which they were added).
(3) Block allows to allocate several consecutive
items at a time, whereas DBlock can add only a single item.
Note that no constructors or destructors are called for items.
Example usage for items of type 'MyType':
///////////////////////////////////////////////////
#include "block.h"
#define BLOCK_SIZE 1024
typedef struct { int a, b; } MyType;
MyType *ptr, *array[10000];
...
Block<MyType> *block = new Block<MyType>(BLOCK_SIZE);
// adding items
for (int i=0; i<sizeof(array); i++)
{
ptr = block -> New();
ptr -> a = ptr -> b = rand();
}
// reading items
for (ptr=block->ScanFirst(); ptr; ptr=block->ScanNext())
{
printf("%d %d\n", ptr->a, ptr->b);
}
delete block;
...
DBlock<MyType> *dblock = new DBlock<MyType>(BLOCK_SIZE);
// adding items
for (int i=0; i<sizeof(array); i++)
{
array[i] = dblock -> New();
}
// deleting items
for (int i=0; i<sizeof(array); i+=2)
{
dblock -> Delete(array[i]);
}
// adding items
for (int i=0; i<sizeof(array); i++)
{
array[i] = dblock -> New();
}
delete dblock;
///////////////////////////////////////////////////
Note that DBlock deletes items by marking them as
empty (i.e., by adding them to the list of free items),
so that this memory could be used for subsequently
added items. Thus, at each moment the memory allocated
is determined by the maximum number of items allocated
simultaneously at earlier moments. All memory is
deallocated only when the destructor is called.
*/
/***********************************************************************/
/***********************************************************************/
/***********************************************************************/
template <class Type> class Block
{
public:
/* Constructor. Arguments are the block size and
(optionally) the pointer to the function which
will be called if allocation failed; the message
passed to this function is "Not enough memory!" */
Block(int size, void(*err_function)(char *) = NULL) { first = last = NULL; block_size = size; error_function = err_function; }
/* Destructor. Deallocates all items added so far */
~Block() { while (first) { block *next = first->next; delete[]((char*)first); first = next; } }
/* Allocates 'num' consecutive items; returns pointer
to the first item. 'num' cannot be greater than the
block size since items must fit in one block */
Type *New(int num = 1)
{
Type *t;
if (!last || last->current + num > last->last)
{
if (last && last->next) last = last->next;
else
{
block *next = (block *) new char[sizeof(block) + (block_size - 1) * sizeof(Type)];
if (!next) { if (error_function) (*error_function)("Not enough memory!"); exit(1); }
if (last) last->next = next;
else first = next;
last = next;
last->current = &(last->data[0]);
last->last = last->current + block_size;
last->next = NULL;
}
}
t = last->current;
last->current += num;
return t;
}
/* Returns the first item (or NULL, if no items were added) */
Type *ScanFirst()
{
for (scan_current_block = first; scan_current_block; scan_current_block = scan_current_block->next)
{
scan_current_data = &(scan_current_block->data[0]);
if (scan_current_data < scan_current_block->current) return scan_current_data++;
}
return NULL;
}
/* Returns the next item (or NULL, if all items have been read)
Can be called only if previous ScanFirst() or ScanNext()
call returned not NULL. */
Type *ScanNext()
{
while (scan_current_data >= scan_current_block->current)
{
scan_current_block = scan_current_block->next;
if (!scan_current_block) return NULL;
scan_current_data = &(scan_current_block->data[0]);
}
return scan_current_data++;
}
/* Marks all elements as empty */
void Reset()
{
block *b;
if (!first) return;
for (b = first; ; b = b->next)
{
b->current = &(b->data[0]);
if (b == last) break;
}
last = first;
}
/***********************************************************************/
private:
typedef struct block_st
{
Type *current, *last;
struct block_st *next;
Type data[1];
} block;
int block_size;
block *first;
block *last;
block *scan_current_block;
Type *scan_current_data;
void(*error_function)(char *);
};
/***********************************************************************/
/***********************************************************************/
/***********************************************************************/
template <class Type> class DBlock
{
public:
/* Constructor. Arguments are the block size and
(optionally) the pointer to the function which
will be called if allocation failed; the message
passed to this function is "Not enough memory!" */
DBlock(int size, void(*err_function)(char *) = NULL) { first = NULL; first_free = NULL; block_size = size; error_function = err_function; }
/* Destructor. Deallocates all items added so far */
~DBlock() { while (first) { block *next = first->next; delete[]((char*)first); first = next; } }
/* Allocates one item */
Type *New()
{
block_item *item;
if (!first_free)
{
block *next = first;
first = (block *) new char[sizeof(block) + (block_size - 1) * sizeof(block_item)];
if (!first) { if (error_function) (*error_function)("Not enough memory!"); exit(1); }
first_free = &(first->data[0]);
for (item = first_free; item < first_free + block_size - 1; item++)
item->next_free = item + 1;
item->next_free = NULL;
first->next = next;
}
item = first_free;
first_free = item->next_free;
return (Type *)item;
}
/* Deletes an item allocated previously */
void Delete(Type *t)
{
((block_item *)t)->next_free = first_free;
first_free = (block_item *)t;
}
/***********************************************************************/
private:
typedef union block_item_st
{
Type t;
block_item_st *next_free;
} block_item;
typedef struct block_st
{
struct block_st *next;
block_item data[1];
} block;
int block_size;
block *first;
block_item *first_free;
void(*error_function)(char *);
};
/* graph.h */
/*
This software library implements the maxflow algorithm
described in
"An Experimental Comparison of Min-Cut/Max-Flow Algorithms for Energy Minimization in Vision."
Yuri Boykov and Vladimir Kolmogorov.
In IEEE Transactions on Pattern Analysis and Machine Intelligence (PAMI),
September 2004
This algorithm was developed by Yuri Boykov and Vladimir Kolmogorov
at Siemens Corporate Research. To make it available for public use,
it was later reimplemented by Vladimir Kolmogorov based on open publications.
If you use this software for research purposes, you should cite
the aforementioned paper in any resulting publication.
----------------------------------------------------------------------
REUSING TREES:
Starting with version 3.0, there is a also an option of reusing search
trees from one maxflow computation to the next, as described in
"Efficiently Solving Dynamic Markov Random Fields Using Graph Cuts."
Pushmeet Kohli and Philip H.S. Torr
International Conference on Computer Vision (ICCV), 2005
If you use this option, you should cite
the aforementioned paper in any resulting publication.
*/
/*
For description, license, example usage see README.TXT.
*/
// NOTE: in UNIX you need to use -DNDEBUG preprocessor option to supress assert's!!!
// captype: type of edge capacities (excluding t-links)
// tcaptype: type of t-links (edges between nodes and terminals)
// flowtype: type of total flow
//
// Current instantiations are in instances.inc
template <typename captype, typename tcaptype, typename flowtype> class Graph
{
public:
typedef enum
{
SOURCE = 0,
SINK = 1
} termtype; // terminals
typedef int node_id;
/////////////////////////////////////////////////////////////////////////
// BASIC INTERFACE FUNCTIONS //
// (should be enough for most applications) //
/////////////////////////////////////////////////////////////////////////
// Constructor.
// The first argument gives an estimate of the maximum number of nodes that can be added
// to the graph, and the second argument is an estimate of the maximum number of edges.
// The last (optional) argument is the pointer to the function which will be called
// if an error occurs; an error message is passed to this function.
// If this argument is omitted, exit(1) will be called.
//
// IMPORTANT: It is possible to add more nodes to the graph than node_num_max
// (and node_num_max can be zero). However, if the count is exceeded, then
// the internal memory is reallocated (increased by 50%) which is expensive.
// Also, temporarily the amount of allocated memory would be more than twice than needed.
// Similarly for edges.
// If you wish to avoid this overhead, you can download version 2.2, where nodes and edges are stored in blocks.
Graph(int node_num_max, int edge_num_max, void(*err_function)(char *) = NULL);
// Destructor
~Graph();
// Adds node(s) to the graph. By default, one node is added (num=1); then first call returns 0, second call returns 1, and so on.
// If num>1, then several nodes are added, and node_id of the first one is returned.
// IMPORTANT: see note about the constructor
node_id add_node(int num = 1);
// Adds a bidirectional edge between 'i' and 'j' with the weights 'cap' and 'rev_cap'.
// IMPORTANT: see note about the constructor
void add_edge(node_id i, node_id j, captype cap, captype rev_cap);
// Adds new edges 'SOURCE->i' and 'i->SINK' with corresponding weights.
// Can be called multiple times for each node.
// Weights can be negative.
// NOTE: the number of such edges is not counted in edge_num_max.
// No internal memory is allocated by this call.
void add_tweights(node_id i, tcaptype cap_source, tcaptype cap_sink);
// Computes the maxflow. Can be called several times.
// FOR DESCRIPTION OF reuse_trees, SEE mark_node().
// FOR DESCRIPTION OF changed_list, SEE remove_from_changed_list().
flowtype maxflow(bool reuse_trees = false, Block<node_id>* changed_list = NULL);
// After the maxflow is computed, this function returns to which
// segment the node 'i' belongs (Graph<captype,tcaptype,flowtype>::SOURCE or Graph<captype,tcaptype,flowtype>::SINK).
//
// Occasionally there may be several minimum cuts. If a node can be assigned
// to both the source and the sink, then default_segm is returned.
termtype what_segment(node_id i, termtype default_segm = SOURCE);
//////////////////////////////////////////////
// ADVANCED INTERFACE FUNCTIONS //
// (provide access to the graph) //
//////////////////////////////////////////////
private:
struct node;
struct arc;
public:
////////////////////////////
// 1. Reallocating graph. //
////////////////////////////
// Removes all nodes and edges.
// After that functions add_node() and add_edge() must be called again.
//
// Advantage compared to deleting Graph and allocating it again:
// no calls to delete/new (which could be quite slow).
//
// If the graph structure stays the same, then an alternative
// is to go through all nodes/edges and set new residual capacities
// (see functions below).
void reset();
////////////////////////////////////////////////////////////////////////////////
// 2. Functions for getting pointers to arcs and for reading graph structure. //
// NOTE: adding new arcs may invalidate these pointers (if reallocation //
// happens). So it's best not to add arcs while reading graph structure. //
////////////////////////////////////////////////////////////////////////////////
// The following two functions return arcs in the same order that they
// were added to the graph. NOTE: for each call add_edge(i,j,cap,cap_rev)
// the first arc returned will be i->j, and the second j->i.
// If there are no more arcs, then the function can still be called, but
// the returned arc_id is undetermined.
typedef arc* arc_id;
arc_id get_first_arc();
arc_id get_next_arc(arc_id a);
// other functions for reading graph structure
int get_node_num() { return node_num; }
int get_arc_num() { return (int)(arc_last - arcs); }
void get_arc_ends(arc_id a, node_id& i, node_id& j); // returns i,j to that a = i->j
///////////////////////////////////////////////////
// 3. Functions for reading residual capacities. //
///////////////////////////////////////////////////
// returns residual capacity of SOURCE->i minus residual capacity of i->SINK
tcaptype get_trcap(node_id i);
// returns residual capacity of arc a
captype get_rcap(arc* a);
/////////////////////////////////////////////////////////////////
// 4. Functions for setting residual capacities. //
// NOTE: If these functions are used, the value of the flow //
// returned by maxflow() will not be valid! //
/////////////////////////////////////////////////////////////////
void set_trcap(node_id i, tcaptype trcap);
void set_rcap(arc* a, captype rcap);
////////////////////////////////////////////////////////////////////
// 5. Functions related to reusing trees & list of changed nodes. //
////////////////////////////////////////////////////////////////////
// If flag reuse_trees is true while calling maxflow(), then search trees
// are reused from previous maxflow computation.
// In this case before calling maxflow() the user must
// specify which parts of the graph have changed by calling mark_node():
// add_tweights(i),set_trcap(i) => call mark_node(i)
// add_edge(i,j),set_rcap(a) => call mark_node(i); mark_node(j)
//
// This option makes sense only if a small part of the graph is changed.
// The initialization procedure goes only through marked nodes then.
//
// mark_node(i) can either be called before or after graph modification.
// Can be called more than once per node, but calls after the first one
// do not have any effect.
//
// NOTE:
// - This option cannot be used in the first call to maxflow().
// - It is not necessary to call mark_node() if the change is ``not essential'',
// i.e. sign(trcap) is preserved for a node and zero/nonzero status is preserved for an arc.
// - To check that you marked all necessary nodes, you can call maxflow(false) after calling maxflow(true).
// If everything is correct, the two calls must return the same value of flow. (Useful for debugging).
void mark_node(node_id i);
// If changed_list is not NULL while calling maxflow(), then the algorithm
// keeps a list of nodes which could potentially have changed their segmentation label.
// Nodes which are not in the list are guaranteed to keep their old segmentation label (SOURCE or SINK).
// Example usage:
//
// typedef Graph<int,int,int> G;
// G* g = new Graph(nodeNum, edgeNum);
// Block<G::node_id>* changed_list = new Block<G::node_id>(128);
//
// ... // add nodes and edges
//
// g->maxflow(); // first call should be without arguments
// for (int iter=0; iter<10; iter++)
// {
// ... // change graph, call mark_node() accordingly
//
// g->maxflow(true, changed_list);
// G::node_id* ptr;
// for (ptr=changed_list->ScanFirst(); ptr; ptr=changed_list->ScanNext())
// {
// G::node_id i = *ptr; assert(i>=0 && i<nodeNum);
// g->remove_from_changed_list(i);
// // do something with node i...
// if (g->what_segment(i) == G::SOURCE) { ... }
// }
// changed_list->Reset();
// }
// delete changed_list;
//
// NOTE:
// - If changed_list option is used, then reuse_trees must be used as well.
// - In the example above, the user may omit calls g->remove_from_changed_list(i) and changed_list->Reset() in a given iteration.
// Then during the next call to maxflow(true, &changed_list) new nodes will be added to changed_list.
// - If the next call to maxflow() does not use option reuse_trees, then calling remove_from_changed_list()
// is not necessary. ("changed_list->Reset()" or "delete changed_list" should still be called, though).
void remove_from_changed_list(node_id i)
{
assert(i >= 0 && i < node_num && nodes[i].is_in_changed_list);
nodes[i].is_in_changed_list = 0;
}
/////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////
private:
// internal variables and functions
struct node
{
arc *first; // first outcoming arc
arc *parent; // node's parent
node *next; // pointer to the next active node
// (or to itself if it is the last node in the list)
int TS; // timestamp showing when DIST was computed
int DIST; // distance to the terminal
int is_sink : 1; // flag showing whether the node is in the source or in the sink tree (if parent!=NULL)
int is_marked : 1; // set by mark_node()
int is_in_changed_list : 1; // set by maxflow if
tcaptype tr_cap; // if tr_cap > 0 then tr_cap is residual capacity of the arc SOURCE->node
// otherwise -tr_cap is residual capacity of the arc node->SINK
};
struct arc
{
node *head; // node the arc points to
arc *next; // next arc with the same originating node
arc *sister; // reverse arc
captype r_cap; // residual capacity
};
struct nodeptr
{
node *ptr;
nodeptr *next;
};
static const int NODEPTR_BLOCK_SIZE = 128;
node *nodes, *node_last, *node_max; // node_last = nodes+node_num, node_max = nodes+node_num_max;
arc *arcs, *arc_last, *arc_max; // arc_last = arcs+2*edge_num, arc_max = arcs+2*edge_num_max;
int node_num;
DBlock<nodeptr> *nodeptr_block;
void(*error_function)(char *); // this function is called if a error occurs,
// with a corresponding error message
// (or exit(1) is called if it's NULL)
flowtype flow; // total flow
// reusing trees & list of changed pixels
int maxflow_iteration; // counter
Block<node_id> *changed_list;
/////////////////////////////////////////////////////////////////////////
node *queue_first[2], *queue_last[2]; // list of active nodes
nodeptr *orphan_first, *orphan_last; // list of pointers to orphans
int TIME; // monotonically increasing global counter
/////////////////////////////////////////////////////////////////////////
void reallocate_nodes(int num); // num is the number of new nodes
void reallocate_arcs();
// functions for processing active list
void set_active(node *i);
node *next_active();
// functions for processing orphans list
void set_orphan_front(node* i); // add to the beginning of the list
void set_orphan_rear(node* i); // add to the end of the list
void add_to_changed_list(node* i);
void maxflow_init(); // called if reuse_trees == false
void maxflow_reuse_trees_init(); // called if reuse_trees == true
void augment(arc *middle_arc);
void process_source_orphan(node *i);
void process_sink_orphan(node *i);
void test_consistency(node* current_node = NULL); // debug function
};
///////////////////////////////////////
// Implementation - inline functions //
///////////////////////////////////////
template <typename captype, typename tcaptype, typename flowtype>
inline typename Graph<captype, tcaptype, flowtype>::node_id Graph<captype, tcaptype, flowtype>::add_node(int num)
{
assert(num > 0);
if (node_last + num > node_max) reallocate_nodes(num);
if (num == 1)
{
node_last->first = NULL;
node_last->tr_cap = 0;
node_last->is_marked = 0;
node_last->is_in_changed_list = 0;
node_last++;
return node_num++;
}
else
{
memset(node_last, 0, num * sizeof(node));
node_id i = node_num;
node_num += num;
node_last += num;
return i;
}
}
template <typename captype, typename tcaptype, typename flowtype>
inline void Graph<captype, tcaptype, flowtype>::add_tweights(node_id i, tcaptype cap_source, tcaptype cap_sink)
{
assert(i >= 0 && i < node_num);
tcaptype delta = nodes[i].tr_cap;
if (delta > 0) cap_source += delta;
else cap_sink -= delta;
flow += (cap_source < cap_sink) ? cap_source : cap_sink;
nodes[i].tr_cap = cap_source - cap_sink;
}
template <typename captype, typename tcaptype, typename flowtype>
inline void Graph<captype, tcaptype, flowtype>::add_edge(node_id _i, node_id _j, captype cap, captype rev_cap)
{
assert(_i >= 0 && _i < node_num);
assert(_j >= 0 && _j < node_num);
assert(_i != _j);
assert(cap >= 0);
assert(rev_cap >= 0);
if (arc_last == arc_max) reallocate_arcs();
arc *a = arc_last++;
arc *a_rev = arc_last++;
node* i = nodes + _i;
node* j = nodes + _j;
a->sister = a_rev;
a_rev->sister = a;
a->next = i->first;
i->first = a;
a_rev->next = j->first;
j->first = a_rev;
a->head = j;
a_rev->head = i;
a->r_cap = cap;
a_rev->r_cap = rev_cap;
}
template <typename captype, typename tcaptype, typename flowtype>
inline typename Graph<captype, tcaptype, flowtype>::arc* Graph<captype, tcaptype, flowtype>::get_first_arc()
{
return arcs;
}
template <typename captype, typename tcaptype, typename flowtype>
inline typename Graph<captype, tcaptype, flowtype>::arc* Graph<captype, tcaptype, flowtype>::get_next_arc(arc* a)
{
return a + 1;
}
template <typename captype, typename tcaptype, typename flowtype>
inline void Graph<captype, tcaptype, flowtype>::get_arc_ends(arc* a, node_id& i, node_id& j)
{
assert(a >= arcs && a < arc_last);
i = (node_id)(a->sister->head - nodes);
j = (node_id)(a->head - nodes);
}
template <typename captype, typename tcaptype, typename flowtype>
inline tcaptype Graph<captype, tcaptype, flowtype>::get_trcap(node_id i)
{
assert(i >= 0 && i < node_num);
return nodes[i].tr_cap;
}
template <typename captype, typename tcaptype, typename flowtype>
inline captype Graph<captype, tcaptype, flowtype>::get_rcap(arc* a)
{
assert(a >= arcs && a < arc_last);
return a->r_cap;
}
template <typename captype, typename tcaptype, typename flowtype>
inline void Graph<captype, tcaptype, flowtype>::set_trcap(node_id i, tcaptype trcap)
{
assert(i >= 0 && i < node_num);
nodes[i].tr_cap = trcap;
}
template <typename captype, typename tcaptype, typename flowtype>
inline void Graph<captype, tcaptype, flowtype>::set_rcap(arc* a, captype rcap)
{
assert(a >= arcs && a < arc_last);
a->r_cap = rcap;
}
template <typename captype, typename tcaptype, typename flowtype>
inline typename Graph<captype, tcaptype, flowtype>::termtype Graph<captype, tcaptype, flowtype>::what_segment(node_id i, termtype default_segm)
{
if (nodes[i].parent)
{
return (nodes[i].is_sink) ? SINK : SOURCE;
}
else
{
return default_segm;
}
}
template <typename captype, typename tcaptype, typename flowtype>
inline void Graph<captype, tcaptype, flowtype>::mark_node(node_id _i)
{
node* i = nodes + _i;
if (!i->next)
{
/* it's not in the list yet */
if (queue_last[1]) queue_last[1]->next = i;
else queue_first[1] = i;
queue_last[1] = i;
i->next = i;
}
i->is_marked = 1;
}
/* graph.cpp */
template <typename captype, typename tcaptype, typename flowtype>
Graph<captype, tcaptype, flowtype>::Graph(int node_num_max, int edge_num_max, void(*err_function)(char *))
: node_num(0),
nodeptr_block(NULL),
error_function(err_function)
{
if (node_num_max < 16) node_num_max = 16;
if (edge_num_max < 16) edge_num_max = 16;
nodes = (node*)malloc(node_num_max * sizeof(node));
arcs = (arc*)malloc(2 * edge_num_max * sizeof(arc));
if (!nodes || !arcs) { if (error_function) (*error_function)("Not enough memory!"); exit(1); }
node_last = nodes;
node_max = nodes + node_num_max;
arc_last = arcs;
arc_max = arcs + 2 * edge_num_max;
maxflow_iteration = 0;
flow = 0;
}
template <typename captype, typename tcaptype, typename flowtype>
Graph<captype, tcaptype, flowtype>::~Graph()
{
if (nodeptr_block)
{
delete nodeptr_block;
nodeptr_block = NULL;
}
free(nodes);
free(arcs);
}
template <typename captype, typename tcaptype, typename flowtype>
void Graph<captype, tcaptype, flowtype>::reset()
{
node_last = nodes;
arc_last = arcs;
node_num = 0;
if (nodeptr_block)
{
delete nodeptr_block;
nodeptr_block = NULL;
}
maxflow_iteration = 0;
flow = 0;
}
template <typename captype, typename tcaptype, typename flowtype>
void Graph<captype, tcaptype, flowtype>::reallocate_nodes(int num)
{
int node_num_max = (int)(node_max - nodes);
node* nodes_old = nodes;
node_num_max += node_num_max / 2;
if (node_num_max < node_num + num) node_num_max = node_num + num;
nodes = (node*)realloc(nodes_old, node_num_max * sizeof(node));
if (!nodes) { if (error_function) (*error_function)("Not enough memory!"); exit(1); }
node_last = nodes + node_num;
node_max = nodes + node_num_max;
if (nodes != nodes_old)
{
arc* a;
for (a = arcs; a < arc_last; a++)
{
a->head = (node*)((char*)a->head + (((char*)nodes) - ((char*)nodes_old)));
}
}
}
template <typename captype, typename tcaptype, typename flowtype>
void Graph<captype, tcaptype, flowtype>::reallocate_arcs()
{
int arc_num_max = (int)(arc_max - arcs);
int arc_num = (int)(arc_last - arcs);
arc* arcs_old = arcs;
arc_num_max += arc_num_max / 2; if (arc_num_max & 1) arc_num_max++;
arcs = (arc*)realloc(arcs_old, arc_num_max * sizeof(arc));
if (!arcs) { if (error_function) (*error_function)("Not enough memory!"); exit(1); }
arc_last = arcs + arc_num;
arc_max = arcs + arc_num_max;
if (arcs != arcs_old)
{
node* i;
arc* a;
for (i = nodes; i < node_last; i++)
{
if (i->first) i->first = (arc*)((char*)i->first + (((char*)arcs) - ((char*)arcs_old)));
}
for (a = arcs; a < arc_last; a++)
{
if (a->next) a->next = (arc*)((char*)a->next + (((char*)arcs) - ((char*)arcs_old)));
a->sister = (arc*)((char*)a->sister + (((char*)arcs) - ((char*)arcs_old)));
}
}
}
/* maxflow.cpp */
/*
special constants for node->parent
*/
#define TERMINAL ( (arc *) 1 ) /* to terminal */
#define ORPHAN ( (arc *) 2 ) /* orphan */
#define INFINITE_D ((int)(((unsigned)-1)/2)) /* infinite distance to the terminal */
/***********************************************************************/
/*
Functions for processing active list.
i->next points to the next node in the list
(or to i, if i is the last node in the list).
If i->next is NULL iff i is not in the list.
There are two queues. Active nodes are added
to the end of the second queue and read from
the front of the first queue. If the first queue
is empty, it is replaced by the second queue
(and the second queue becomes empty).
*/
template <typename captype, typename tcaptype, typename flowtype>
inline void Graph<captype, tcaptype, flowtype>::set_active(node *i)
{
if (!i->next)
{
/* it's not in the list yet */
if (queue_last[1]) queue_last[1]->next = i;
else queue_first[1] = i;
queue_last[1] = i;
i->next = i;
}
}
/*
Returns the next active node.
If it is connected to the sink, it stays in the list,
otherwise it is removed from the list
*/
template <typename captype, typename tcaptype, typename flowtype>
inline typename Graph<captype, tcaptype, flowtype>::node* Graph<captype, tcaptype, flowtype>::next_active()
{
node *i;
while (1)
{
if (!(i = queue_first[0]))
{
queue_first[0] = i = queue_first[1];
queue_last[0] = queue_last[1];
queue_first[1] = NULL;
queue_last[1] = NULL;
if (!i) return NULL;
}
/* remove it from the active list */
if (i->next == i) queue_first[0] = queue_last[0] = NULL;
else queue_first[0] = i->next;
i->next = NULL;
/* a node in the list is active iff it has a parent */
if (i->parent) return i;
}
}
/***********************************************************************/
template <typename captype, typename tcaptype, typename flowtype>
inline void Graph<captype, tcaptype, flowtype>::set_orphan_front(node *i)
{
nodeptr *np;
i->parent = ORPHAN;
np = nodeptr_block->New();
np->ptr = i;
np->next = orphan_first;
orphan_first = np;
}
template <typename captype, typename tcaptype, typename flowtype>
inline void Graph<captype, tcaptype, flowtype>::set_orphan_rear(node *i)
{
nodeptr *np;
i->parent = ORPHAN;
np = nodeptr_block->New();
np->ptr = i;
if (orphan_last) orphan_last->next = np;
else orphan_first = np;
orphan_last = np;
np->next = NULL;
}
/***********************************************************************/
template <typename captype, typename tcaptype, typename flowtype>
inline void Graph<captype, tcaptype, flowtype>::add_to_changed_list(node *i)
{
if (changed_list && !i->is_in_changed_list)
{
node_id* ptr = changed_list->New();
*ptr = (node_id)(i - nodes);
i->is_in_changed_list = true;
}
}
/***********************************************************************/
template <typename captype, typename tcaptype, typename flowtype>
void Graph<captype, tcaptype, flowtype>::maxflow_init()
{
node *i;
queue_first[0] = queue_last[0] = NULL;
queue_first[1] = queue_last[1] = NULL;
orphan_first = NULL;
TIME = 0;
for (i = nodes; i < node_last; i++)
{
i->next = NULL;
i->is_marked = 0;
i->is_in_changed_list = 0;
i->TS = TIME;
if (i->tr_cap > 0)
{
/* i is connected to the source */
i->is_sink = 0;
i->parent = TERMINAL;
set_active(i);
i->DIST = 1;
}
else if (i->tr_cap < 0)
{
/* i is connected to the sink */
i->is_sink = 1;
i->parent = TERMINAL;
set_active(i);
i->DIST = 1;
}
else
{
i->parent = NULL;
}
}
}
template <typename captype, typename tcaptype, typename flowtype>
void Graph<captype, tcaptype, flowtype>::maxflow_reuse_trees_init()
{
node* i;
node* j;
node* queue = queue_first[1];
arc* a;
nodeptr* np;
queue_first[0] = queue_last[0] = NULL;
queue_first[1] = queue_last[1] = NULL;
orphan_first = orphan_last = NULL;
TIME++;
while ((i = queue))
{
queue = i->next;
if (queue == i) queue = NULL;
i->next = NULL;
i->is_marked = 0;
set_active(i);
if (i->tr_cap == 0)
{
if (i->parent) set_orphan_rear(i);
continue;
}
if (i->tr_cap > 0)
{
if (!i->parent || i->is_sink)
{
i->is_sink = 0;
for (a = i->first; a; a = a->next)
{
j = a->head;
if (!j->is_marked)
{
if (j->parent == a->sister) set_orphan_rear(j);
if (j->parent && j->is_sink && a->r_cap > 0) set_active(j);
}
}
add_to_changed_list(i);
}
}
else
{
if (!i->parent || !i->is_sink)
{
i->is_sink = 1;
for (a = i->first; a; a = a->next)
{
j = a->head;
if (!j->is_marked)
{
if (j->parent == a->sister) set_orphan_rear(j);
if (j->parent && !j->is_sink && a->sister->r_cap > 0) set_active(j);
}
}
add_to_changed_list(i);
}
}
i->parent = TERMINAL;
i->TS = TIME;
i->DIST = 1;
}
//test_consistency();
/* adoption */
while ((np = orphan_first))
{
orphan_first = np->next;
i = np->ptr;
nodeptr_block->Delete(np);
if (!orphan_first) orphan_last = NULL;
if (i->is_sink) process_sink_orphan(i);
else process_source_orphan(i);
}
/* adoption end */
//test_consistency();
}
template <typename captype, typename tcaptype, typename flowtype>
void Graph<captype, tcaptype, flowtype>::augment(arc *middle_arc)
{
node *i;
arc *a;
tcaptype bottleneck;
/* 1. Finding bottleneck capacity */
/* 1a - the source tree */
bottleneck = middle_arc->r_cap;
for (i = middle_arc->sister->head; ; i = a->head)
{
a = i->parent;
if (a == TERMINAL) break;
if (bottleneck > a->sister->r_cap) bottleneck = a->sister->r_cap;
}
if (bottleneck > i->tr_cap) bottleneck = i->tr_cap;
/* 1b - the sink tree */
for (i = middle_arc->head; ; i = a->head)
{
a = i->parent;
if (a == TERMINAL) break;
if (bottleneck > a->r_cap) bottleneck = a->r_cap;
}
if (bottleneck > -i->tr_cap) bottleneck = -i->tr_cap;
/* 2. Augmenting */
/* 2a - the source tree */
middle_arc->sister->r_cap += bottleneck;
middle_arc->r_cap -= bottleneck;
for (i = middle_arc->sister->head; ; i = a->head)
{
a = i->parent;
if (a == TERMINAL) break;
a->r_cap += bottleneck;
a->sister->r_cap -= bottleneck;
if (!a->sister->r_cap)
{
set_orphan_front(i); // add i to the beginning of the adoption list
}
}
i->tr_cap -= bottleneck;
if (!i->tr_cap)
{
set_orphan_front(i); // add i to the beginning of the adoption list
}
/* 2b - the sink tree */
for (i = middle_arc->head; ; i = a->head)
{
a = i->parent;
if (a == TERMINAL) break;
a->sister->r_cap += bottleneck;
a->r_cap -= bottleneck;
if (!a->r_cap)
{
set_orphan_front(i); // add i to the beginning of the adoption list
}
}
i->tr_cap += bottleneck;
if (!i->tr_cap)
{
set_orphan_front(i); // add i to the beginning of the adoption list
}
flow += bottleneck;
}
/***********************************************************************/
template <typename captype, typename tcaptype, typename flowtype>
void Graph<captype, tcaptype, flowtype>::process_source_orphan(node *i)
{
node *j;
arc *a0, *a0_min = NULL, *a;
int d, d_min = INFINITE_D;
/* trying to find a new parent */
for (a0 = i->first; a0; a0 = a0->next)
if (a0->sister->r_cap)
{
j = a0->head;
if (!j->is_sink && (a = j->parent))
{
/* checking the origin of j */
d = 0;
while (1)
{
if (j->TS == TIME)
{
d += j->DIST;
break;
}
a = j->parent;
d++;
if (a == TERMINAL)
{
j->TS = TIME;
j->DIST = 1;
break;
}
if (a == ORPHAN) { d = INFINITE_D; break; }
j = a->head;
}
if (d < INFINITE_D) /* j originates from the source - done */
{
if (d < d_min)
{
a0_min = a0;
d_min = d;
}
/* set marks along the path */
for (j = a0->head; j->TS != TIME; j = j->parent->head)
{
j->TS = TIME;
j->DIST = d--;
}
}
}
}
if (i->parent = a0_min)
{
i->TS = TIME;
i->DIST = d_min + 1;
}
else
{
/* no parent is found */
add_to_changed_list(i);
/* process neighbors */
for (a0 = i->first; a0; a0 = a0->next)
{
j = a0->head;
if (!j->is_sink && (a = j->parent))
{
if (a0->sister->r_cap) set_active(j);
if (a != TERMINAL && a != ORPHAN && a->head == i)
{
set_orphan_rear(j); // add j to the end of the adoption list
}
}
}
}
}
template <typename captype, typename tcaptype, typename flowtype>
void Graph<captype, tcaptype, flowtype>::process_sink_orphan(node *i)
{
node *j;
arc *a0, *a0_min = NULL, *a;
int d, d_min = INFINITE_D;
/* trying to find a new parent */
for (a0 = i->first; a0; a0 = a0->next)
if (a0->r_cap)
{
j = a0->head;
if (j->is_sink && (a = j->parent))
{
/* checking the origin of j */
d = 0;
while (1)
{
if (j->TS == TIME)
{
d += j->DIST;
break;
}
a = j->parent;
d++;
if (a == TERMINAL)
{
j->TS = TIME;
j->DIST = 1;
break;
}
if (a == ORPHAN) { d = INFINITE_D; break; }
j = a->head;
}
if (d < INFINITE_D) /* j originates from the sink - done */
{
if (d < d_min)
{
a0_min = a0;
d_min = d;
}
/* set marks along the path */
for (j = a0->head; j->TS != TIME; j = j->parent->head)
{
j->TS = TIME;
j->DIST = d--;
}
}
}
}
if (i->parent = a0_min)
{
i->TS = TIME;
i->DIST = d_min + 1;
}
else
{
/* no parent is found */
add_to_changed_list(i);
/* process neighbors */
for (a0 = i->first; a0; a0 = a0->next)
{
j = a0->head;
if (j->is_sink && (a = j->parent))
{
if (a0->r_cap) set_active(j);
if (a != TERMINAL && a != ORPHAN && a->head == i)
{
set_orphan_rear(j); // add j to the end of the adoption list
}
}
}
}
}
/***********************************************************************/
template <typename captype, typename tcaptype, typename flowtype>
flowtype Graph<captype, tcaptype, flowtype>::maxflow(bool reuse_trees, Block<node_id>* _changed_list)
{
node *i, *j, *current_node = NULL;
arc *a;
nodeptr *np, *np_next;
if (!nodeptr_block)
{
nodeptr_block = new DBlock<nodeptr>(NODEPTR_BLOCK_SIZE, error_function);
}
changed_list = _changed_list;
if (maxflow_iteration == 0 && reuse_trees) { if (error_function) (*error_function)("reuse_trees cannot be used in the first call to maxflow()!"); exit(1); }
if (changed_list && !reuse_trees) { if (error_function) (*error_function)("changed_list cannot be used without reuse_trees!"); exit(1); }
if (reuse_trees) maxflow_reuse_trees_init();
else maxflow_init();
// main loop
while (1)
{
// test_consistency(current_node);
if ((i = current_node))
{
i->next = NULL; /* remove active flag */
if (!i->parent) i = NULL;
}
if (!i)
{
if (!(i = next_active())) break;
}
/* growth */
if (!i->is_sink)
{
/* grow source tree */
for (a = i->first; a; a = a->next)
if (a->r_cap)
{
j = a->head;
if (!j->parent)
{
j->is_sink = 0;
j->parent = a->sister;
j->TS = i->TS;
j->DIST = i->DIST + 1;
set_active(j);
add_to_changed_list(j);
}
else if (j->is_sink) break;
else if (j->TS <= i->TS &&
j->DIST > i->DIST)
{
/* heuristic - trying to make the distance from j to the source shorter */
j->parent = a->sister;
j->TS = i->TS;
j->DIST = i->DIST + 1;
}
}
}
else
{
/* grow sink tree */
for (a = i->first; a; a = a->next)
if (a->sister->r_cap)
{
j = a->head;
if (!j->parent)
{
j->is_sink = 1;
j->parent = a->sister;
j->TS = i->TS;
j->DIST = i->DIST + 1;
set_active(j);
add_to_changed_list(j);
}
else if (!j->is_sink) { a = a->sister; break; }
else if (j->TS <= i->TS &&
j->DIST > i->DIST)
{
/* heuristic - trying to make the distance from j to the sink shorter */
j->parent = a->sister;
j->TS = i->TS;
j->DIST = i->DIST + 1;
}
}
}
TIME++;
if (a)
{
i->next = i; /* set active flag */
current_node = i;
/* augmentation */
augment(a);
/* augmentation end */
/* adoption */
while ((np = orphan_first))
{
np_next = np->next;
np->next = NULL;
while ((np = orphan_first))
{
orphan_first = np->next;
i = np->ptr;
nodeptr_block->Delete(np);
if (!orphan_first) orphan_last = NULL;
if (i->is_sink) process_sink_orphan(i);
else process_source_orphan(i);
}
orphan_first = np_next;
}
/* adoption end */
}
else current_node = NULL;
}
// test_consistency();
if (!reuse_trees || (maxflow_iteration % 64) == 0)
{
delete nodeptr_block;
nodeptr_block = NULL;
}
maxflow_iteration++;
return flow;
}
/***********************************************************************/
template <typename captype, typename tcaptype, typename flowtype>
void Graph<captype, tcaptype, flowtype>::test_consistency(node* current_node)
{
node *i;
arc *a;
int r;
int num1 = 0, num2 = 0;
// test whether all nodes i with i->next!=NULL are indeed in the queue
for (i = nodes; i < node_last; i++)
{
if (i->next || i == current_node) num1++;
}
for (r = 0; r < 3; r++)
{
i = (r == 2) ? current_node : queue_first[r];
if (i)
for (; ; i = i->next)
{
num2++;
if (i->next == i)
{
if (r < 2) assert(i == queue_last[r]);
else assert(i == current_node);
break;
}
}
}
assert(num1 == num2);
for (i = nodes; i < node_last; i++)
{
// test whether all edges in seach trees are non-saturated
if (i->parent == NULL) {}
else if (i->parent == ORPHAN) {}
else if (i->parent == TERMINAL)
{
if (!i->is_sink) assert(i->tr_cap > 0);
else assert(i->tr_cap < 0);
}
else
{
if (!i->is_sink) assert(i->parent->sister->r_cap > 0);
else assert(i->parent->r_cap > 0);
}
// test whether passive nodes in search trees have neighbors in
// a different tree through non-saturated edges
if (i->parent && !i->next)
{
if (!i->is_sink)
{
assert(i->tr_cap >= 0);
for (a = i->first; a; a = a->next)
{
if (a->r_cap > 0) assert(a->head->parent && !a->head->is_sink);
}
}
else
{
assert(i->tr_cap <= 0);
for (a = i->first; a; a = a->next)
{
if (a->sister->r_cap > 0) assert(a->head->parent && a->head->is_sink);
}
}
}
// test marking invariants
if (i->parent && i->parent != ORPHAN && i->parent != TERMINAL)
{
assert(i->TS <= i->parent->head->TS);
if (i->TS == i->parent->head->TS) assert(i->DIST > i->parent->head->DIST);
}
}
}
}
#endif | {'repo_name': 'zuoqing1988/ZQlib', 'stars': '104', 'repo_language': 'C++', 'file_name': 'SampleCameraCalibrationMono.cpp', 'mime_type': 'text/x-c++', 'hash': -3546890123076754344, 'source_dataset': 'data'} |
'use strict';
var o = { 1: 1, 2: 2, 3: 3 };
module.exports = function (t, a) {
var o2 = {}, i = 0;
t(o, function (value, name) {
o2[name] = value;
return false;
});
a(JSON.stringify(o2), JSON.stringify(o), "Iterates");
a(t(o, function () {
++i;
return true;
}), true, "Succeeds");
a(i, 1, "Stops iteration after condition is met");
a(t(o, function () {
return false;
}), false, "Fails");
};
| {'repo_name': 'japgolly/scalacss', 'stars': '286', 'repo_language': 'Scala', 'file_name': 'index.md', 'mime_type': 'text/plain', 'hash': -1796247362817244777, 'source_dataset': 'data'} |
<?xml version="1.0" encoding="UTF-8"?>
<language>
<name><![CDATA[lietuvių kalba (Lithuanian)]]></name>
<locale>lt-LT</locale>
<language_code>lt-lt</language_code>
<date_format_lite>d/m/Y</date_format_lite>
<date_format_full>d/m/Y H:i:s</date_format_full>
<is_rtl>false</is_rtl>
</language>
| {'repo_name': 'PrestaShop/PrestaShop', 'stars': '5017', 'repo_language': 'PHP', 'file_name': 'controllerHttp.php', 'mime_type': 'text/x-php', 'hash': 1022104864418066649, 'source_dataset': 'data'} |
import {ACTION_TYPES} from './actions';
const initialState = {
isFetching: false,
error: null,
nextPageUrl: undefined,
results: [],
};
export default function userReducer(state = initialState, action = {}) {
switch (action.type) {
case ACTION_TYPES.USER_REQUEST:
return {...state, isFetching: true, error: null};
case ACTION_TYPES.USER_SUCCESS:
return {...state, isFetching: false, error: null};
case ACTION_TYPES.USER_FAILURE:
return {...state, isFetching: false, error: action.error};
default:
return state;
}
}
| {'repo_name': 'iZaL/real-estate-app-ui', 'stars': '122', 'repo_language': 'JavaScript', 'file_name': 'setup.js', 'mime_type': 'text/x-c++', 'hash': 8236778250150043759, 'source_dataset': 'data'} |
package com.github.eclipsecolortheme.mapper;
import org.eclipse.core.runtime.preferences.IEclipsePreferences;
import com.github.eclipsecolortheme.ColorThemeMapping;
import com.github.eclipsecolortheme.ColorThemeSetting;
public class StatetEditorMapper extends GenericMapper {
private class Mapping extends ColorThemeMapping {
public Mapping(String pluginKey, String themeKey) {
super(pluginKey, themeKey);
}
@Override
public void putPreferences(IEclipsePreferences preferences,
ColorThemeSetting setting) {
preferences.put(pluginKey, setting.getColor().asRGB());
if (setting.isBoldEnabled() != null)
preferences.putBoolean(pluginKey.replaceAll(".color", ".bold"), setting.isBoldEnabled());
if (setting.isItalicEnabled() != null)
preferences.putBoolean(pluginKey.replaceAll(".color", ".italic"), setting.isItalicEnabled());
if (setting.isStrikethroughEnabled() != null)
preferences.putBoolean(pluginKey.replaceAll(".color", ".strikethrough"), setting.isStrikethroughEnabled());
if (setting.isUnderlineEnabled() != null)
preferences.putBoolean(pluginKey.replaceAll(".color", ".underline"), setting.isUnderlineEnabled());
}
}
@Override
protected ColorThemeMapping createMapping(String pluginKey, String themeKey) {
return new Mapping(pluginKey, themeKey);
}
}
| {'repo_name': 'eclipse-color-theme/eclipse-color-theme', 'stars': '847', 'repo_language': 'Java', 'file_name': 'build.properties', 'mime_type': 'text/plain', 'hash': 2794074543950574420, 'source_dataset': 'data'} |
// Modified and added to the TPIE distribution in April 2003 by
// Octavian Procopiuc <[email protected]>
/* getopts.cpp - Command line argument parser
*
* Whom: Steve Mertz <[email protected]>
* Date: 20010111
* Why: Because I couldn't find one that I liked. So I wrote this one.
*
*/
/*
* Copyright (c) 2001, 2002, Steve Mertz <[email protected]>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of Dragon Ware nor the names of its contributors may be
* used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "getopts.h"
#ifdef __cplusplus
extern "C" {
#endif
int option_index = 1;
/* int getopts_usage()
*
* Returns: 1 - Successful
*/
int getopts_usage(char *progName, struct options opts[])
{
int count;
char *cmd;
printf("Usage: %s [options]\n\n", progName);
printf(" --help, -h\t\t\tDisplays this information\n");
for (count = 0; opts[count].description; count++)
{
if (opts[count].name && opts[count].shortName)
{
cmd = (char*) calloc(1, strlen(opts[count].name) + strlen(opts[count].shortName) + 15);
if (opts[count].args)
{
sprintf(cmd, "--%s, -%s <args>\t\t", opts[count].name, opts[count].shortName);
}
else
{
sprintf(cmd, "--%s, -%s\t\t\t", opts[count].name, opts[count].shortName);
}
}
else if (opts[count].name)
{
cmd = (char*) calloc(1, strlen(opts[count].name) + 15);
if (opts[count].args)
{
sprintf(cmd, "--%s <args>\t\t\t", opts[count].name);
}
else
{
sprintf(cmd, "--%s\t\t\t", opts[count].name);
}
}
else if (opts[count].shortName)
{
cmd = (char*) calloc(1, strlen(opts[count].shortName) + 15);
if (opts[count].args)
{
sprintf(cmd, "\t\t-%s <args>\t\t", opts[count].shortName);
}
else
{
sprintf(cmd, "\t\t-%s\t\t\t", opts[count].shortName);
}
}
printf(" %s%s\n", cmd, opts[count].description);
free(cmd);
}
return 1;
}
/* int getopts()
*
* Returns: -1 - Couldn't allocate memory. Please handle me.
* 0 - No arguements to parse
* # - The number in the struct for the matched arg.
*
*/
int getopts(int argc, char **argv, struct options opts[], char **args)
{
int count1, sizeOfArgs;
if (argc == 1 || option_index == argc)
return 0;
/* Search for '-h' or '--help' first. Then we can just exit */
for (count1 = 1; count1 < argc; count1++)
{
if (!strcmp(argv[count1], "-h") || !strcmp(argv[count1], "--help"))
{
useage:
getopts_usage(argv[0], opts);
exit(0);
}
}
/* End of -h --help section */
*args = NULL;
if (option_index <= argc)
{
for (count1 = 0; opts[count1].description; count1++)
{
if ((opts[count1].name && !strcmp(opts[count1].name,
(argv[option_index]+2))) ||
(opts[count1].shortName && !strcmp(opts[count1].shortName,
(argv[option_index]+1))))
{
if (opts[count1].args)
{
option_index++;
if (option_index >= argc)
goto useage;
/* This grossness that follows is to supporte having a '-' in the
argument. It's all squished together like this because I use
an 80 char wide screen for my coding. If you don't like it, help
yourself to fixing it so you do. */
if (*argv[option_index] == '-')
{
int optionSeeker;
for (optionSeeker = 0; opts[optionSeeker].description;
optionSeeker++)
{
if ((opts[optionSeeker].name &&
!strcmp(opts[optionSeeker].name,
(argv[option_index]+2))) ||
(opts[optionSeeker].shortName &&
!strcmp(opts[optionSeeker].shortName,
(argv[option_index]+1))))
{
goto useage;
}
}
/* End of gross hack for supporting '-' in arguments. */
}
sizeOfArgs = strlen(argv[option_index]);
if ((*args = (char*) calloc(1, sizeOfArgs+1)) == NULL)
return -1;
strncpy(*args, argv[option_index], sizeOfArgs);
}
option_index++;
return opts[count1].number;
}
}
}
return 0;
}
#ifdef __cplusplus
}
#endif
| {'repo_name': 'cliqz-oss/keyvi', 'stars': '165', 'repo_language': 'C++', 'file_name': 'Building keyvi dictionaries with python.md', 'mime_type': 'text/plain', 'hash': 4503536577811668698, 'source_dataset': 'data'} |
package com.cxytiandi.elasticjob.parser;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.ManagedList;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.env.Environment;
import org.springframework.util.StringUtils;
import com.cxytiandi.elasticjob.annotation.ElasticJobConf;
import com.cxytiandi.elasticjob.base.JobAttributeTag;
import com.cxytiandi.elasticjob.dynamic.service.JobService;
import com.dangdang.ddframe.job.config.JobCoreConfiguration;
import com.dangdang.ddframe.job.config.JobTypeConfiguration;
import com.dangdang.ddframe.job.config.dataflow.DataflowJobConfiguration;
import com.dangdang.ddframe.job.config.script.ScriptJobConfiguration;
import com.dangdang.ddframe.job.config.simple.SimpleJobConfiguration;
import com.dangdang.ddframe.job.event.rdb.JobEventRdbConfiguration;
import com.dangdang.ddframe.job.executor.handler.JobProperties.JobPropertiesEnum;
import com.dangdang.ddframe.job.lite.config.LiteJobConfiguration;
import com.dangdang.ddframe.job.lite.spring.api.SpringJobScheduler;
import com.dangdang.ddframe.job.reg.zookeeper.ZookeeperRegistryCenter;
/**
* Job解析类
*
* <p>从注解中解析任务信息初始化<p>
*
* @author yinjihuan
*
* @about http://cxytiandi.com/about
*/
public class JobConfParser implements ApplicationContextAware {
private Logger logger = LoggerFactory.getLogger(JobConfParser.class);
@Autowired
private ZookeeperRegistryCenter zookeeperRegistryCenter;
private String prefix = "elastic.job.";
private Environment environment;
@Autowired(required=false)
private JobService jobService;
private List<String> jobTypeNameList = Arrays.asList("SimpleJob", "DataflowJob", "ScriptJob");
public void setApplicationContext(ApplicationContext ctx) throws BeansException {
environment = ctx.getEnvironment();
Map<String, Object> beanMap = ctx.getBeansWithAnnotation(ElasticJobConf.class);
for (Object confBean : beanMap.values()) {
Class<?> clz = confBean.getClass();
// 解决CGLIB代理问题
String jobTypeName = clz.getInterfaces()[0].getSimpleName();
if (!jobTypeNameList.contains(jobTypeName)) {
jobTypeName = clz.getSuperclass().getInterfaces()[0].getSimpleName();
clz = clz.getSuperclass();
}
ElasticJobConf conf = AnnotationUtils.findAnnotation(clz, ElasticJobConf.class);
String jobClass = clz.getName();
String jobName = conf.name();
String cron = getEnvironmentStringValue(jobName, JobAttributeTag.CRON, conf.cron());
String shardingItemParameters = getEnvironmentStringValue(jobName, JobAttributeTag.SHARDING_ITEM_PARAMETERS, conf.shardingItemParameters());
String description = getEnvironmentStringValue(jobName, JobAttributeTag.DESCRIPTION, conf.description());
String jobParameter = getEnvironmentStringValue(jobName, JobAttributeTag.JOB_PARAMETER, conf.jobParameter());
String jobExceptionHandler = getEnvironmentStringValue(jobName, JobAttributeTag.JOB_EXCEPTION_HANDLER, conf.jobExceptionHandler());
String executorServiceHandler = getEnvironmentStringValue(jobName, JobAttributeTag.EXECUTOR_SERVICE_HANDLER, conf.executorServiceHandler());
String jobShardingStrategyClass = getEnvironmentStringValue(jobName, JobAttributeTag.JOB_SHARDING_STRATEGY_CLASS, conf.jobShardingStrategyClass());
String eventTraceRdbDataSource = getEnvironmentStringValue(jobName, JobAttributeTag.EVENT_TRACE_RDB_DATA_SOURCE, conf.eventTraceRdbDataSource());
String scriptCommandLine = getEnvironmentStringValue(jobName, JobAttributeTag.SCRIPT_COMMAND_LINE, conf.scriptCommandLine());
boolean failover = getEnvironmentBooleanValue(jobName, JobAttributeTag.FAILOVER, conf.failover());
boolean misfire = getEnvironmentBooleanValue(jobName, JobAttributeTag.MISFIRE, conf.misfire());
boolean overwrite = getEnvironmentBooleanValue(jobName, JobAttributeTag.OVERWRITE, conf.overwrite());
boolean disabled = getEnvironmentBooleanValue(jobName, JobAttributeTag.DISABLED, conf.disabled());
boolean monitorExecution = getEnvironmentBooleanValue(jobName, JobAttributeTag.MONITOR_EXECUTION, conf.monitorExecution());
boolean streamingProcess = getEnvironmentBooleanValue(jobName, JobAttributeTag.STREAMING_PROCESS, conf.streamingProcess());
int shardingTotalCount = getEnvironmentIntValue(jobName, JobAttributeTag.SHARDING_TOTAL_COUNT, conf.shardingTotalCount());
int monitorPort = getEnvironmentIntValue(jobName, JobAttributeTag.MONITOR_PORT, conf.monitorPort());
int maxTimeDiffSeconds = getEnvironmentIntValue(jobName, JobAttributeTag.MAX_TIME_DIFF_SECONDS, conf.maxTimeDiffSeconds());
int reconcileIntervalMinutes = getEnvironmentIntValue(jobName, JobAttributeTag.RECONCILE_INTERVAL_MINUTES, conf.reconcileIntervalMinutes());
// 核心配置
JobCoreConfiguration coreConfig =
JobCoreConfiguration.newBuilder(jobName, cron, shardingTotalCount)
.shardingItemParameters(shardingItemParameters)
.description(description)
.failover(failover)
.jobParameter(jobParameter)
.misfire(misfire)
.jobProperties(JobPropertiesEnum.JOB_EXCEPTION_HANDLER.getKey(), jobExceptionHandler)
.jobProperties(JobPropertiesEnum.EXECUTOR_SERVICE_HANDLER.getKey(), executorServiceHandler)
.build();
// 不同类型的任务配置处理
LiteJobConfiguration jobConfig = null;
JobTypeConfiguration typeConfig = null;
if (jobTypeName.equals("SimpleJob")) {
typeConfig = new SimpleJobConfiguration(coreConfig, jobClass);
}
if (jobTypeName.equals("DataflowJob")) {
typeConfig = new DataflowJobConfiguration(coreConfig, jobClass, streamingProcess);
}
if (jobTypeName.equals("ScriptJob")) {
typeConfig = new ScriptJobConfiguration(coreConfig, scriptCommandLine);
}
jobConfig = LiteJobConfiguration.newBuilder(typeConfig)
.overwrite(overwrite)
.disabled(disabled)
.monitorPort(monitorPort)
.monitorExecution(monitorExecution)
.maxTimeDiffSeconds(maxTimeDiffSeconds)
.jobShardingStrategyClass(jobShardingStrategyClass)
.reconcileIntervalMinutes(reconcileIntervalMinutes)
.build();
List<BeanDefinition> elasticJobListeners = getTargetElasticJobListeners(conf);
// 构建SpringJobScheduler对象来初始化任务
BeanDefinitionBuilder factory = BeanDefinitionBuilder.rootBeanDefinition(SpringJobScheduler.class);
factory.setScope(BeanDefinition.SCOPE_PROTOTYPE);
if ("ScriptJob".equals(jobTypeName)) {
factory.addConstructorArgValue(null);
} else {
factory.addConstructorArgValue(confBean);
}
factory.addConstructorArgValue(zookeeperRegistryCenter);
factory.addConstructorArgValue(jobConfig);
// 任务执行日志数据源,以名称获取
if (StringUtils.hasText(eventTraceRdbDataSource)) {
BeanDefinitionBuilder rdbFactory = BeanDefinitionBuilder.rootBeanDefinition(JobEventRdbConfiguration.class);
rdbFactory.addConstructorArgReference(eventTraceRdbDataSource);
factory.addConstructorArgValue(rdbFactory.getBeanDefinition());
}
factory.addConstructorArgValue(elasticJobListeners);
DefaultListableBeanFactory defaultListableBeanFactory = (DefaultListableBeanFactory)ctx.getAutowireCapableBeanFactory();
defaultListableBeanFactory.registerBeanDefinition(jobName+"SpringJobScheduler", factory.getBeanDefinition());
SpringJobScheduler springJobScheduler = (SpringJobScheduler) ctx.getBean(jobName+"SpringJobScheduler");
springJobScheduler.init();
logger.info("【" + jobName + "】\t" + jobClass + "\tinit success");
}
//开启任务监听,当有任务添加时,监听zk中的数据增加,自动在其他节点也初始化该任务
if (jobService != null) {
jobService.monitorJobRegister();
}
}
private List<BeanDefinition> getTargetElasticJobListeners(ElasticJobConf conf) {
List<BeanDefinition> result = new ManagedList<BeanDefinition>(2);
String listeners = getEnvironmentStringValue(conf.name(), JobAttributeTag.LISTENER, conf.listener());
if (StringUtils.hasText(listeners)) {
BeanDefinitionBuilder factory = BeanDefinitionBuilder.rootBeanDefinition(listeners);
factory.setScope(BeanDefinition.SCOPE_PROTOTYPE);
result.add(factory.getBeanDefinition());
}
String distributedListeners = getEnvironmentStringValue(conf.name(), JobAttributeTag.DISTRIBUTED_LISTENER, conf.distributedListener());
long startedTimeoutMilliseconds = getEnvironmentLongValue(conf.name(), JobAttributeTag.DISTRIBUTED_LISTENER_STARTED_TIMEOUT_MILLISECONDS, conf.startedTimeoutMilliseconds());
long completedTimeoutMilliseconds = getEnvironmentLongValue(conf.name(), JobAttributeTag.DISTRIBUTED_LISTENER_COMPLETED_TIMEOUT_MILLISECONDS, conf.completedTimeoutMilliseconds());
if (StringUtils.hasText(distributedListeners)) {
BeanDefinitionBuilder factory = BeanDefinitionBuilder.rootBeanDefinition(distributedListeners);
factory.setScope(BeanDefinition.SCOPE_PROTOTYPE);
factory.addConstructorArgValue(startedTimeoutMilliseconds);
factory.addConstructorArgValue(completedTimeoutMilliseconds);
result.add(factory.getBeanDefinition());
}
return result;
}
/**
* 获取配置中的任务属性值,environment没有就用注解中的值
* @param jobName 任务名称
* @param fieldName 属性名称
* @param defaultValue 默认值
* @return
*/
private String getEnvironmentStringValue(String jobName, String fieldName, String defaultValue) {
String key = prefix + jobName + "." + fieldName;
String value = environment.getProperty(key);
if (StringUtils.hasText(value)) {
return value;
}
return defaultValue;
}
private int getEnvironmentIntValue(String jobName, String fieldName, int defaultValue) {
String key = prefix + jobName + "." + fieldName;
String value = environment.getProperty(key);
if (StringUtils.hasText(value)) {
return Integer.valueOf(value);
}
return defaultValue;
}
private long getEnvironmentLongValue(String jobName, String fieldName, long defaultValue) {
String key = prefix + jobName + "." + fieldName;
String value = environment.getProperty(key);
if (StringUtils.hasText(value)) {
return Long.valueOf(value);
}
return defaultValue;
}
private boolean getEnvironmentBooleanValue(String jobName, String fieldName, boolean defaultValue) {
String key = prefix + jobName + "." + fieldName;
String value = environment.getProperty(key);
if (StringUtils.hasText(value)) {
return Boolean.valueOf(value);
}
return defaultValue;
}
}
| {'repo_name': 'yinjihuan/elastic-job-spring-boot-starter', 'stars': '339', 'repo_language': 'Java', 'file_name': 'JobAttributeTag.java', 'mime_type': 'text/plain', 'hash': 4935101989502277869, 'source_dataset': 'data'} |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import json
import urllib2
import urllib
WITNESS_URL = "http://127.0.0.1:28090"
POST_DATA = '{"jsonrpc": "2.0", "method": "call", "params": [0, "get_witness_participation_rate", []], "id": 1}'
WECHAT_NOTIFY_URL = "http://172.19.19.49:8091/notify/wechat/send?message=%s&agent=GXCHAIN"
NO_RESULT_MSG = "见证人监控程序,无法获取参与率, 错误信息:"
WARNING_MSG = "见证人参与率预期为100%,当前参与率:"
def download(url, data = None):
opener = urllib2.build_opener()
request = urllib2.Request(url, data)
response = opener.open(request, timeout=60)
return response.read()
def main():
# get error_msg
error_msg = ""
try:
res = download(WITNESS_URL, POST_DATA)
js = json.loads(res)
participation_rate = js['result']
if 10000 <> participation_rate:
error_msg = "%s %f %%" % (WARNING_MSG, float(participation_rate)/100)
except Exception as e:
error_msg = NO_RESULT_MSG + str(e)
# send error_msg
if len(error_msg) > 0:
notify_url = WECHAT_NOTIFY_URL % (urllib.quote(error_msg))
#print notify_url
download(notify_url)
if __name__ == "__main__":
main()
| {'repo_name': 'gxchain/gxb-core', 'stars': '223', 'repo_language': 'WebAssembly', 'file_name': 'CMakeLists.txt', 'mime_type': 'text/plain', 'hash': -7421662159820525924, 'source_dataset': 'data'} |
#!/usr/bin/env python3
"""
Copyright 2020 The Magma Authors.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree.
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import argparse
import grpc
from magma.common.rpc_utils import cloud_grpc_wrapper
from orc8r.protos.common_pb2 import Void
from feg.protos.mock_core_pb2_grpc import MockCoreConfiguratorStub
@cloud_grpc_wrapper
def send_reset(client, args):
print("Sending reset")
try:
client.Reset(Void())
except grpc.RpcError as e:
print("gRPC failed with %s: %s" % (e.code(), e.details()))
def create_parser():
"""
Creates the argparse parser with all the arguments.
"""
parser = argparse.ArgumentParser(
description='Management CLI for mock PCRF',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
# Add subcommands
subparsers = parser.add_subparsers(title='subcommands', dest='cmd')
# Reset
alert_ack_parser = subparsers.add_parser(
'reset', help='Send Reset to mock PCRF hosted in FeG')
alert_ack_parser.set_defaults(func=send_reset)
return parser
def main():
parser = create_parser()
# Parse the args
args = parser.parse_args()
if not args.cmd:
parser.print_usage()
exit(1)
# Execute the subcommand function
args.func(args, MockCoreConfiguratorStub, 'pcrf')
if __name__ == "__main__":
main()
| {'repo_name': 'facebookincubator/magma', 'stars': '502', 'repo_language': 'Go', 'file_name': '0008-ovs-datapath-enable-kernel-5.6.patch', 'mime_type': 'text/x-diff', 'hash': -5417632233278398942, 'source_dataset': 'data'} |
//
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard.
//
#import <CommunicationsSetupUI/CNFRegAuthorizedAccountWebViewController.h>
@class IMAccount;
@interface CNFRegSecureAccountWebViewController : CNFRegAuthorizedAccountWebViewController
{
IMAccount *_account;
BOOL _triedGettingNewCredentials;
BOOL _gotNewCredential;
unsigned int _signinFailureCount;
}
@property(retain, nonatomic) IMAccount *account; // @synthesize account=_account;
- (void)_setupAccountHandlers;
- (id)authTokenHeaderValue;
- (id)authIdHeaderValue;
- (void)_showForgotPasswordAlert;
- (void)_incrementSigninFailureCount;
- (void)_resetSigninFailureCount;
- (void)_launchForgotPasswordUrl;
- (void)_showRequestPasswordAlert;
- (void)_showBadPasswordAlert;
- (void)_showRegistrationFailureWithError:(id)arg1;
- (void)_handleTimeout;
- (void)doHandoffWithStatus:(int)arg1 appleID:(id)arg2 authID:(id)arg3 authToken:(id)arg4;
- (void)viewWillDisappear:(BOOL)arg1;
- (void)viewDidAppear:(BOOL)arg1;
- (void)dealloc;
- (id)initWithRegController:(id)arg1 account:(id)arg2;
@end
| {'repo_name': 'MP0w/iOS-Headers', 'stars': '405', 'repo_language': 'Objective-C', 'file_name': 'IMAVChat-IMAVChatAudioAdditions.h', 'mime_type': 'text/x-objective-c', 'hash': -1651543631709905891, 'source_dataset': 'data'} |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="AccountDao">
<resultMap id="AccountMap" type="AccountDO">
<id property="id" column="id" />
<result property="username" column="username" />
<result property="password" column="password" />
<result property="role" column="role" />
<result property="status" column="status" />
<result property="gmtCreate" column="gmt_create" />
<result property="gmtModify" column="gmt_modify" />
</resultMap>
<insert id="insert" parameterType="com.xiaojukeji.kafka.manager.common.entity.po.AccountDO">
<![CDATA[
REPLACE account
(username, password, role, status)
VALUES
(#{username}, #{password}, #{role}, #{status})
]]>
</insert>
<insert id="insertOnPG" parameterType="com.xiaojukeji.kafka.manager.common.entity.po.AccountDO">
<![CDATA[
insert into account
(username, password, role, status)
values
(#{username}, #{password}, #{role}, #{status})
on conflict (username) do update set password = excluded.password,
role = excluded.role,
status = excluded.status
]]>
</insert>
<delete id="deleteByName" parameterType="java.lang.String">
DELETE FROM account WHERE username = #{username}
</delete>
<select id="getByName" parameterType="java.lang.String" resultMap="AccountMap">
<![CDATA[
SELECT * FROM account WHERE username = #{username} AND status=0
]]>
</select>
<select id="list" resultMap="AccountMap">
<![CDATA[
SELECT * FROM account WHERE status = 0
]]>
</select>
</mapper> | {'repo_name': 'didi/kafka-manager', 'stars': '193', 'repo_language': 'Java', 'file_name': 'create_mysql_table.sql', 'mime_type': 'text/plain', 'hash': -8504975406507662978, 'source_dataset': 'data'} |
# Node.js
[![Gitter](https://badges.gitter.im/Join Chat.svg)](https://gitter.im/nodejs/node?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) [![CII Best Practices](https://bestpractices.coreinfrastructure.org/projects/29/badge)](https://bestpractices.coreinfrastructure.org/projects/29)
Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine. Node.js
uses an event-driven, non-blocking I/O model that makes it lightweight and
efficient. The Node.js package ecosystem, npm, is the largest ecosystem of open
source libraries in the world.
The Node.js project is supported by the
[Node.js Foundation](https://nodejs.org/en/foundation/). Contributions,
policies, and releases are managed under an
[open governance model](./GOVERNANCE.md). We are also bound by a
[Code of Conduct](./CODE_OF_CONDUCT.md).
If you need help using or installing Node.js, please use the
[nodejs/help](https://github.com/nodejs/help) issue tracker.
## Resources for Newcomers
### Official Resources
* [Website][]
* [Node.js Help][]
* [Contributing to the project][]
* IRC (node core development): [#node-dev on chat.freenode.net][]
### Unofficial Resources
* IRC (general questions): [#node.js on chat.freenode.net][]. Please see
<http://nodeirc.info/> for more information regarding the `#node.js` IRC
channel.
_Please note that unofficial resources are neither managed by (nor necessarily
endorsed by) the Node.js TSC/CTC. Specifically, such resources are not
currently covered by the [Node.js Moderation Policy][] and the selection and
actions of resource operators/moderators are not subject to TSC/CTC oversight._
## Release Types
The Node.js project maintains multiple types of releases:
* **Current**: Released from active development branches of this repository,
versioned by [SemVer](http://semver.org/) and signed by a member of the
[Release Team](#release-team).
Code for Current releases is organized in this repository by major version
number. For example: [v4.x](https://github.com/nodejs/node/tree/v4.x).
The major version number of Current releases will increment every 6 months
allowing for breaking changes to be introduced. This happens in April and
October every year. Current release lines beginning in October each year have
a maximum support life of 8 months. Current release lines beginning in April
each year will convert to LTS (see below) after 6 months and receive further
support for 30 months.
* **LTS**: Releases that receive Long-term Support, with a focus on stability
and security. Every second Current release line (major version) will become an
LTS line and receive 18 months of _Active LTS_ support and a further 12
months of _Maintenance_. LTS release lines are given alphabetically
ordered codenames, beginning with v4 Argon. LTS releases are less frequent
and will attempt to maintain consistent major and minor version numbers,
only incrementing patch version numbers. There are no breaking changes or
feature additions, except in some special circumstances. More information
can be found in the [LTS README](https://github.com/nodejs/LTS/).
* **Nightly**: Versions of code in this repository on the current Current
branch, automatically built every 24-hours where changes exist. Use with
caution.
## Download
Binaries, installers, and source tarballs are available at
<https://nodejs.org>.
**Current** and **LTS** releases are available at
<https://nodejs.org/download/release/>, listed under their version strings.
The [latest](https://nodejs.org/download/release/latest/) directory is an
alias for the latest Current release. The latest LTS release from an LTS
line is available in the form: latest-_codename_. For example:
<https://nodejs.org/download/release/latest-argon>
**Nightly** builds are available at
<https://nodejs.org/download/nightly/>, listed under their version
string which includes their date (in UTC time) and the commit SHA at
the HEAD of the release.
**API documentation** is available in each release and nightly
directory under _docs_. <https://nodejs.org/api/> points to the API
documentation of the latest stable version.
### Verifying Binaries
Current, LTS and Nightly download directories all contain a _SHASUM256.txt_
file that lists the SHA checksums for each file available for
download.
The _SHASUM256.txt_ can be downloaded using curl.
```console
$ curl -O https://nodejs.org/dist/vx.y.z/SHASUMS256.txt
```
To check that a downloaded file matches the checksum, run
it through `sha256sum` with a command such as:
```console
$ grep node-vx.y.z.tar.gz SHASUMS256.txt | sha256sum -c -
```
_(Where "node-vx.y.z.tar.gz" is the name of the file you have
downloaded)_
Additionally, Current and LTS releases (not Nightlies) have GPG signed
copies of SHASUM256.txt files available as SHASUM256.txt.asc. You can use
`gpg` to verify that the file has not been tampered with.
To verify a SHASUM256.txt.asc, you will first need to import all of
the GPG keys of individuals authorized to create releases. They are
listed at the bottom of this README under [Release Team](#release-team).
Use a command such as this to import the keys:
```console
$ gpg --keyserver pool.sks-keyservers.net --recv-keys DD8F2338BAE7501E3DD5AC78C273792F7D83545D
```
_(See the bottom of this README for a full script to import active
release keys)_
You can then use `gpg --verify SHASUMS256.txt.asc` to verify that the
file has been signed by an authorized member of the Node.js team.
Once verified, use the SHASUMS256.txt.asc file to get the checksum for
the binary verification command above.
## Building Node.js
See [BUILDING.md](BUILDING.md) for instructions on how to build
Node.js from source.
## Security
All security bugs in Node.js are taken seriously and should be reported by
emailing [email protected]. This will be delivered to a subset of the project
team who handle security issues. Please don't disclose security bugs
publicly until they have been handled by the security team.
Your email will be acknowledged within 24 hours, and you’ll receive a more
detailed response to your email within 48 hours indicating the next steps in
handling your report.
## Current Project Team Members
The Node.js project team comprises a group of core collaborators and a sub-group
that forms the _Core Technical Committee_ (CTC) which governs the project. For
more information about the governance of the Node.js project, see
[GOVERNANCE.md](./GOVERNANCE.md).
### CTC (Core Technical Committee)
* [addaleax](https://github.com/addaleax) -
**Anna Henningsen** <[email protected]>
* [bnoordhuis](https://github.com/bnoordhuis) -
**Ben Noordhuis** <[email protected]>
* [ChALkeR](https://github.com/ChALkeR) -
**Сковорода Никита Андреевич** <[email protected]>
* [chrisdickinson](https://github.com/chrisdickinson) -
**Chris Dickinson** <[email protected]>
* [cjihrig](https://github.com/cjihrig) -
**Colin Ihrig** <[email protected]>
* [evanlucas](https://github.com/evanlucas) -
**Evan Lucas** <[email protected]>
* [fishrock123](https://github.com/fishrock123) -
**Jeremiah Senkpiel** <[email protected]>
* [indutny](https://github.com/indutny) -
**Fedor Indutny** <[email protected]>
* [jasnell](https://github.com/jasnell) -
**James M Snell** <[email protected]>
* [mhdawson](https://github.com/mhdawson) -
**Michael Dawson** <[email protected]>
* [misterdjules](https://github.com/misterdjules) -
**Julien Gilli** <[email protected]>
* [mscdex](https://github.com/mscdex) -
**Brian White** <[email protected]>
* [ofrobots](https://github.com/ofrobots) -
**Ali Ijaz Sheikh** <[email protected]>
* [rvagg](https://github.com/rvagg) -
**Rod Vagg** <[email protected]>
* [shigeki](https://github.com/shigeki) -
**Shigeki Ohtsu** <[email protected]>
* [TheAlphaNerd](https://github.com/TheAlphaNerd) -
**Myles Borins** <[email protected]>
* [trevnorris](https://github.com/trevnorris) -
**Trevor Norris** <[email protected]>
* [Trott](https://github.com/Trott) -
**Rich Trott** <[email protected]>
### Collaborators
* [ak239](https://github.com/ak239) -
**Aleksei Koziatinskii** <[email protected]>
* [andrasq](https://github.com/andrasq) -
**Andras** <[email protected]>
* [AndreasMadsen](https://github.com/AndreasMadsen) -
**Andreas Madsen** <[email protected]>
* [bengl](https://github.com/bengl) -
**Bryan English** <[email protected]>
* [benjamingr](https://github.com/benjamingr) -
**Benjamin Gruenbaum** <[email protected]>
* [bmeck](https://github.com/bmeck) -
**Bradley Farias** <[email protected]>
* [brendanashworth](https://github.com/brendanashworth) -
**Brendan Ashworth** <[email protected]>
* [bzoz](https://github.com/bzoz) -
**Bartosz Sosnowski** <[email protected]>
* [calvinmetcalf](https://github.com/calvinmetcalf) -
**Calvin Metcalf** <[email protected]>
* [claudiorodriguez](https://github.com/claudiorodriguez) -
**Claudio Rodriguez** <[email protected]>
* [danbev](https://github.com/danbev) -
**Daniel Bevenius** <[email protected]>
* [domenic](https://github.com/domenic) -
**Domenic Denicola** <[email protected]>
* [eljefedelrodeodeljefe](https://github.com/eljefedelrodeodeljefe) -
**Robert Jefe Lindstaedt** <[email protected]>
* [estliberitas](https://github.com/estliberitas) -
**Alexander Makarenko** <[email protected]>
* [eugeneo](https://github.com/eugeneo) -
**Eugene Ostroukhov** <[email protected]>
* [fhinkel](https://github.com/fhinkel) -
**Franziska Hinkelmann** <[email protected]>
* [firedfox](https://github.com/firedfox) -
**Daniel Wang** <[email protected]>
* [geek](https://github.com/geek) -
**Wyatt Preul** <[email protected]>
* [gibfahn](https://github.com/gibfahn) -
**Gibson Fahnestock** <[email protected]>
* [iarna](https://github.com/iarna) -
**Rebecca Turner** <[email protected]>
* [imyller](https://github.com/imyller) -
**Ilkka Myller** <[email protected]>
* [isaacs](https://github.com/isaacs) -
**Isaac Z. Schlueter** <[email protected]>
* [iWuzHere](https://github.com/iWuzHere) -
**Imran Iqbal** <[email protected]>
* [JacksonTian](https://github.com/JacksonTian) -
**Jackson Tian** <[email protected]>
* [jbergstroem](https://github.com/jbergstroem) -
**Johan Bergström** <[email protected]>
* [jhamhader](https://github.com/jhamhader) -
**Yuval Brik** <[email protected]>
* [joaocgreis](https://github.com/joaocgreis) -
**João Reis** <[email protected]>
* [joshgav](https://github.com/joshgav) -
**Josh Gavant** <[email protected]>
* [julianduque](https://github.com/julianduque) -
**Julian Duque** <[email protected]>
* [JungMinu](https://github.com/JungMinu) -
**Minwoo Jung** <[email protected]>
* [lance](https://github.com/lance) -
**Lance Ball** <[email protected]>
* [lpinca](https://github.com/lpinca) -
**Luigi Pinca** <[email protected]>
* [lxe](https://github.com/lxe) -
**Aleksey Smolenchuk** <[email protected]>
* [matthewloring](https://github.com/matthewloring) -
**Matthew Loring** <[email protected]>
* [mcollina](https://github.com/mcollina) -
**Matteo Collina** <[email protected]>
* [micnic](https://github.com/micnic) -
**Nicu Micleușanu** <[email protected]>
* [mikeal](https://github.com/mikeal) -
**Mikeal Rogers** <[email protected]>
* [monsanto](https://github.com/monsanto) -
**Christopher Monsanto** <[email protected]>
* [not-an-aardvark](https://github.com/not-an-aardvark) -
**Teddy Katz** <[email protected]>
* [Olegas](https://github.com/Olegas) -
**Oleg Elifantiev** <[email protected]>
* [orangemocha](https://github.com/orangemocha) -
**Alexis Campailla** <[email protected]>
* [othiym23](https://github.com/othiym23) -
**Forrest L Norvell** <[email protected]>
* [petkaantonov](https://github.com/petkaantonov) -
**Petka Antonov** <[email protected]>
* [phillipj](https://github.com/phillipj) -
**Phillip Johnsen** <[email protected]>
* [piscisaureus](https://github.com/piscisaureus) -
**Bert Belder** <[email protected]>
* [pmq20](https://github.com/pmq20) -
**Minqi Pan** <[email protected]>
* [princejwesley](https://github.com/princejwesley) -
**Prince John Wesley** <[email protected]>
* [qard](https://github.com/qard) -
**Stephen Belanger** <[email protected]>
* [rlidwka](https://github.com/rlidwka) -
**Alex Kocharin** <[email protected]>
* [rmg](https://github.com/rmg) -
**Ryan Graham** <[email protected]>
* [robertkowalski](https://github.com/robertkowalski) -
**Robert Kowalski** <[email protected]>
* [romankl](https://github.com/romankl) -
**Roman Klauke** <[email protected]>
* [ronkorving](https://github.com/ronkorving) -
**Ron Korving** <[email protected]>
* [RReverser](https://github.com/RReverser) -
**Ingvar Stepanyan** <[email protected]>
* [saghul](https://github.com/saghul) -
**Saúl Ibarra Corretgé** <[email protected]>
* [sam-github](https://github.com/sam-github) -
**Sam Roberts** <[email protected]>
* [santigimeno](https://github.com/santigimeno) -
**Santiago Gimeno** <[email protected]>
* [seishun](https://github.com/seishun) -
**Nikolai Vavilov** <[email protected]>
* [silverwind](https://github.com/silverwind) -
**Roman Reiss** <[email protected]>
* [srl295](https://github.com/srl295) -
**Steven R Loomis** <[email protected]>
* [stefanmb](https://github.com/stefanmb) -
**Stefan Budeanu** <[email protected]>
* [targos](https://github.com/targos) -
**Michaël Zasso** <[email protected]>
* [tellnes](https://github.com/tellnes) -
**Christian Tellnes** <[email protected]>
* [thefourtheye](https://github.com/thefourtheye) -
**Sakthipriyan Vairamani** <[email protected]>
* [thekemkid](https://github.com/thekemkid) -
**Glen Keane** <[email protected]>
* [thlorenz](https://github.com/thlorenz) -
**Thorsten Lorenz** <[email protected]>
* [tunniclm](https://github.com/tunniclm) -
**Mike Tunnicliffe** <[email protected]>
* [vkurchatkin](https://github.com/vkurchatkin) -
**Vladimir Kurchatkin** <[email protected]>
* [whitlockjc](https://github.com/whitlockjc) -
**Jeremy Whitlock** <[email protected]>
* [yorkie](https://github.com/yorkie) -
**Yorkie Liu** <[email protected]>
* [yosuke-furukawa](https://github.com/yosuke-furukawa) -
**Yosuke Furukawa** <[email protected]>
* [zkat](https://github.com/zkat) -
**Kat Marchán** <[email protected]>
Collaborators (which includes CTC members) follow the
[COLLABORATOR_GUIDE.md](./COLLABORATOR_GUIDE.md) in maintaining the Node.js
project.
### Release Team
Releases of Node.js and io.js will be signed with one of the following GPG keys:
* **Chris Dickinson** <[email protected]>
`9554F04D7259F04124DE6B476D5A82AC7E37093B`
* **Colin Ihrig** <[email protected]>
`94AE36675C464D64BAFA68DD7434390BDBE9B9C5`
* **Evan Lucas** <[email protected]>
`B9AE9905FFD7803F25714661B63B535A4C206CA9`
* **James M Snell** <[email protected]>
`71DCFD284A79C3B38668286BC97EC7A07EDE3FC1`
* **Jeremiah Senkpiel** <[email protected]>
`FD3A5288F042B6850C66B31F09FE44734EB7990E`
* **Myles Borins** <[email protected]>
`C4F0DFFF4E8C1A8236409D08E73BC641CC11F4C8`
* **Rod Vagg** <[email protected]>
`DD8F2338BAE7501E3DD5AC78C273792F7D83545D`
* **Sam Roberts** <[email protected]>
`0034A06D9D9B0064CE8ADF6BF1747F4AD2306D93`
The full set of trusted release keys can be imported by running:
```shell
gpg --keyserver pool.sks-keyservers.net --recv-keys 9554F04D7259F04124DE6B476D5A82AC7E37093B
gpg --keyserver pool.sks-keyservers.net --recv-keys 94AE36675C464D64BAFA68DD7434390BDBE9B9C5
gpg --keyserver pool.sks-keyservers.net --recv-keys 0034A06D9D9B0064CE8ADF6BF1747F4AD2306D93
gpg --keyserver pool.sks-keyservers.net --recv-keys FD3A5288F042B6850C66B31F09FE44734EB7990E
gpg --keyserver pool.sks-keyservers.net --recv-keys 71DCFD284A79C3B38668286BC97EC7A07EDE3FC1
gpg --keyserver pool.sks-keyservers.net --recv-keys DD8F2338BAE7501E3DD5AC78C273792F7D83545D
gpg --keyserver pool.sks-keyservers.net --recv-keys C4F0DFFF4E8C1A8236409D08E73BC641CC11F4C8
gpg --keyserver pool.sks-keyservers.net --recv-keys B9AE9905FFD7803F25714661B63B535A4C206CA9
```
See the section above on [Verifying Binaries](#verifying-binaries) for details
on what to do with these keys to verify that a downloaded file is official.
Previous releases of Node.js have been signed with one of the following GPG
keys:
* **Isaac Z. Schlueter** <[email protected]>
`93C7E9E91B49E432C2F75674B0A78B0A6C481CF6`
* **Julien Gilli** <[email protected]>
`114F43EE0176B71C7BC219DD50A3051F888C628D`
* **Timothy J Fontaine** <[email protected]>
`7937DFD2AB06298B2293C3187D33FF9D0246406D`
[Website]: https://nodejs.org/en/
[Contributing to the project]: CONTRIBUTING.md
[Node.js Help]: https://github.com/nodejs/help
[Node.js Moderation Policy]: https://github.com/nodejs/TSC/blob/master/Moderation-Policy.md
[#node.js on chat.freenode.net]: https://webchat.freenode.net?channels=node.js&uio=d4
[#node-dev on chat.freenode.net]: https://webchat.freenode.net?channels=node-dev&uio=d4
| {'repo_name': 'domino-team/openwrt-cc', 'stars': '111', 'repo_language': 'C++', 'file_name': 'ecp_nistz256-avx2.pl', 'mime_type': 'text/x-perl', 'hash': -285215796152848364, 'source_dataset': 'data'} |
"itembuilds/default_sohei.txt"
{
"author" "Open Angel Arena"
"hero" "npc_dota_hero_sohei"
"Title" "Recommended items for Sohei"
"Items"
{
"#DOTA_Item_Build_Starting_Items"
{
"item" "item_quelling_blade"
"item" "item_flask"
"item" "item_magic_wand"
}
"#DOTA_Item_Build_Early_Game"
{
"item" "item_armlet"
"item" "item_echo_sabre"
"item" "item_heart"
}
"#DOTA_Item_Build_Mid_Items"
{
"item" "item_desolator"
"item" "item_mjollnir"
"item" "item_monkey_king_bar"
}
"#DOTA_Item_Build_Core_Items"
{
"item" "item_satanic"
"item" "item_bfury"
"item" "item_greater_crit"
}
"#DOTA_Item_Build_Luxury"
{
"item" "item_ultimate_scepter"
"item" "item_abyssal_blade_3"
"item" "item_assault"
"item" "item_giant_form"
"item" "item_pull_staff"
"item" "item_heavens_halberd"
}
}
}
| {'repo_name': 'OpenAngelArena/oaa', 'stars': '193', 'repo_language': 'Lua', 'file_name': 'launch.json', 'mime_type': 'text/plain', 'hash': 7437959883519751732, 'source_dataset': 'data'} |
//-------------------------------------------------------------------------
// flags for vc_dispmanx_element_change_attributes
//
// can be found in interface/vmcs_host/vc_vchi_dispmanx.h
// but you can't include that file as
// interface/peer/vc_vchi_dispmanx_common.h is missing.
//
//-------------------------------------------------------------------------
#ifndef ELEMENT_CHANGE_H
#define ELEMENT_CHANGE_H
#ifndef ELEMENT_CHANGE_LAYER
#define ELEMENT_CHANGE_LAYER (1<<0)
#endif
#ifndef ELEMENT_CHANGE_OPACITY
#define ELEMENT_CHANGE_OPACITY (1<<1)
#endif
#ifndef ELEMENT_CHANGE_DEST_RECT
#define ELEMENT_CHANGE_DEST_RECT (1<<2)
#endif
#ifndef ELEMENT_CHANGE_SRC_RECT
#define ELEMENT_CHANGE_SRC_RECT (1<<3)
#endif
#ifndef ELEMENT_CHANGE_MASK_RESOURCE
#define ELEMENT_CHANGE_MASK_RESOURCE (1<<4)
#endif
#ifndef ELEMENT_CHANGE_TRANSFORM
#define ELEMENT_CHANGE_TRANSFORM (1<<5)
#endif
#endif
| {'repo_name': 'AndrewFromMelbourne/raspidmx', 'stars': '177', 'repo_language': 'C', 'file_name': 'Makefile', 'mime_type': 'text/x-makefile', 'hash': 251230986575201211, 'source_dataset': 'data'} |
#%Module1.0
##############################################################################
# Modules Revision 3.0
# Providing a flexible user environment
#
# File: versions/%M%
# Revision: %I%
# First Edition: 2001/06/20
# Last Mod.: %U%, %G%
#
# Authors: R.K.Owen
#
# Description: Testuite modulefile
# Command:
#
# Invocation:
# Result: %R{
# }R%
# Comment: %C{
# tests whether the versioning stack is working.
# }C%
#
##############################################################################
if [ expr [ module-info mode load ] || [ module-info mode display ] ] {
setenv MODULE_VERSION 1.1
}
prepend-path MODULE_VERSION_STACK 1.1
if [ module-info mode remove ] {
unsetenv MODULE_VERSION [lindex [split $env(MODULE_VERSION_STACK) : ] 0 ]
}
| {'repo_name': 'cea-hpc/modules', 'stars': '267', 'repo_language': 'Tcl', 'file_name': 'name', 'mime_type': 'text/plain', 'hash': -5763305062082910138, 'source_dataset': 'data'} |
<resources>
<color name="colorPrimary">#3F51B5</color>
<color name="colorPrimaryDark">#303F9F</color>
<color name="colorAccent">#FF4081</color>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
</resources> | {'repo_name': 'heremaps/here-android-sdk-examples', 'stars': '109', 'repo_language': 'Java', 'file_name': 'MapFragmentView.java', 'mime_type': 'text/x-java', 'hash': -5434807066047510772, 'source_dataset': 'data'} |
<!--
- @copyright Copyright (c) 2018 Julius Härtl <[email protected]>
-
- @author Julius Härtl <[email protected]>
-
- @license GNU AGPL version 3 or any later version
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU Affero General Public License as
- published by the Free Software Foundation, either version 3 of the
- License, or (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU Affero General Public License for more details.
-
- You should have received a copy of the GNU Affero General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
-
-->
<template>
<div class="section" :class="{ selected: isSelected }" @click="showAppDetails">
<div class="app-image app-image-icon" @click="showAppDetails">
<div v-if="(listView && !app.preview) || (!listView && !screenshotLoaded)" class="icon-settings-dark" />
<svg v-else-if="listView && app.preview"
width="32"
height="32"
viewBox="0 0 32 32">
<defs><filter :id="filterId"><feColorMatrix in="SourceGraphic" type="matrix" values="-1 0 0 0 1 0 -1 0 0 1 0 0 -1 0 1 0 0 0 1 0" /></filter></defs>
<image x="0"
y="0"
width="32"
height="32"
preserveAspectRatio="xMinYMin meet"
:filter="filterUrl"
:xlink:href="app.preview"
class="app-icon" />
</svg>
<img v-if="!listView && app.screenshot && screenshotLoaded" :src="app.screenshot" width="100%">
</div>
<div class="app-name" @click="showAppDetails">
{{ app.name }}
</div>
<div v-if="!listView" class="app-summary">
{{ app.summary }}
</div>
<div v-if="listView" class="app-version">
<span v-if="app.version">{{ app.version }}</span>
<span v-else-if="app.appstoreData.releases[0].version">{{ app.appstoreData.releases[0].version }}</span>
</div>
<div class="app-level">
<span v-if="app.level === 300"
v-tooltip.auto="t('settings', 'This app is supported via your current Nextcloud subscription.')"
class="supported icon-checkmark-color">
{{ t('settings', 'Supported') }}</span>
<span v-if="app.level === 200"
v-tooltip.auto="t('settings', 'Featured apps are developed by and within the community. They offer central functionality and are ready for production use.')"
class="official icon-checkmark">
{{ t('settings', 'Featured') }}</span>
<AppScore v-if="hasRating && !listView" :score="app.score" />
</div>
<div class="actions">
<div v-if="app.error" class="warning">
{{ app.error }}
</div>
<div v-if="isLoading" class="icon icon-loading-small" />
<input v-if="app.update"
class="update primary"
type="button"
:value="t('settings', 'Update to {update}', {update:app.update})"
:disabled="installing || isLoading"
@click.stop="update(app.id)">
<input v-if="app.canUnInstall"
class="uninstall"
type="button"
:value="t('settings', 'Remove')"
:disabled="installing || isLoading"
@click.stop="remove(app.id)">
<input v-if="app.active"
class="enable"
type="button"
:value="t('settings','Disable')"
:disabled="installing || isLoading"
@click.stop="disable(app.id)">
<input v-if="!app.active && (app.canInstall || app.isCompatible)"
v-tooltip.auto="enableButtonTooltip"
class="enable"
type="button"
:value="enableButtonText"
:disabled="!app.canInstall || installing || isLoading"
@click.stop="enable(app.id)">
<input v-else-if="!app.active"
v-tooltip.auto="forceEnableButtonTooltip"
class="enable force"
type="button"
:value="forceEnableButtonText"
:disabled="installing || isLoading"
@click.stop="forceEnable(app.id)">
</div>
</div>
</template>
<script>
import AppScore from './AppScore'
import AppManagement from '../../mixins/AppManagement'
import SvgFilterMixin from '../SvgFilterMixin'
export default {
name: 'AppItem',
components: {
AppScore,
},
mixins: [AppManagement, SvgFilterMixin],
props: {
app: {},
category: {},
listView: {
type: Boolean,
default: true,
},
},
data() {
return {
isSelected: false,
scrolled: false,
screenshotLoaded: false,
}
},
computed: {
hasRating() {
return this.app.appstoreData && this.app.appstoreData.ratingNumOverall > 5
},
},
watch: {
'$route.params.id'(id) {
this.isSelected = (this.app.id === id)
},
},
mounted() {
this.isSelected = (this.app.id === this.$route.params.id)
if (this.app.screenshot) {
const image = new Image()
image.onload = (e) => {
this.screenshotLoaded = true
}
image.src = this.app.screenshot
}
},
watchers: {
},
methods: {
async showAppDetails(event) {
if (event.currentTarget.tagName === 'INPUT' || event.currentTarget.tagName === 'A') {
return
}
try {
await this.$router.push({
name: 'apps-details',
params: { category: this.category, id: this.app.id },
})
} catch (e) {
// we already view this app
}
},
prefix(prefix, content) {
return prefix + '_' + content
},
},
}
</script>
<style scoped>
.force {
background: var(--color-main-background);
border-color: var(--color-error);
color: var(--color-error);
}
.force:hover,
.force:active {
background: var(--color-error);
border-color: var(--color-error) !important;
color: var(--color-main-background);
}
</style>
| {'repo_name': 'nextcloud/server', 'stars': '11218', 'repo_language': 'PHP', 'file_name': 'webpack.js', 'mime_type': 'text/plain', 'hash': -4158776790597008594, 'source_dataset': 'data'} |
// Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.aws.toolkits.core.utils
import java.util.Random
object RuleUtils {
fun randomName(prefix: String = "a", length: Int = 63): String {
val characters = ('0'..'9') + ('A'..'Z') + ('a'..'Z')
val userName = System.getProperty("user.name", "unknown")
return "${prefix.toLowerCase()}-${userName.toLowerCase()}-${List(length) { characters.random() }.joinToString("")}".take(length)
}
fun prefixFromCallingClass(): String {
val callingClass = Thread.currentThread().stackTrace[3].className
return callingClass.substringAfterLast(".")
}
fun randomNumber(min: Int = 0, max: Int = 65535): Int = Random().nextInt(max - min + 1) + min
}
| {'repo_name': 'aws/aws-toolkit-jetbrains', 'stars': '449', 'repo_language': 'Kotlin', 'file_name': 'DotNetLambdaBuilderTest.kt', 'mime_type': 'text/plain', 'hash': 4634542050259621556, 'source_dataset': 'data'} |
//
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Jun 9 2015 22:53:21).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2014 by Steve Nygard.
//
#import <Foundation/NSValueTransformer.h>
@interface TNSUIntegerToNSSizeTransformer : NSValueTransformer
{
}
- (BOOL)allowsReverseTransformation;
- (id)reverseTransformedValue:(id)arg1;
- (id)transformedValue:(id)arg1;
@end
| {'repo_name': 'w0lfschild/macOS_headers', 'stars': '304', 'repo_language': 'None', 'file_name': 'NSTextFinderBarContainer-Protocol.h', 'mime_type': 'text/x-objective-c', 'hash': 5205870497944673134, 'source_dataset': 'data'} |
//===- ThreadSafetyCommon.h -------------------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// Parts of thread safety analysis that are not specific to thread safety
// itself have been factored into classes here, where they can be potentially
// used by other analyses. Currently these include:
//
// * Generalize clang CFG visitors.
// * Conversion of the clang CFG to SSA form.
// * Translation of clang Exprs to TIL SExprs
//
// UNDER CONSTRUCTION. USE AT YOUR OWN RISK.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_ANALYSIS_ANALYSES_THREADSAFETYCOMMON_H
#define LLVM_CLANG_ANALYSIS_ANALYSES_THREADSAFETYCOMMON_H
#include "clang/AST/Decl.h"
#include "clang/Analysis/Analyses/PostOrderCFGView.h"
#include "clang/Analysis/Analyses/ThreadSafetyTIL.h"
#include "clang/Analysis/Analyses/ThreadSafetyTraverse.h"
#include "clang/Analysis/Analyses/ThreadSafetyUtil.h"
#include "clang/Analysis/AnalysisDeclContext.h"
#include "clang/Analysis/CFG.h"
#include "clang/Basic/LLVM.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Support/Casting.h"
#include <sstream>
#include <string>
#include <utility>
#include <vector>
namespace clang {
class AbstractConditionalOperator;
class ArraySubscriptExpr;
class BinaryOperator;
class CallExpr;
class CastExpr;
class CXXDestructorDecl;
class CXXMemberCallExpr;
class CXXOperatorCallExpr;
class CXXThisExpr;
class DeclRefExpr;
class DeclStmt;
class Expr;
class MemberExpr;
class Stmt;
class UnaryOperator;
namespace threadSafety {
// Various helper functions on til::SExpr
namespace sx {
inline bool equals(const til::SExpr *E1, const til::SExpr *E2) {
return til::EqualsComparator::compareExprs(E1, E2);
}
inline bool matches(const til::SExpr *E1, const til::SExpr *E2) {
// We treat a top-level wildcard as the "univsersal" lock.
// It matches everything for the purpose of checking locks, but not
// for unlocking them.
if (isa<til::Wildcard>(E1))
return isa<til::Wildcard>(E2);
if (isa<til::Wildcard>(E2))
return isa<til::Wildcard>(E1);
return til::MatchComparator::compareExprs(E1, E2);
}
inline bool partiallyMatches(const til::SExpr *E1, const til::SExpr *E2) {
const auto *PE1 = dyn_cast_or_null<til::Project>(E1);
if (!PE1)
return false;
const auto *PE2 = dyn_cast_or_null<til::Project>(E2);
if (!PE2)
return false;
return PE1->clangDecl() == PE2->clangDecl();
}
inline std::string toString(const til::SExpr *E) {
std::stringstream ss;
til::StdPrinter::print(E, ss);
return ss.str();
}
} // namespace sx
// This class defines the interface of a clang CFG Visitor.
// CFGWalker will invoke the following methods.
// Note that methods are not virtual; the visitor is templatized.
class CFGVisitor {
// Enter the CFG for Decl D, and perform any initial setup operations.
void enterCFG(CFG *Cfg, const NamedDecl *D, const CFGBlock *First) {}
// Enter a CFGBlock.
void enterCFGBlock(const CFGBlock *B) {}
// Returns true if this visitor implements handlePredecessor
bool visitPredecessors() { return true; }
// Process a predecessor edge.
void handlePredecessor(const CFGBlock *Pred) {}
// Process a successor back edge to a previously visited block.
void handlePredecessorBackEdge(const CFGBlock *Pred) {}
// Called just before processing statements.
void enterCFGBlockBody(const CFGBlock *B) {}
// Process an ordinary statement.
void handleStatement(const Stmt *S) {}
// Process a destructor call
void handleDestructorCall(const VarDecl *VD, const CXXDestructorDecl *DD) {}
// Called after all statements have been handled.
void exitCFGBlockBody(const CFGBlock *B) {}
// Return true
bool visitSuccessors() { return true; }
// Process a successor edge.
void handleSuccessor(const CFGBlock *Succ) {}
// Process a successor back edge to a previously visited block.
void handleSuccessorBackEdge(const CFGBlock *Succ) {}
// Leave a CFGBlock.
void exitCFGBlock(const CFGBlock *B) {}
// Leave the CFG, and perform any final cleanup operations.
void exitCFG(const CFGBlock *Last) {}
};
// Walks the clang CFG, and invokes methods on a given CFGVisitor.
class CFGWalker {
public:
CFGWalker() = default;
// Initialize the CFGWalker. This setup only needs to be done once, even
// if there are multiple passes over the CFG.
bool init(AnalysisDeclContext &AC) {
ACtx = &AC;
CFGraph = AC.getCFG();
if (!CFGraph)
return false;
// Ignore anonymous functions.
if (!dyn_cast_or_null<NamedDecl>(AC.getDecl()))
return false;
SortedGraph = AC.getAnalysis<PostOrderCFGView>();
if (!SortedGraph)
return false;
return true;
}
// Traverse the CFG, calling methods on V as appropriate.
template <class Visitor>
void walk(Visitor &V) {
PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
V.enterCFG(CFGraph, getDecl(), &CFGraph->getEntry());
for (const auto *CurrBlock : *SortedGraph) {
VisitedBlocks.insert(CurrBlock);
V.enterCFGBlock(CurrBlock);
// Process predecessors, handling back edges last
if (V.visitPredecessors()) {
SmallVector<CFGBlock*, 4> BackEdges;
// Process successors
for (CFGBlock::const_pred_iterator SI = CurrBlock->pred_begin(),
SE = CurrBlock->pred_end();
SI != SE; ++SI) {
if (*SI == nullptr)
continue;
if (!VisitedBlocks.alreadySet(*SI)) {
BackEdges.push_back(*SI);
continue;
}
V.handlePredecessor(*SI);
}
for (auto *Blk : BackEdges)
V.handlePredecessorBackEdge(Blk);
}
V.enterCFGBlockBody(CurrBlock);
// Process statements
for (const auto &BI : *CurrBlock) {
switch (BI.getKind()) {
case CFGElement::Statement:
V.handleStatement(BI.castAs<CFGStmt>().getStmt());
break;
case CFGElement::AutomaticObjectDtor: {
CFGAutomaticObjDtor AD = BI.castAs<CFGAutomaticObjDtor>();
auto *DD = const_cast<CXXDestructorDecl *>(
AD.getDestructorDecl(ACtx->getASTContext()));
auto *VD = const_cast<VarDecl *>(AD.getVarDecl());
V.handleDestructorCall(VD, DD);
break;
}
default:
break;
}
}
V.exitCFGBlockBody(CurrBlock);
// Process successors, handling back edges first.
if (V.visitSuccessors()) {
SmallVector<CFGBlock*, 8> ForwardEdges;
// Process successors
for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
SE = CurrBlock->succ_end();
SI != SE; ++SI) {
if (*SI == nullptr)
continue;
if (!VisitedBlocks.alreadySet(*SI)) {
ForwardEdges.push_back(*SI);
continue;
}
V.handleSuccessorBackEdge(*SI);
}
for (auto *Blk : ForwardEdges)
V.handleSuccessor(Blk);
}
V.exitCFGBlock(CurrBlock);
}
V.exitCFG(&CFGraph->getExit());
}
const CFG *getGraph() const { return CFGraph; }
CFG *getGraph() { return CFGraph; }
const NamedDecl *getDecl() const {
return dyn_cast<NamedDecl>(ACtx->getDecl());
}
const PostOrderCFGView *getSortedGraph() const { return SortedGraph; }
private:
CFG *CFGraph = nullptr;
AnalysisDeclContext *ACtx = nullptr;
PostOrderCFGView *SortedGraph = nullptr;
};
// TODO: move this back into ThreadSafety.cpp
// This is specific to thread safety. It is here because
// translateAttrExpr needs it, but that should be moved too.
class CapabilityExpr {
private:
/// The capability expression.
const til::SExpr* CapExpr;
/// True if this is a negative capability.
bool Negated;
public:
CapabilityExpr(const til::SExpr *E, bool Neg) : CapExpr(E), Negated(Neg) {}
const til::SExpr* sexpr() const { return CapExpr; }
bool negative() const { return Negated; }
CapabilityExpr operator!() const {
return CapabilityExpr(CapExpr, !Negated);
}
bool equals(const CapabilityExpr &other) const {
return (Negated == other.Negated) && sx::equals(CapExpr, other.CapExpr);
}
bool matches(const CapabilityExpr &other) const {
return (Negated == other.Negated) && sx::matches(CapExpr, other.CapExpr);
}
bool matchesUniv(const CapabilityExpr &CapE) const {
return isUniversal() || matches(CapE);
}
bool partiallyMatches(const CapabilityExpr &other) const {
return (Negated == other.Negated) &&
sx::partiallyMatches(CapExpr, other.CapExpr);
}
const ValueDecl* valueDecl() const {
if (Negated || CapExpr == nullptr)
return nullptr;
if (const auto *P = dyn_cast<til::Project>(CapExpr))
return P->clangDecl();
if (const auto *P = dyn_cast<til::LiteralPtr>(CapExpr))
return P->clangDecl();
return nullptr;
}
std::string toString() const {
if (Negated)
return "!" + sx::toString(CapExpr);
return sx::toString(CapExpr);
}
bool shouldIgnore() const { return CapExpr == nullptr; }
bool isInvalid() const { return sexpr() && isa<til::Undefined>(sexpr()); }
bool isUniversal() const { return sexpr() && isa<til::Wildcard>(sexpr()); }
};
// Translate clang::Expr to til::SExpr.
class SExprBuilder {
public:
/// Encapsulates the lexical context of a function call. The lexical
/// context includes the arguments to the call, including the implicit object
/// argument. When an attribute containing a mutex expression is attached to
/// a method, the expression may refer to formal parameters of the method.
/// Actual arguments must be substituted for formal parameters to derive
/// the appropriate mutex expression in the lexical context where the function
/// is called. PrevCtx holds the context in which the arguments themselves
/// should be evaluated; multiple calling contexts can be chained together
/// by the lock_returned attribute.
struct CallingContext {
// The previous context; or 0 if none.
CallingContext *Prev;
// The decl to which the attr is attached.
const NamedDecl *AttrDecl;
// Implicit object argument -- e.g. 'this'
const Expr *SelfArg = nullptr;
// Number of funArgs
unsigned NumArgs = 0;
// Function arguments
const Expr *const *FunArgs = nullptr;
// is Self referred to with -> or .?
bool SelfArrow = false;
CallingContext(CallingContext *P, const NamedDecl *D = nullptr)
: Prev(P), AttrDecl(D) {}
};
SExprBuilder(til::MemRegionRef A) : Arena(A) {
// FIXME: we don't always have a self-variable.
SelfVar = new (Arena) til::Variable(nullptr);
SelfVar->setKind(til::Variable::VK_SFun);
}
// Translate a clang expression in an attribute to a til::SExpr.
// Constructs the context from D, DeclExp, and SelfDecl.
CapabilityExpr translateAttrExpr(const Expr *AttrExp, const NamedDecl *D,
const Expr *DeclExp, VarDecl *SelfD=nullptr);
CapabilityExpr translateAttrExpr(const Expr *AttrExp, CallingContext *Ctx);
// Translate a clang statement or expression to a TIL expression.
// Also performs substitution of variables; Ctx provides the context.
// Dispatches on the type of S.
til::SExpr *translate(const Stmt *S, CallingContext *Ctx);
til::SCFG *buildCFG(CFGWalker &Walker);
til::SExpr *lookupStmt(const Stmt *S);
til::BasicBlock *lookupBlock(const CFGBlock *B) {
return BlockMap[B->getBlockID()];
}
const til::SCFG *getCFG() const { return Scfg; }
til::SCFG *getCFG() { return Scfg; }
private:
// We implement the CFGVisitor API
friend class CFGWalker;
til::SExpr *translateDeclRefExpr(const DeclRefExpr *DRE,
CallingContext *Ctx) ;
til::SExpr *translateCXXThisExpr(const CXXThisExpr *TE, CallingContext *Ctx);
til::SExpr *translateMemberExpr(const MemberExpr *ME, CallingContext *Ctx);
til::SExpr *translateObjCIVarRefExpr(const ObjCIvarRefExpr *IVRE,
CallingContext *Ctx);
til::SExpr *translateCallExpr(const CallExpr *CE, CallingContext *Ctx,
const Expr *SelfE = nullptr);
til::SExpr *translateCXXMemberCallExpr(const CXXMemberCallExpr *ME,
CallingContext *Ctx);
til::SExpr *translateCXXOperatorCallExpr(const CXXOperatorCallExpr *OCE,
CallingContext *Ctx);
til::SExpr *translateUnaryOperator(const UnaryOperator *UO,
CallingContext *Ctx);
til::SExpr *translateBinOp(til::TIL_BinaryOpcode Op,
const BinaryOperator *BO,
CallingContext *Ctx, bool Reverse = false);
til::SExpr *translateBinAssign(til::TIL_BinaryOpcode Op,
const BinaryOperator *BO,
CallingContext *Ctx, bool Assign = false);
til::SExpr *translateBinaryOperator(const BinaryOperator *BO,
CallingContext *Ctx);
til::SExpr *translateCastExpr(const CastExpr *CE, CallingContext *Ctx);
til::SExpr *translateArraySubscriptExpr(const ArraySubscriptExpr *E,
CallingContext *Ctx);
til::SExpr *translateAbstractConditionalOperator(
const AbstractConditionalOperator *C, CallingContext *Ctx);
til::SExpr *translateDeclStmt(const DeclStmt *S, CallingContext *Ctx);
// Map from statements in the clang CFG to SExprs in the til::SCFG.
using StatementMap = llvm::DenseMap<const Stmt *, til::SExpr *>;
// Map from clang local variables to indices in a LVarDefinitionMap.
using LVarIndexMap = llvm::DenseMap<const ValueDecl *, unsigned>;
// Map from local variable indices to SSA variables (or constants).
using NameVarPair = std::pair<const ValueDecl *, til::SExpr *>;
using LVarDefinitionMap = CopyOnWriteVector<NameVarPair>;
struct BlockInfo {
LVarDefinitionMap ExitMap;
bool HasBackEdges = false;
// Successors yet to be processed
unsigned UnprocessedSuccessors = 0;
// Predecessors already processed
unsigned ProcessedPredecessors = 0;
BlockInfo() = default;
BlockInfo(BlockInfo &&) = default;
BlockInfo &operator=(BlockInfo &&) = default;
};
void enterCFG(CFG *Cfg, const NamedDecl *D, const CFGBlock *First);
void enterCFGBlock(const CFGBlock *B);
bool visitPredecessors() { return true; }
void handlePredecessor(const CFGBlock *Pred);
void handlePredecessorBackEdge(const CFGBlock *Pred);
void enterCFGBlockBody(const CFGBlock *B);
void handleStatement(const Stmt *S);
void handleDestructorCall(const VarDecl *VD, const CXXDestructorDecl *DD);
void exitCFGBlockBody(const CFGBlock *B);
bool visitSuccessors() { return true; }
void handleSuccessor(const CFGBlock *Succ);
void handleSuccessorBackEdge(const CFGBlock *Succ);
void exitCFGBlock(const CFGBlock *B);
void exitCFG(const CFGBlock *Last);
void insertStmt(const Stmt *S, til::SExpr *E) {
SMap.insert(std::make_pair(S, E));
}
til::SExpr *getCurrentLVarDefinition(const ValueDecl *VD);
til::SExpr *addStatement(til::SExpr *E, const Stmt *S,
const ValueDecl *VD = nullptr);
til::SExpr *lookupVarDecl(const ValueDecl *VD);
til::SExpr *addVarDecl(const ValueDecl *VD, til::SExpr *E);
til::SExpr *updateVarDecl(const ValueDecl *VD, til::SExpr *E);
void makePhiNodeVar(unsigned i, unsigned NPreds, til::SExpr *E);
void mergeEntryMap(LVarDefinitionMap Map);
void mergeEntryMapBackEdge();
void mergePhiNodesBackEdge(const CFGBlock *Blk);
private:
// Set to true when parsing capability expressions, which get translated
// inaccurately in order to hack around smart pointers etc.
static const bool CapabilityExprMode = true;
til::MemRegionRef Arena;
// Variable to use for 'this'. May be null.
til::Variable *SelfVar = nullptr;
til::SCFG *Scfg = nullptr;
// Map from Stmt to TIL Variables
StatementMap SMap;
// Indices of clang local vars.
LVarIndexMap LVarIdxMap;
// Map from clang to til BBs.
std::vector<til::BasicBlock *> BlockMap;
// Extra information per BB. Indexed by clang BlockID.
std::vector<BlockInfo> BBInfo;
LVarDefinitionMap CurrentLVarMap;
std::vector<til::Phi *> CurrentArguments;
std::vector<til::SExpr *> CurrentInstructions;
std::vector<til::Phi *> IncompleteArgs;
til::BasicBlock *CurrentBB = nullptr;
BlockInfo *CurrentBlockInfo = nullptr;
};
// Dump an SCFG to llvm::errs().
void printSCFG(CFGWalker &Walker);
} // namespace threadSafety
} // namespace clang
#endif // LLVM_CLANG_THREAD_SAFETY_COMMON_H
| {'repo_name': 'apple/swift-clang', 'stars': '668', 'repo_language': 'C++', 'file_name': '__init__.py', 'mime_type': 'text/plain', 'hash': -2807252079772653443, 'source_dataset': 'data'} |
import React from 'react';
import { StyledIcon } from '../StyledIcon';
export const Inspect = props => (
<StyledIcon viewBox='0 0 24 24' a11yTitle='Inspect' {...props}>
<path fill='none' stroke='#000' strokeWidth='2' d='M5.5,21 C7.98528137,21 10,18.9852814 10,16.5 C10,14.0147186 7.98528137,12 5.5,12 C3.01471863,12 1,14.0147186 1,16.5 C1,18.9852814 3.01471863,21 5.5,21 Z M1,16 L1,7 L1,6.5 C1,4.01471863 3.01471863,2 5.5,2 L6,2 M23,16 L23,7 L23,6.5 C23,4.01471863 20.9852814,2 18.5,2 L18,2 M18.5,21 C20.9852814,21 23,18.9852814 23,16.5 C23,14.0147186 20.9852814,12 18.5,12 C16.0147186,12 14,14.0147186 14,16.5 C14,18.9852814 16.0147186,21 18.5,21 Z M10,17 C10,17 10,15 12,15 C14,15 14,17 14,17' />
</StyledIcon>
);
| {'repo_name': 'grommet/grommet-icons', 'stars': '180', 'repo_language': 'JavaScript', 'file_name': 'config.yml', 'mime_type': 'text/plain', 'hash': 6005147089431510929, 'source_dataset': 'data'} |
/*
* Copyright 2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.api.internal.artifacts.repositories.metadata;
import org.gradle.api.artifacts.ModuleIdentifier;
import org.gradle.api.internal.artifacts.ivyservice.ivyresolve.parser.MetaDataParser;
import org.gradle.internal.hash.ChecksumService;
import org.gradle.api.internal.artifacts.repositories.maven.MavenMetadataLoader;
import org.gradle.api.internal.artifacts.repositories.resolver.ResourcePattern;
import org.gradle.api.internal.artifacts.repositories.resolver.VersionLister;
import org.gradle.internal.component.external.model.ModuleDependencyMetadata;
import org.gradle.internal.component.external.model.maven.MutableMavenModuleResolveMetadata;
import org.gradle.internal.component.model.IvyArtifactName;
import org.gradle.internal.resolve.result.BuildableModuleVersionListingResolveResult;
import org.gradle.internal.resource.local.FileResourceRepository;
import javax.inject.Inject;
import java.util.List;
import static org.gradle.api.internal.artifacts.repositories.metadata.DefaultArtifactMetadataSource.getPrimaryDependencyArtifact;
public class MavenLocalPomMetadataSource extends DefaultMavenPomMetadataSource {
@Inject
public MavenLocalPomMetadataSource(MetadataArtifactProvider metadataArtifactProvider, MetaDataParser<MutableMavenModuleResolveMetadata> pomParser, FileResourceRepository fileResourceRepository, MavenMetadataValidator validator, MavenMetadataLoader mavenMetadataLoader, ChecksumService checksumService) {
super(metadataArtifactProvider, pomParser, fileResourceRepository, validator, mavenMetadataLoader, checksumService);
}
@Override
public void listModuleVersions(ModuleDependencyMetadata dependency, ModuleIdentifier module, List<ResourcePattern> ivyPatterns, List<ResourcePattern> artifactPatterns, VersionLister versionLister, BuildableModuleVersionListingResolveResult result) {
IvyArtifactName dependencyArtifact = getPrimaryDependencyArtifact(dependency);
versionLister.listVersions(module, dependencyArtifact, artifactPatterns, result);
}
}
| {'repo_name': 'gradle/gradle', 'stars': '10712', 'repo_language': 'Groovy', 'file_name': 'DefaultRuleActionAdapterTest.groovy', 'mime_type': 'text/plain', 'hash': 2961538894354833027, 'source_dataset': 'data'} |