repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
HackNTU/HackingMap | src/router/index.js | 1490 | import Vue from 'vue'
import Router from 'vue-router'
import Home from '@/components/home/Home'
import MapView from '@/components/home/hackingmap/MapView.vue'
import ListView from '@/components/home/hackingmap/ListView.vue'
import FullMapView from '@/components/home/hackingmap/FullMapView'
import AdminView from '@/components/AdminView'
import MentorView from '@/components/MentorView'
import AskMentor from '@/components/AskMentor'
import LiveAwards from '@/components/LiveAwards'
import Speaker from '@/components/Speaker'
import Expo from '@/components/Expo'
// import User from '@/components/user/User'
// import Profile from '@/components/user/Profile'
Vue.use(Router)
export default new Router({
routes: [
{ path: '*', redirect: '/projects' },
{
path: '/',
component: Home,
children: [
{ path: 'map', component: MapView, name: 'Map' },
{ path: 'projects', component: ListView },
{ path: 'full_map', component: FullMapView },
{ path: '', redirect: '/projects' }
]
},
{ path: '/admin', component: AdminView },
{ path: '/mentor', component: MentorView },
{ path: '/askMentor', component: AskMentor },
{ path: '/liveAwards', component: LiveAwards },
{ path: '/speaker', component: Speaker },
{ path: '/expo', component: Expo }
// {
// path: '/user',
// component: User,
// children: [
// { path: '/user/profile', component: Profile }
// ]
// }
]
})
| apache-2.0 |
jerlang/jerlang | src/main/java/org/jerlang/erts/epmd/NodeRegistry.java | 1317 | package org.jerlang.erts.epmd;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class NodeRegistry {
private Map<String, Node> nodes = new ConcurrentHashMap<>();
private Map<String, Node> unreg = new ConcurrentHashMap<>();
public void register(Node node) {
nodes.put(node.nodeName(), node);
unreg.remove(node.nodeName());
}
public void unregister(Node node) {
nodes.remove(node.nodeName());
unreg.put(node.nodeName(), node);
}
public String names() {
StringBuilder stringBuilder = new StringBuilder();
list(stringBuilder, nodes.values(), "name ", "\n");
return stringBuilder.toString();
}
public String dump() {
StringBuilder stringBuilder = new StringBuilder();
list(stringBuilder, nodes.values(), "active name ", ", fd = 0\n");
list(stringBuilder, unreg.values(), "old/unused name ", ", fd = 0 \n");
return stringBuilder.toString();
}
private static void list(StringBuilder sb, Collection<Node> nodes, String prefix, String suffix) {
for (Node node : nodes) {
sb.append(prefix).append(node.nodeName());
sb.append(" at port ").append(node.portNo()).append(suffix);
}
}
}
| apache-2.0 |
mdavid/nuget | test/Core.Test/UserSettingsTests.cs | 32646 | using System;
using System.Collections.Generic;
using System.IO;
using Moq;
using Xunit;
using NuGet.Test.Mocks;
namespace NuGet.Test
{
public class SettingsTests
{
[Fact]
public void UserSettings_CallingCtroWithNullFileSystemWithThrowException()
{
// Act & Assert
ExceptionAssert.Throws<ArgumentNullException>(() => new Settings(null));
}
[Fact]
public void UserSettings_WillGetConfigurationFromSpecifiedPath()
{
// Arrange
const string configFile = "NuGet.Config";
var mockFileSystem = new Mock<IFileSystem>();
string config = @"
<configuration>
<SectionName>
<add key='key1' value='value1' />
<add Key='key2' Value='value2' />
</SectionName>
</configuration>";
mockFileSystem.Setup(m => m.OpenFile(configFile)).Returns(config.AsStream());
mockFileSystem.Setup(m => m.FileExists(configFile)).Returns(true);
// Act
Settings settings = new Settings(mockFileSystem.Object);
// Assert
mockFileSystem.Verify(x => x.OpenFile(configFile), Times.Once(), "File was not read");
}
[Fact]
public void UserSettings_CallingGetValuesWithNullSectionWillThrowException()
{
// Arrange
var mockFileSystem = new Mock<IFileSystem>();
var settings = new Settings(mockFileSystem.Object);
// Act & Assert
ExceptionAssert.Throws<ArgumentException>(() => settings.GetValues(null));
}
[Fact]
public void UserSettings_CallingGetValueWithNullSectionWillThrowException()
{
// Arrange
var mockFileSystem = new Mock<IFileSystem>();
var settings = new Settings(mockFileSystem.Object);
// Act & Assert
ExceptionAssert.Throws<ArgumentException>(() => settings.GetValue(null, "SomeKey"));
}
[Fact]
public void UserSettings_CallingGetValueWithNullKeyWillThrowException()
{
// Arrange
var mockFileSystem = new Mock<IFileSystem>();
var settings = new Settings(mockFileSystem.Object);
// Act & Assert
ExceptionAssert.Throws<ArgumentException>(() => settings.GetValue("SomeSection", null));
}
[Fact]
public void UserSettings_CallingCtorWithMalformedConfigThrowsException()
{
var mockFileSystem = new Mock<IFileSystem>();
var nugetConfigPath = "NuGet.Config";
mockFileSystem.Setup(m => m.FileExists(nugetConfigPath)).Returns(true);
string config = @"<configuration><sectionName></configuration>";
mockFileSystem.Setup(m => m.OpenFile(nugetConfigPath)).Returns(config.AsStream());
// Act & Assert
ExceptionAssert.Throws<System.Xml.XmlException>(() => new Settings(mockFileSystem.Object));
}
[Fact]
public void UserSetting_CallingGetValuesWithNonExistantSectionReturnsNull()
{
// Arrange
var mockFileSystem = new Mock<IFileSystem>();
var nugetConfigPath = "NuGet.Config";
mockFileSystem.Setup(m => m.FileExists(nugetConfigPath)).Returns(true);
string config = @"<configuration></configuration>";
mockFileSystem.Setup(m => m.OpenFile(nugetConfigPath)).Returns(config.AsStream());
Settings settings = new Settings(mockFileSystem.Object);
// Act
var result = settings.GetValues("DoesNotExisit");
// Assert
Assert.Null(result);
}
[Fact]
public void UserSettings_CallingGetValuesWithSectionWithInvalidAddItemsThrows()
{
// Arrange
var config = @"
<configuration>
<SectionName>
<add Key='key2' Value='value2' />
</SectionName>
</configuration>";
var nugetConfigPath = "NuGet.Config";
var mockFileSystem = new MockFileSystem(@"x:\test");
mockFileSystem.AddFile(nugetConfigPath, config.AsStream());
Settings settings = new Settings(mockFileSystem);
// Act and Assert
ExceptionAssert.Throws<InvalidDataException>(() => settings.GetValues("SectionName"), @"Unable to parse config file 'x:\test\NuGet.Config'.");
}
[Fact]
public void GetValuesThrowsIfSettingsIsMissingKeys()
{
var config = @"<?xml version=""1.0"" encoding=""utf-8""?>
<configuration>
<packageSources>
<add key="""" value=""C:\Temp\Nuget"" />
</packageSources>
<activePackageSource>
<add key=""test2"" value=""C:\Temp\Nuget"" />
</activePackageSource>
</configuration>";
var nugetConfigPath = "NuGet.Config";
var mockFileSystem = new MockFileSystem(@"x:\test");
mockFileSystem.AddFile(nugetConfigPath, config.AsStream());
Settings settings = new Settings(mockFileSystem);
// Act and Assert
ExceptionAssert.Throws<InvalidDataException>(() => settings.GetValues("packageSources"), @"Unable to parse config file 'x:\test\NuGet.Config'.");
}
[Fact]
public void UserSettings_CallingGetValuesWithoutSectionReturnsNull()
{
// Arrange
var mockFileSystem = new Mock<IFileSystem>();
var nugetConfigPath = "NuGet.Config";
mockFileSystem.Setup(m => m.FileExists(nugetConfigPath)).Returns(true);
string config = @"
<configuration>
<SectionName>
<add key='key1' value='value1' />
<add key='key2' value='value2' />
</SectionName>
</configuration>";
mockFileSystem.Setup(m => m.OpenFile(nugetConfigPath)).Returns(config.AsStream());
Settings settings = new Settings(mockFileSystem.Object);
// Act
var result = settings.GetValues("NotTheSectionName");
// Arrange
Assert.Null(result);
}
[Fact]
public void UserSettings_CallingGetValueWithoutSectionReturnsNull()
{
// Arrange
var mockFileSystem = new Mock<IFileSystem>();
var nugetConfigPath = "NuGet.Config";
mockFileSystem.Setup(m => m.FileExists(nugetConfigPath)).Returns(true);
string config = @"
<configuration>
<SectionName>
<add key='key1' value='value1' />
<add key='key2' value='value2' />
</SectionName>
</configuration>";
mockFileSystem.Setup(m => m.OpenFile(nugetConfigPath)).Returns(config.AsStream());
Settings settings = new Settings(mockFileSystem.Object);
// Act
var result = settings.GetValue("NotTheSectionName", "key1");
// Arrange
Assert.Null(result);
}
[Fact]
public void UserSettings_CallingGetValueWithSectionButNoValidKeyReturnsNull()
{
// Arrange
var mockFileSystem = new Mock<IFileSystem>();
var nugetConfigPath = "NuGet.Config";
mockFileSystem.Setup(m => m.FileExists(nugetConfigPath)).Returns(true);
string config = @"
<configuration>
<SectionName>
<add key='key1' value='value1' />
<add key='key2' value='value2' />
</SectionName>
</configuration>";
mockFileSystem.Setup(m => m.OpenFile(nugetConfigPath)).Returns(config.AsStream());
Settings settings = new Settings(mockFileSystem.Object);
// Act
var result = settings.GetValue("SectionName", "key3");
// Assert
Assert.Null(result);
}
[Fact]
public void UserSettings_CallingGetValuesWithSectionReturnsDictionary()
{
// Arrange
var mockFileSystem = new Mock<IFileSystem>();
var nugetConfigPath = "NuGet.Config";
mockFileSystem.Setup(m => m.FileExists(nugetConfigPath)).Returns(true);
string config = @"
<configuration>
<SectionName>
<add key='key1' value='value1' />
<add key='key2' value='value2' />
</SectionName>
</configuration>";
mockFileSystem.Setup(m => m.OpenFile(nugetConfigPath)).Returns(config.AsStream());
Settings settings = new Settings(mockFileSystem.Object);
// Act
var result = settings.GetValues("SectionName");
// Assert
Assert.NotNull(result);
Assert.Equal(2, result.Count);
}
[Fact]
public void UserSettings_CallingGetValueWithSectionAndKeyReturnsValue()
{
// Arrange
var mockFileSystem = new Mock<IFileSystem>();
var nugetConfigPath = "NuGet.Config";
mockFileSystem.Setup(m => m.FileExists(nugetConfigPath)).Returns(true);
string config = @"
<configuration>
<SectionName>
<add key='key1' value='value1' />
</SectionName>
<SectionNameTwo>
<add key='key2' value='value2' />
</SectionNameTwo>
</configuration>";
mockFileSystem.Setup(m => m.OpenFile(nugetConfigPath)).Returns(config.AsStream());
Settings settings = new Settings(mockFileSystem.Object);
// Act
var result1 = settings.GetValue("SectionName", "key1");
var result2 = settings.GetValue("SectionNameTwo", "key2");
// Assert
Assert.Equal("value1", result1);
Assert.Equal("value2", result2);
}
[Fact]
public void UserSettings_CallingSetValueWithEmptySectionNameThrowsException()
{
// Arrange
var mockFileSystem = new Mock<IFileSystem>();
var settings = new Settings(mockFileSystem.Object);
// Act & Assert
ExceptionAssert.Throws<ArgumentException>(() => settings.SetValue("", "SomeKey", "SomeValue"));
}
[Fact]
public void UserSettings_CallingSetValueWithEmptyKeyThrowsException()
{
// Arrange
var mockFileSystem = new Mock<IFileSystem>();
var settings = new Settings(mockFileSystem.Object);
// Act & Assert
ExceptionAssert.Throws<ArgumentException>(() => settings.SetValue("SomeKey", "", "SomeValue"));
}
[Fact]
public void UserSettings_CallingSetValueWillAddSectionIfItDoesNotExist()
{
// Arrange
var mockFileSystem = new Mock<IFileSystem>();
var nugetConfigPath = "NuGet.Config";
mockFileSystem.Setup(m => m.FileExists(nugetConfigPath)).Returns(true);
var ms = new MemoryStream();
mockFileSystem.Setup(m => m.AddFile(nugetConfigPath, It.IsAny<Stream>())).Callback<string, Stream>((path, stream) =>
{
stream.CopyTo(ms);
ms.Seek(0, SeekOrigin.Begin);
});
string config = @"<?xml version=""1.0"" encoding=""utf-8""?>
<configuration>
<SectionName>
<add key=""key"" value=""value"" />
</SectionName>
</configuration>";
mockFileSystem.Setup(m => m.OpenFile(nugetConfigPath)).Returns(config.AsStream());
Settings settings = new Settings(mockFileSystem.Object);
// Act
settings.SetValue("NewSectionName", "key", "value");
// Assert
Assert.Equal(@"<?xml version=""1.0"" encoding=""utf-8""?>
<configuration>
<SectionName>
<add key=""key"" value=""value"" />
</SectionName>
<NewSectionName>
<add key=""key"" value=""value"" />
</NewSectionName>
</configuration>", ms.ReadToEnd());
}
[Fact]
public void UserSettings_CallingSetValueWillAddToSectionIfItExist()
{
// Arrange
var mockFileSystem = new Mock<IFileSystem>();
var nugetConfigPath = "NuGet.Config";
mockFileSystem.Setup(m => m.FileExists(nugetConfigPath)).Returns(true);
var ms = new MemoryStream();
mockFileSystem.Setup(m => m.AddFile(nugetConfigPath, It.IsAny<Stream>())).Callback<string, Stream>((path, stream) =>
{
stream.CopyTo(ms);
ms.Seek(0, SeekOrigin.Begin);
});
string config = @"<?xml version=""1.0"" encoding=""utf-8""?>
<configuration>
<SectionName>
<add key=""key"" value=""value"" />
</SectionName>
</configuration>";
mockFileSystem.Setup(m => m.OpenFile(nugetConfigPath)).Returns(config.AsStream());
Settings settings = new Settings(mockFileSystem.Object);
// Act
settings.SetValue("SectionName", "keyTwo", "valueTwo");
// Assert
Assert.Equal(@"<?xml version=""1.0"" encoding=""utf-8""?>
<configuration>
<SectionName>
<add key=""key"" value=""value"" />
<add key=""keyTwo"" value=""valueTwo"" />
</SectionName>
</configuration>", ms.ReadToEnd());
}
[Fact]
public void UserSettings_CallingSetValueWillOverrideValueIfKeyExists()
{
// Arrange
var mockFileSystem = new Mock<IFileSystem>();
var nugetConfigPath = "NuGet.Config";
mockFileSystem.Setup(m => m.FileExists(nugetConfigPath)).Returns(true);
var ms = new MemoryStream();
mockFileSystem.Setup(m => m.AddFile(nugetConfigPath, It.IsAny<Stream>())).Callback<string, Stream>((path, stream) =>
{
stream.CopyTo(ms);
ms.Seek(0, SeekOrigin.Begin);
});
string config = @"<?xml version=""1.0"" encoding=""utf-8""?>
<configuration>
<SectionName>
<add key=""key"" value=""value"" />
</SectionName>
</configuration>";
mockFileSystem.Setup(m => m.OpenFile(nugetConfigPath)).Returns(config.AsStream());
Settings settings = new Settings(mockFileSystem.Object);
// Act
settings.SetValue("SectionName", "key", "NewValue");
// Assert
Assert.Equal(@"<?xml version=""1.0"" encoding=""utf-8""?>
<configuration>
<SectionName>
<add key=""key"" value=""NewValue"" />
</SectionName>
</configuration>", ms.ReadToEnd());
}
[Fact]
public void UserSettings_CallingSetValuesWithEmptySectionThrowsException()
{
// Arrange
var mockFileSystem = new Mock<IFileSystem>();
var values = new List<KeyValuePair<string, string>>() { new KeyValuePair<string, string>("key", "value") };
var settings = new Settings(mockFileSystem.Object);
// Act & Assert
ExceptionAssert.Throws<ArgumentException>(() => settings.SetValues("", values));
}
[Fact]
public void UserSettings_CallingSetValuesWithNullValuesThrowsException()
{
// Arrange
var mockFileSystem = new Mock<IFileSystem>();
var settings = new Settings(mockFileSystem.Object);
// Act & Assert
ExceptionAssert.Throws<ArgumentNullException>(() => settings.SetValues("Section", null));
}
[Fact]
public void UserSettings_CallingSetValuesWithEmptyKeyThrowsException()
{
// Arrange
var mockFileSystem = new Mock<IFileSystem>();
var values = new List<KeyValuePair<string, string>>() { new KeyValuePair<string, string>("", "value") };
var settings = new Settings(mockFileSystem.Object);
// Act & Assert
ExceptionAssert.Throws<ArgumentException>(() => settings.SetValues("Section", values));
}
[Fact]
public void UserSettings_CallingSetValuseWillAddSectionIfItDoesNotExist()
{
// Arrange
var mockFileSystem = new Mock<IFileSystem>();
var nugetConfigPath = "NuGet.Config";
mockFileSystem.Setup(m => m.FileExists(nugetConfigPath)).Returns(true);
var ms = new MemoryStream();
mockFileSystem.Setup(m => m.AddFile(nugetConfigPath, It.IsAny<Stream>())).Callback<string, Stream>((path, stream) =>
{
stream.CopyTo(ms);
ms.Seek(0, SeekOrigin.Begin);
});
string config = @"<?xml version=""1.0"" encoding=""utf-8""?>
<configuration>
<SectionName>
<add key=""key"" value=""value"" />
</SectionName>
</configuration>";
mockFileSystem.Setup(m => m.OpenFile(nugetConfigPath)).Returns(config.AsStream());
var values = new List<KeyValuePair<string, string>>() { new KeyValuePair<string, string>("key", "value") };
Settings settings = new Settings(mockFileSystem.Object);
// Act
settings.SetValues("NewSectionName", values);
// Assert
Assert.Equal(@"<?xml version=""1.0"" encoding=""utf-8""?>
<configuration>
<SectionName>
<add key=""key"" value=""value"" />
</SectionName>
<NewSectionName>
<add key=""key"" value=""value"" />
</NewSectionName>
</configuration>", ms.ReadToEnd());
}
[Fact]
public void UserSettings_CallingSetValuesWillAddToSectionIfItExist()
{
// Arrange
var mockFileSystem = new Mock<IFileSystem>();
var nugetConfigPath = "NuGet.Config";
mockFileSystem.Setup(m => m.FileExists(nugetConfigPath)).Returns(true);
var ms = new MemoryStream();
mockFileSystem.Setup(m => m.AddFile(nugetConfigPath, It.IsAny<Stream>())).Callback<string, Stream>((path, stream) =>
{
stream.CopyTo(ms);
ms.Seek(0, SeekOrigin.Begin);
});
string config = @"<?xml version=""1.0"" encoding=""utf-8""?>
<configuration>
<SectionName>
<add key=""key"" value=""value"" />
</SectionName>
</configuration>";
mockFileSystem.Setup(m => m.OpenFile(nugetConfigPath)).Returns(config.AsStream());
var values = new List<KeyValuePair<string, string>>() { new KeyValuePair<string, string>("keyTwo", "valueTwo") };
Settings settings = new Settings(mockFileSystem.Object);
// Act
settings.SetValues("SectionName", values);
// Assert
Assert.Equal(@"<?xml version=""1.0"" encoding=""utf-8""?>
<configuration>
<SectionName>
<add key=""key"" value=""value"" />
<add key=""keyTwo"" value=""valueTwo"" />
</SectionName>
</configuration>", ms.ReadToEnd());
}
[Fact]
public void UserSettings_CallingSetValuesWillOverrideValueIfKeyExists()
{
// Arrange
var mockFileSystem = new Mock<IFileSystem>();
var nugetConfigPath = "NuGet.Config";
mockFileSystem.Setup(m => m.FileExists(nugetConfigPath)).Returns(true);
var ms = new MemoryStream();
mockFileSystem.Setup(m => m.AddFile(nugetConfigPath, It.IsAny<Stream>())).Callback<string, Stream>((path, stream) =>
{
stream.CopyTo(ms);
ms.Seek(0, SeekOrigin.Begin);
});
string config = @"<?xml version=""1.0"" encoding=""utf-8""?>
<configuration>
<SectionName>
<add key=""key"" value=""value"" />
</SectionName>
</configuration>";
mockFileSystem.Setup(m => m.OpenFile(nugetConfigPath)).Returns(config.AsStream());
var values = new List<KeyValuePair<string, string>>() { new KeyValuePair<string, string>("key", "NewValue") };
Settings settings = new Settings(mockFileSystem.Object);
// Act
settings.SetValues("SectionName", values);
// Assert
Assert.Equal(@"<?xml version=""1.0"" encoding=""utf-8""?>
<configuration>
<SectionName>
<add key=""key"" value=""NewValue"" />
</SectionName>
</configuration>", ms.ReadToEnd());
}
[Fact]
public void UserSettings_CallingSetValuesWilladdValuesInOrder()
{
// Arrange
var mockFileSystem = new Mock<IFileSystem>();
var nugetConfigPath = "NuGet.Config";
mockFileSystem.Setup(m => m.FileExists(nugetConfigPath)).Returns(true);
var ms = new MemoryStream();
mockFileSystem.Setup(m => m.AddFile(nugetConfigPath, It.IsAny<Stream>())).Callback<string, Stream>((path, stream) =>
{
stream.CopyTo(ms);
ms.Seek(0, SeekOrigin.Begin);
});
string config = @"<?xml version=""1.0"" encoding=""utf-8""?>
<configuration>
<SectionName>
<add key=""key"" value=""Value"" />
</SectionName>
</configuration>";
mockFileSystem.Setup(m => m.OpenFile(nugetConfigPath)).Returns(config.AsStream());
var values = new List<KeyValuePair<string, string>>() { new KeyValuePair<string, string>("key1", "Value1"),
new KeyValuePair<string, string>("key2", "Value2") };
Settings settings = new Settings(mockFileSystem.Object);
// Act
settings.SetValues("SectionName", values);
// Assert
Assert.Equal(@"<?xml version=""1.0"" encoding=""utf-8""?>
<configuration>
<SectionName>
<add key=""key"" value=""Value"" />
<add key=""key1"" value=""Value1"" />
<add key=""key2"" value=""Value2"" />
</SectionName>
</configuration>", ms.ReadToEnd());
}
[Fact]
public void UserSettings_CallingDeleteValueWithEmptyKeyThrowsException()
{
// Arrange
var mockFileSystem = new Mock<IFileSystem>();
var settings = new Settings(mockFileSystem.Object);
// Act & Assert
ExceptionAssert.Throws<ArgumentException>(() => settings.DeleteValue("SomeSection", ""));
}
[Fact]
public void UserSettings_CallingDeleteValueWithEmptySectionThrowsException()
{
// Arrange
var mockFileSystem = new Mock<IFileSystem>();
var settings = new Settings(mockFileSystem.Object);
// Act & Assert
ExceptionAssert.Throws<ArgumentException>(() => settings.DeleteValue("", "SomeKey"));
}
[Fact]
public void UserSettings_CallingDeleteValueWhenSectionNameDoesntExistReturnsFalse()
{
// Arrange
var mockFileSystem = new Mock<IFileSystem>();
var nugetConfigPath = "NuGet.Config";
mockFileSystem.Setup(m => m.FileExists(nugetConfigPath)).Returns(true);
string config = @"<?xml version=""1.0"" encoding=""utf-8""?>
<configuration>
<SectionName>
<add key=""key"" value="""" />
</SectionName>
</configuration>";
mockFileSystem.Setup(m => m.OpenFile(nugetConfigPath)).Returns(config.AsStream());
Settings settings = new Settings(mockFileSystem.Object);
// Act & Assert
Assert.False(settings.DeleteValue("SectionDoesNotExists", "SomeKey"));
}
[Fact]
public void UserSettings_CallingDeleteValueWhenKeyDoesntExistThrowsException()
{
// Arrange
var mockFileSystem = new Mock<IFileSystem>();
var nugetConfigPath = "NuGet.Config";
mockFileSystem.Setup(m => m.FileExists(nugetConfigPath)).Returns(true);
string config = @"<?xml version=""1.0"" encoding=""utf-8""?>
<configuration>
<SectionName>
<add key=""key"" value="""" />
</SectionName>
</configuration>";
mockFileSystem.Setup(m => m.OpenFile(nugetConfigPath)).Returns(config.AsStream());
Settings settings = new Settings(mockFileSystem.Object);
// Act & Assert
Assert.False(settings.DeleteValue("SectionName", "KeyDoesNotExist"));
}
[Fact]
public void UserSettings_CallingDeleteValueWithValidSectionAndKeyDeletesTheEntryAndReturnsTrue()
{
// Arrange
var mockFileSystem = new Mock<IFileSystem>();
var nugetConfigPath = "NuGet.Config";
mockFileSystem.Setup(m => m.FileExists(nugetConfigPath)).Returns(true);
var ms = new MemoryStream();
mockFileSystem.Setup(m => m.AddFile(nugetConfigPath, It.IsAny<Stream>())).Callback<string, Stream>((path, stream) =>
{
stream.CopyTo(ms);
ms.Seek(0, SeekOrigin.Begin);
});
string config = @"<?xml version=""1.0"" encoding=""utf-8""?>
<configuration>
<SectionName>
<add key=""DeleteMe"" value=""value"" />
<add key=""keyNotToDelete"" value=""value"" />
</SectionName>
<SectionName2>
<add key=""key"" value=""value"" />
</SectionName2>
</configuration>";
mockFileSystem.Setup(m => m.OpenFile(nugetConfigPath)).Returns(config.AsStream());
Settings settings = new Settings(mockFileSystem.Object);
// Act & Assert
Assert.True(settings.DeleteValue("SectionName", "DeleteMe"));
Assert.Equal(@"<?xml version=""1.0"" encoding=""utf-8""?>
<configuration>
<SectionName>
<add key=""keyNotToDelete"" value=""value"" />
</SectionName>
<SectionName2>
<add key=""key"" value=""value"" />
</SectionName2>
</configuration>", ms.ReadToEnd());
}
[Fact]
public void UserSettings_CallingDeleteSectionWithEmptySectionThrowsException()
{
// Arrange
var mockFileSystem = new Mock<IFileSystem>();
var settings = new Settings(mockFileSystem.Object);
// Act & Assert
ExceptionAssert.Throws<ArgumentException>(() => settings.DeleteSection(""));
}
[Fact]
public void UserSettings_CallingDeleteSectionWhenSectionNameDoesntExistReturnsFalse()
{
// Arrange
var mockFileSystem = new Mock<IFileSystem>();
var nugetConfigPath = "NuGet.Config";
mockFileSystem.Setup(m => m.FileExists(nugetConfigPath)).Returns(true);
string config = @"<?xml version=""1.0"" encoding=""utf-8""?>
<configuration>
<SectionName>
<add key=""key"" value="""" />
</SectionName>
</configuration>";
mockFileSystem.Setup(m => m.OpenFile(nugetConfigPath)).Returns(config.AsStream());
Settings settings = new Settings(mockFileSystem.Object);
// Act & Assert
Assert.False(settings.DeleteSection("SectionDoesNotExists"));
}
[Fact]
public void UserSettings_CallingDeleteSectionWithValidSectionDeletesTheSectionAndReturnsTrue()
{
// Arrange
var mockFileSystem = new Mock<IFileSystem>();
var nugetConfigPath = "NuGet.Config";
mockFileSystem.Setup(m => m.FileExists(nugetConfigPath)).Returns(true);
var ms = new MemoryStream();
mockFileSystem.Setup(m => m.AddFile(nugetConfigPath, It.IsAny<Stream>())).Callback<string, Stream>((path, stream) =>
{
stream.CopyTo(ms);
ms.Seek(0, SeekOrigin.Begin);
});
string config = @"<?xml version=""1.0"" encoding=""utf-8""?>
<configuration>
<SectionName>
<add key=""DeleteMe"" value=""value"" />
<add key=""keyNotToDelete"" value=""value"" />
</SectionName>
<SectionName2>
<add key=""key"" value=""value"" />
</SectionName2>
</configuration>";
mockFileSystem.Setup(m => m.OpenFile(nugetConfigPath)).Returns(config.AsStream());
Settings settings = new Settings(mockFileSystem.Object);
// Act & Assert
Assert.True(settings.DeleteSection("SectionName"));
Assert.Equal(@"<?xml version=""1.0"" encoding=""utf-8""?>
<configuration>
<SectionName2>
<add key=""key"" value=""value"" />
</SectionName2>
</configuration>", ms.ReadToEnd());
}
/* Extension Methods for Settings Class */
[Fact]
public void UserSettingsExtentions_SetEncryptedValue()
{
// Arrange
var mockFileSystem = new Mock<IFileSystem>();
var nugetConfigPath = "NuGet.Config";
mockFileSystem.Setup(m => m.FileExists(nugetConfigPath)).Returns(true);
var ms = new MemoryStream();
mockFileSystem.Setup(m => m.AddFile(nugetConfigPath, It.IsAny<Stream>())).Callback<string, Stream>((path, stream) =>
{
stream.CopyTo(ms);
ms.Seek(0, SeekOrigin.Begin);
});
string config = @"<?xml version=""1.0"" encoding=""utf-8""?>
<configuration>
<SectionName>
<add key=""key"" value=""value"" />
</SectionName>
</configuration>";
mockFileSystem.Setup(m => m.OpenFile(nugetConfigPath)).Returns(config.AsStream());
Settings settings = new Settings(mockFileSystem.Object);
// Act
settings.SetEncryptedValue("SectionName", "key", "NewValue");
// Assert
Assert.False(ms.ReadToEnd().Contains("NewValue"), "Value Should Be Ecrypted and Base64 encoded.");
}
[Fact]
public void UserSettingsExtentions_GetEncryptedValue()
{
// Arrange
var mockFileSystem = new Mock<IFileSystem>();
var nugetConfigPath = "NuGet.Config";
mockFileSystem.Setup(m => m.FileExists(@"c:\users\bob\appdata\roaming\NuGet\Nuget.Config")).Returns(false);
var ms = new MemoryStream();
mockFileSystem.Setup(m => m.AddFile(nugetConfigPath, It.IsAny<Stream>())).Callback<string, Stream>((path, stream) =>
{
stream.CopyTo(ms);
ms.Seek(0, SeekOrigin.Begin);
});
Settings settings = new Settings(mockFileSystem.Object);
settings.SetEncryptedValue("SectionName", "key", "value");
// Act
var result = settings.GetDecryptedValue("SectionName", "key");
// Assert
Assert.Equal("value", result);
}
[Fact]
public void UserSettingsExtentions_GetDecryptedValueWithEmptyValueReturnsEmptyString()
{
// Arrange
var mockFileSystem = new Mock<IFileSystem>();
var nugetConfigPath = "NuGet.Config";
mockFileSystem.Setup(m => m.FileExists(nugetConfigPath)).Returns(true);
string config = @"<?xml version=""1.0"" encoding=""utf-8""?>
<configuration>
<SectionName>
<add key=""key"" value="""" />
</SectionName>
</configuration>";
mockFileSystem.Setup(m => m.OpenFile(nugetConfigPath)).Returns(config.AsStream());
Settings settings = new Settings(mockFileSystem.Object);
// Act
var result = settings.GetDecryptedValue("SectionName", "key");
// Assert
Assert.Equal(String.Empty, result);
}
[Fact]
public void UserSettingsExtentions_GetDecryptedValueWithNoKeyReturnsNull()
{
// Arrange
var mockFileSystem = new Mock<IFileSystem>();
var nugetConfigPath = "NuGet.Config";
mockFileSystem.Setup(m => m.FileExists(nugetConfigPath)).Returns(true);
string config = @"<?xml version=""1.0"" encoding=""utf-8""?>
<configuration>
<SectionName>
<add key=""key"" value="""" />
</SectionName>
</configuration>";
mockFileSystem.Setup(m => m.OpenFile(nugetConfigPath)).Returns(config.AsStream());
Settings settings = new Settings(mockFileSystem.Object);
// Act
var result = settings.GetDecryptedValue("SectionName", "NoKeyByThatName");
// Assert
Assert.Null(result);
}
}
}
| apache-2.0 |
ox-it/ords-database-api | src/test/java/uk/ac/ox/it/ords/api/database/resources/TableTestComplex.java | 3024 | /*
* Copyright 2015 University of Oxford
*
* 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 uk.ac.ox.it.ords.api.database.resources;
import static org.junit.Assert.assertEquals;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import javax.ws.rs.core.Response;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.cxf.jaxrs.ext.multipart.Attachment;
import org.apache.cxf.jaxrs.ext.multipart.ContentDisposition;
import org.apache.cxf.jaxrs.ext.multipart.MultipartBody;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import uk.ac.ox.it.ords.api.database.data.Row;
public class TableTestComplex extends AbstractDatabaseTestRunner{
private String dbID;
@Before
public void setupTable() throws FileNotFoundException{
loginBasicUser();
File file = new File(getClass().getResource("/mondial.accdb").getFile());
FileInputStream inputStream = new FileInputStream(file);
ContentDisposition cd = new ContentDisposition("attachment;filename=mondial.accdb");
Attachment att = new Attachment("dataFile", inputStream, cd);
WebClient client = getClient(false);
client.type("multipart/form-data");
Response response = client.path("/"+logicalDatabaseId+"/data/test").post(new MultipartBody(att));
assertEquals(201, response.getStatus());
String path = response.getLocation().getPath();
dbID = path.substring(path.lastIndexOf('/')+1);
DatabaseReference r = new DatabaseReference(Integer.parseInt(dbID), false);
AbstractResourceTest.databases.add(r);
}
@After
public void tearDownTable() throws Exception{
logout();
}
@Test
public void deleteRowWithConstraint() throws Exception{
loginBasicUser();
assertEquals(200, getClient(true).path("/"+dbID+"/tabledata/country").get().getStatus());
//
// Delete it
//
assertEquals(409, getClient(true).path("/"+dbID+"/tabledata/country").query("primaryKey", "Code").query("primaryKeyValue", "AFG").delete().getStatus());
//logout();
}
@Test
public void insertRowWithPKandAutonumber() throws Exception{
loginBasicUser();
assertEquals(200, getClient(true).path("/"+dbID+"/tabledata/city").get().getStatus());
//
// Create the row
//
Row row = new Row();
row.columnNames = new String[]{"CityName", "Population"};
row.values = new String[]{"XXXX","XXXX"};
Response response = getClient(true).path("/"+dbID+"/tabledata/city").post(row);
assertEquals(201, response.getStatus());
//logout();
}
}
| apache-2.0 |
taimir/dashboard | src/app/frontend/replicasetdetail/replicasetdetail_module.js | 1458 | // Copyright 2015 Google Inc. 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.
import componentsModule from 'common/components/components_module';
import chromeModule from 'chrome/chrome_module';
import eventsModule from 'events/events_module';
import filtersModule from 'common/filters/filters_module';
import stateConfig from './replicasetdetail_stateconfig';
import {replicaSetInfoComponent} from './replicasetinfo_component';
/**
* Angular module for the Replica Set details view.
*
* The view shows detailed view of a Replica Set.
*/
export default angular
.module(
'kubernetesDashboard.replicaSetDetail',
[
'ngMaterial',
'ngResource',
'ui.router',
componentsModule.name,
chromeModule.name,
filtersModule.name,
eventsModule.name,
])
.config(stateConfig)
.component('kdReplicaSetInfo', replicaSetInfoComponent);
| apache-2.0 |
NymphWeb/nymph | com/nymph/annotation/POST.java | 487 | package com.nymph.annotation;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
* Http协议的Post请求方式
* @author LiuYang
* @author LiangTianDong
* @date 2017年10月22日下午3:18:25
*/
@Retention(RUNTIME)
@Target(METHOD)
@Request
public @interface POST {
/**
* url的路径
* @return
*/
String value() default "";
}
| apache-2.0 |
trasa/aws-sdk-java | aws-java-sdk-ecs/src/main/java/com/amazonaws/services/ecs/model/transform/SubmitTaskStateChangeResultJsonUnmarshaller.java | 2958 | /*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amazonaws.services.ecs.model.transform;
import java.util.Map;
import java.util.Map.Entry;
import com.amazonaws.services.ecs.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* SubmitTaskStateChangeResult JSON Unmarshaller
*/
public class SubmitTaskStateChangeResultJsonUnmarshaller implements
Unmarshaller<SubmitTaskStateChangeResult, JsonUnmarshallerContext> {
public SubmitTaskStateChangeResult unmarshall(
JsonUnmarshallerContext context) throws Exception {
SubmitTaskStateChangeResult submitTaskStateChangeResult = new SubmitTaskStateChangeResult();
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null)
token = context.nextToken();
if (token == VALUE_NULL)
return null;
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
if (context.testExpression("acknowledgment", targetDepth)) {
context.nextToken();
submitTaskStateChangeResult
.setAcknowledgment(StringJsonUnmarshaller
.getInstance().unmarshall(context));
}
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null
|| context.getLastParsedParentElement().equals(
currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth)
break;
}
}
token = context.nextToken();
}
return submitTaskStateChangeResult;
}
private static SubmitTaskStateChangeResultJsonUnmarshaller instance;
public static SubmitTaskStateChangeResultJsonUnmarshaller getInstance() {
if (instance == null)
instance = new SubmitTaskStateChangeResultJsonUnmarshaller();
return instance;
}
}
| apache-2.0 |
nirvanesque/g5k-api | config/initializers/mime_types.rb | 998 | # Copyright (c) 2009-2011 Cyril Rohr, INRIA Rennes - Bretagne Atlantique
#
# 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.
# Be sure to restart your server when you modify this file.
# Add new mime types for use in respond_to blocks:
# Mime::Type.register "application/vnd.grid5000+json", :g5kjson
Mime::Type.register "application/vnd.grid5000.collection+json", :g5kcollectionjson
Mime::Type.register "application/vnd.grid5000.item+json", :g5kitemjson
# Mime::Type.register_alias "text/html", :iphone
| apache-2.0 |
zhaowenjian/CCCourse | runtime/kv/USER_TOKEN_aes_key.php | 40 | <?php //hsnfgZ7YQAP7yqVfc0WO17c04G4QXCSl | apache-2.0 |
dicentim/rockr0lla | master-module/util/src/main/java/org/rdform/ConfigurationUtil.java | 1156 | /*
* project: RMF-0RM
* date: 26.11.12
* file : ConfigurationUtil.java
* encoding: UTF-8
*/
package org.rdform;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.XMLConfiguration;
import java.net.URL;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* @author Mihai
* @version 1.00-SNAPSHOT
* @since 1.00-SNAPSHOT
*/
public final class ConfigurationUtil {
private ConfigurationUtil() {
// UNIMPLEMENTED
}
public static XMLConfiguration getConfiguration(String fileName) throws ConfigurationException {
checkNotNull(fileName, "The filename can not be null.");
final ClassLoader classLoader = ConfigurationUtil.class.getClassLoader();
final URL resource = classLoader.getResource(fileName);
if (resource == null) {
// stop the tests if there is no configuration
throw new IllegalStateException("The persistence-conf.xml can not be located in the classpath.");
}
final XMLConfiguration configuration = new XMLConfiguration(resource);
return configuration;
}
}
| apache-2.0 |
Birdrock/client-javascript | kubernetes/test/model/V1beta1Deployment.spec.js | 3130 | /**
* Kubernetes
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: v1.5.1-660c2a2
*
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*
*/
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD.
define(['expect.js', '../../src/index'], factory);
} else if (typeof module === 'object' && module.exports) {
// CommonJS-like environments that support module.exports, like Node.
factory(require('expect.js'), require('../../src/index'));
} else {
// Browser globals (root is window)
factory(root.expect, root.KubernetesJsClient);
}
}(this, function(expect, KubernetesJsClient) {
'use strict';
var instance;
beforeEach(function() {
instance = new KubernetesJsClient.V1beta1Deployment();
});
var getProperty = function(object, getter, property) {
// Use getter method if present; otherwise, get the property directly.
if (typeof object[getter] === 'function')
return object[getter]();
else
return object[property];
}
var setProperty = function(object, setter, property, value) {
// Use setter method if present; otherwise, set the property directly.
if (typeof object[setter] === 'function')
object[setter](value);
else
object[property] = value;
}
describe('V1beta1Deployment', function() {
it('should create an instance of V1beta1Deployment', function() {
// uncomment below and update the code to test V1beta1Deployment
//var instane = new KubernetesJsClient.V1beta1Deployment();
//expect(instance).to.be.a(KubernetesJsClient.V1beta1Deployment);
});
it('should have the property apiVersion (base name: "apiVersion")', function() {
// uncomment below and update the code to test the property apiVersion
//var instane = new KubernetesJsClient.V1beta1Deployment();
//expect(instance).to.be();
});
it('should have the property kind (base name: "kind")', function() {
// uncomment below and update the code to test the property kind
//var instane = new KubernetesJsClient.V1beta1Deployment();
//expect(instance).to.be();
});
it('should have the property metadata (base name: "metadata")', function() {
// uncomment below and update the code to test the property metadata
//var instane = new KubernetesJsClient.V1beta1Deployment();
//expect(instance).to.be();
});
it('should have the property spec (base name: "spec")', function() {
// uncomment below and update the code to test the property spec
//var instane = new KubernetesJsClient.V1beta1Deployment();
//expect(instance).to.be();
});
it('should have the property status (base name: "status")', function() {
// uncomment below and update the code to test the property status
//var instane = new KubernetesJsClient.V1beta1Deployment();
//expect(instance).to.be();
});
});
}));
| apache-2.0 |
lastaflute/lastaflute-test-fortress | src/main/java/org/docksidestage/remote/maihama/showbase/wx/remogen/suffix/toponly/RemoteWxRemogenSuffixToponlyReturn.java | 1950 | /*
* Copyright 2015-2021 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.docksidestage.remote.maihama.showbase.wx.remogen.suffix.toponly;
import org.lastaflute.core.util.Lato;
import org.lastaflute.web.validation.Required;
/**
* The bean class as return for remote API of GET /wx/remogen/suffix/toponly.
* @author FreeGen
*/
public class RemoteWxRemogenSuffixToponlyReturn extends org.docksidestage.bizfw.remoteapi.AbstractListGetReturn {
/** The property of resortName. */
@Required
public String resortName;
/** The property of resortPark. (NullAllowed) */
@javax.validation.Valid
public ResortParkPart resortPark;
/**
* The part class of ResortParkPart.
* @author FreeGen
*/
public static class ResortParkPart {
/** The property of parkName. */
@Required
public String parkName;
/** The property of showStages. (NullAllowed) */
@javax.validation.Valid
public org.eclipse.collections.api.list.ImmutableList<ShowStagePart> showStages;
/**
* The part class of ShowStagePart.
* @author FreeGen
*/
public static class ShowStagePart {
/** The property of stageName. */
@Required
public String stageName;
}
}
@Override
public String toString() {
return Lato.string(this);
}
}
| apache-2.0 |
matrix-org/matrix-react-sdk | src/accessibility/roving/types.ts | 698 | /*
Copyright 2020 The Matrix.org Foundation C.I.C.
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 { RefObject } from "react";
export type Ref = RefObject<HTMLElement>;
export type FocusHandler = () => void;
| apache-2.0 |
raulv/license-audit | src/main/java/org/itcollege/valge/licenseaudit/model/Scope.java | 278 | package org.itcollege.valge.licenseaudit.model;
public class Scope {
public final String name;
public final boolean isBundled;
public int dependencyCount = 0;
public Scope(String name, boolean isBundled) {
this.name = name;
this.isBundled = isBundled;
}
}
| apache-2.0 |
XGe1991/myProject | src/public/libs/umeditor-php/umeditor.config.js | 10494 | /**
* umeditor完整配置项
* 可以在这里配置整个编辑器的特性
*/
/**************************提示********************************
* 所有被注释的配置项均为UEditor默认值。
* 修改默认配置请首先确保已经完全明确该参数的真实用途。
* 主要有两种修改方案,一种是取消此处注释,然后修改成对应参数;另一种是在实例化编辑器时传入对应参数。
* 当升级编辑器时,可直接使用旧版配置文件替换新版配置文件,不用担心旧版配置文件中因缺少新功能所需的参数而导致脚本报错。
**************************提示********************************/
(function () {
/**
* 编辑器资源文件根路径。它所表示的含义是:以编辑器实例化页面为当前路径,指向编辑器资源文件(即dialog等文件夹)的路径。
* 鉴于很多同学在使用编辑器的时候出现的种种路径问题,此处强烈建议大家使用"相对于网站根目录的相对路径"进行配置。
* "相对于网站根目录的相对路径"也就是以斜杠开头的形如"/myProject/umeditor/"这样的路径。
* 如果站点中有多个不在同一层级的页面需要实例化编辑器,且引用了同一UEditor的时候,此处的URL可能不适用于每个页面的编辑器。
* 因此,UEditor提供了针对不同页面的编辑器可单独配置的根路径,具体来说,在需要实例化编辑器的页面最顶部写上如下代码即可。当然,需要令此处的URL等于对应的配置。
* window.UMEDITOR_HOME_URL = "/xxxx/xxxx/";
*/
var URL = window.UMEDITOR_HOME_URL || (function(){
function PathStack() {
this.documentURL = self.document.URL || self.location.href;
this.separator = '/';
this.separatorPattern = /\\|\//g;
this.currentDir = './';
this.currentDirPattern = /^[.]\/]/;
this.path = this.documentURL;
this.stack = [];
this.push( this.documentURL );
}
PathStack.isParentPath = function( path ){
return path === '..';
};
PathStack.hasProtocol = function( path ){
return !!PathStack.getProtocol( path );
};
PathStack.getProtocol = function( path ){
var protocol = /^[^:]*:\/*/.exec( path );
return protocol ? protocol[0] : null;
};
PathStack.prototype = {
push: function( path ){
this.path = path;
update.call( this );
parse.call( this );
return this;
},
getPath: function(){
return this + "";
},
toString: function(){
return this.protocol + ( this.stack.concat( [''] ) ).join( this.separator );
}
};
function update() {
var protocol = PathStack.getProtocol( this.path || '' );
if( protocol ) {
//根协议
this.protocol = protocol;
//local
this.localSeparator = /\\|\//.exec( this.path.replace( protocol, '' ) )[0];
this.stack = [];
} else {
protocol = /\\|\//.exec( this.path );
protocol && (this.localSeparator = protocol[0]);
}
}
function parse(){
var parsedStack = this.path.replace( this.currentDirPattern, '' );
if( PathStack.hasProtocol( this.path ) ) {
parsedStack = parsedStack.replace( this.protocol , '');
}
parsedStack = parsedStack.split( this.localSeparator );
parsedStack.length = parsedStack.length - 1;
for(var i= 0,tempPath,l=parsedStack.length,root = this.stack;i<l;i++){
tempPath = parsedStack[i];
if(tempPath){
if( PathStack.isParentPath( tempPath ) ) {
root.pop();
} else {
root.push( tempPath );
}
}
}
}
var currentPath = document.getElementsByTagName('script');
currentPath = currentPath[ currentPath.length -1 ].src;
return new PathStack().push( currentPath ) + "";
})();
/**
* 配置项主体。注意,此处所有涉及到路径的配置别遗漏URL变量。
*/
window.UMEDITOR_CONFIG = {
//为编辑器实例添加一个路径,这个不能被注释
UMEDITOR_HOME_URL : URL
//图片上传配置区
,imageUrl:URL+"php/imageUp.php" //图片上传提交地址
,imagePath:URL + "php/" //图片修正地址,引用了fixedImagePath,如有特殊需求,可自行配置
,imageFieldName:"upfile" //图片数据的key,若此处修改,需要在后台对应文件修改对应参数
//工具栏上的所有的功能按钮和下拉框,可以在new编辑器的实例时选择自己需要的从新定义 emotion image video | map
,toolbar:[
'source | undo redo | bold italic underline strikethrough | superscript subscript | forecolor backcolor | removeformat |',
'insertorderedlist insertunorderedlist | selectall cleardoc paragraph | fontfamily fontsize' ,
'| justifyleft justifycenter justifyright justifyjustify |',
'link unlink |','| horizontal print preview fullscreen', 'drafts', 'formula'
]
//语言配置项,默认是zh-cn。有需要的话也可以使用如下这样的方式来自动多语言切换,当然,前提条件是lang文件夹下存在对应的语言文件:
//lang值也可以通过自动获取 (navigator.language||navigator.browserLanguage ||navigator.userLanguage).toLowerCase()
//,lang:"zh-cn"
//,langPath:URL +"lang/"
//ie下的链接自动监测
//,autourldetectinie:false
//主题配置项,默认是default。有需要的话也可以使用如下这样的方式来自动多主题切换,当然,前提条件是themes文件夹下存在对应的主题文件:
//现有如下皮肤:default
//,theme:'default'
//,themePath:URL +"themes/"
//针对getAllHtml方法,会在对应的head标签中增加该编码设置。
//,charset:"utf-8"
//常用配置项目
,isShow : true //默认显示编辑器
//,initialContent:'欢迎使用UMEDITOR!' //初始化编辑器的内容,也可以通过textarea/script给值,看官网例子
//,initialFrameWidth:500 //初始化编辑器宽度,默认500
//,initialFrameHeight:500 //初始化编辑器高度,默认500
,autoClearinitialContent:false //是否自动清除编辑器初始内容,注意:如果focus属性设置为true,这个也为真,那么编辑器一上来就会触发导致初始化的内容看不到了
//,textarea:'editorValue' // 提交表单时,服务器获取编辑器提交内容的所用的参数,多实例时可以给容器name属性,会将name给定的值最为每个实例的键值,不用每次实例化的时候都设置这个值
,focus:true //初始化时,是否让编辑器获得焦点true或false
//,autoClearEmptyNode : true //getContent时,是否删除空的inlineElement节点(包括嵌套的情况)
//,fullscreen : false //是否开启初始化时即全屏,默认关闭
//,readonly : false //编辑器初始化结束后,编辑区域是否是只读的,默认是false
,zIndex : 2500 //编辑器层级的基数,默认是900
//如果自定义,最好给p标签如下的行高,要不输入中文时,会有跳动感
//注意这里添加的样式,最好放在.edui-editor-body .edui-body-container这两个的下边,防止跟页面上css冲突
//,initialStyle:'.edui-editor-body .edui-body-container p{line-height:1em}'
,autoSyncData:true //自动同步编辑器要提交的数据
//,emotionLocalization:false //是否开启表情本地化,默认关闭。若要开启请确保emotion文件夹下包含官网提供的images表情文件夹
//,allHtmlEnabled:false //提交到后台的数据是否包含整个html字符串
//fontfamily
//字体设置
,'fontfamily':[
{ name: 'songti', val: '宋体,SimSun'},
{ name: 'yahei', val: '微软雅黑,Microsoft YaHei'},
{ name: 'kaiti', val: '楷体,楷体_GB2312, SimKai'},
{ name: 'heiti', val: '黑体, SimHei'},
{ name: 'lishu', val: '隶书, SimLi'},
{ name: 'andaleMono', val: 'andale mono'},
{ name: 'arial', val: 'arial, helvetica,sans-serif'},
{ name: 'arialBlack', val: 'arial black,avant garde'},
{ name: 'comicSansMs', val: 'comic sans ms'},
{ name: 'impact', val: 'impact,chicago'},
{ name: 'timesNewRoman', val: 'times new roman'}
]
//fontsize
//字号
,'fontsize':[12, 14, 16, 18, 20, 24, 36,48]
//paragraph
//段落格式 值留空时支持多语言自动识别,若配置,则以配置值为准
//,'paragraph':{'p':'', 'h1':'', 'h2':'', 'h3':'', 'h4':'', 'h5':'', 'h6':''}
//undo
//可以最多回退的次数,默认20
//,maxUndoCount:20
//当输入的字符数超过该值时,保存一次现场
//,maxInputCount:1
//imageScaleEnabled
// 是否允许点击文件拖拽改变大小,默认true
//,imageScaleEnabled:true
//dropFileEnabled
// 是否允许拖放图片到编辑区域,上传并插入,默认true
//,dropFileEnabled:true
//pasteImageEnabled
// 是否允许粘贴QQ截屏,上传并插入,默认true
//,pasteImageEnabled:true
//autoHeightEnabled
// 是否自动长高,默认true
//,autoHeightEnabled:true
//autoFloatEnabled
//是否保持toolbar的位置不动,默认true
//,autoFloatEnabled:true
//浮动时工具栏距离浏览器顶部的高度,用于某些具有固定头部的页面
//,topOffset:30
//填写过滤规则
//,filterRules: {}
};
})();
| apache-2.0 |
frreiss/tensorflow-fred | tensorflow/python/saved_model/registration.py | 3714 | # Copyright 2021 The TensorFlow 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.
# ==============================================================================
"""Serialization Registration for SavedModel.
revived_types registration will be migrated to this infrastructure.
"""
from tensorflow.python.util import tf_inspect
_CLASS_REGISTRY = {} # string registered name -> (predicate, class)
_REGISTERED_NAMES = []
def get_registered_name(obj):
for name in reversed(_REGISTERED_NAMES):
predicate, cls = _CLASS_REGISTRY[name]
if not predicate and type(obj) == cls: # pylint: disable=unidiomatic-typecheck
return name
if predicate and predicate(obj):
return name
return None
def get_registered_class(registered_name):
try:
return _CLASS_REGISTRY[registered_name][1]
except KeyError:
return None
def register_serializable(package="Custom", name=None, predicate=None):
"""Decorator for registering a serializable class.
THIS METHOD IS STILL EXPERIMENTAL AND MAY CHANGE AT ANY TIME.
Registered classes will be saved with a name generated by combining the
`package` and `name` arguments. When loading a SavedModel, modules saved with
this registered name will be created using the `_deserialize_from_proto`
method.
By default, only direct instances of the registered class will be saved/
restored with the `serialize_from_proto`/`deserialize_from_proto` methods. To
extend the registration to subclasses, use the `predicate argument`:
```python
class A(tf.Module):
pass
register_serializable(
package="Example", predicate=lambda obj: isinstance(obj, A))(A)
```
Args:
package: The package that this class belongs to.
name: The name to serialize this class under in this package. If None, the
class's name will be used.
predicate: An optional function that takes a single Trackable argument, and
determines whether that object should be serialized with this `package`
and `name`. The default predicate checks whether the object's type exactly
matches the registered class. Predicates are executed in the reverse order
that they are added (later registrations are checked first).
Returns:
A decorator that registers the decorated class with the passed names and
predicate.
Raises:
ValueError if predicate is not callable.
"""
if predicate is not None and not callable(predicate):
raise ValueError("The `predicate` passed to registered_serializable "
"must be callable.")
def decorator(arg):
"""Registers a class with the serialization framework."""
if not tf_inspect.isclass(arg):
raise ValueError(
"Registered serializable must be a class: {}".format(arg))
class_name = name if name is not None else arg.__name__
registered_name = package + "." + class_name
if registered_name in _CLASS_REGISTRY:
raise ValueError("{} has already been registered to {}".format(
registered_name, _CLASS_REGISTRY[registered_name]))
_CLASS_REGISTRY[registered_name] = (predicate, arg)
_REGISTERED_NAMES.append(registered_name)
return arg
return decorator
| apache-2.0 |
EdwinVW/pitstop | src/WebApp/ViewModels/VehicleManagementOfflineViewModel.cs | 91 | namespace Pitstop.WebApp.ViewModels;
public class VehicleManagementOfflineViewModel
{
} | apache-2.0 |
sdgdsffdsfff/appleframework | apple-web/src/main/java/com/appleframework/web/freemarker/directive/CheckboxDirective.java | 3894 | package com.appleframework.web.freemarker.directive;
import java.io.IOException;
import java.io.Writer;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import com.appleframework.web.freemarker.util.DirectiveUtil;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
@Component("checkboxDirective")
public class CheckboxDirective implements TemplateDirectiveModel {
public static final String TAG_NAME = "checkbox";
private static final String NAME_PARAMETER_NAME = "name";
private static final String VALUE_PARAMETER_NAME = "value";
private static final String FIELD_VALUE_PARAMETER_NAME = "fieldValue";
private static final String CSS_CLASS_PARAMETER_NAME = "cssClass";
private static final String CSS_STYLE_PARAMETER_NAME = "cssStyle";
private static final String DISABLED_PARAMETER_NAME = "disabled";
private static final String READONLY_PARAMETER_NAME = "readonly";
private static final String TABINDEX_PARAMETER_NAME = "tabindex";
private static final String ID_PARAMETER_NAME = "id";
private static final String TITLE_PARAMETER_NAME = "title";
@SuppressWarnings({ "unchecked", "rawtypes" })
public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
String id = DirectiveUtil.getStringParameter(ID_PARAMETER_NAME, params);
String name = DirectiveUtil.getStringParameter(NAME_PARAMETER_NAME, params);
String fieldValue = DirectiveUtil.getStringParameter(FIELD_VALUE_PARAMETER_NAME, params);
String cssClass = DirectiveUtil.getStringParameter(CSS_CLASS_PARAMETER_NAME, params);
String cssStyle = DirectiveUtil.getStringParameter(CSS_STYLE_PARAMETER_NAME, params);
String title = DirectiveUtil.getStringParameter(TITLE_PARAMETER_NAME, params);
String tabindex = DirectiveUtil.getStringParameter(TABINDEX_PARAMETER_NAME, params);
Boolean value = DirectiveUtil.getBooleanParameter(VALUE_PARAMETER_NAME, params);
Boolean disabled = DirectiveUtil.getBooleanParameter(DISABLED_PARAMETER_NAME, params);
Boolean readonly = DirectiveUtil.getBooleanParameter(READONLY_PARAMETER_NAME, params);
if (id == null) {
id = name.replace(".", "_");
}
if (name == null) {
name = "";
}
if (fieldValue == null) {
fieldValue = "true";
}
if (value == null) {
value = false;
}
if (disabled == null) {
disabled = false;
}
if (readonly == null) {
readonly = false;
}
Writer out = env.getOut();
StringBuffer stringBuffer = new StringBuffer("<input type=\"checkbox\" name=\"" + name + "\" value=\"" + fieldValue + "\"");
if (StringUtils.isNotEmpty(id)) {
stringBuffer.append(" id=\"" + id + "\"");
}
if (StringUtils.isNotEmpty(cssClass)) {
stringBuffer.append(" class=\"" + cssClass + "\"");
}
if (StringUtils.isNotEmpty(cssStyle)) {
stringBuffer.append(" style=\"" + cssStyle + "\"");
}
if (StringUtils.isNotEmpty(title)) {
stringBuffer.append(" title=\"" + title + "\"");
}
if (StringUtils.isNotEmpty(tabindex)) {
stringBuffer.append(" tabindex=\"" + title + "\"");
}
if (value) {
stringBuffer.append(" checked=\"checked\"");
}
if (disabled) {
stringBuffer.append(" disabled=\"disabled\"");
}
if (readonly) {
stringBuffer.append(" readonly=\"readonly\"");
}
stringBuffer.append(" /><input type=\"hidden\" id=\"__checkbox_" + id + "\" name=\"__checkbox_" + name + "\" value=\"" + fieldValue + "\"");
if (disabled) {
stringBuffer.append(" disabled=\"disabled\"");
}
stringBuffer.append(" />");
out.write(stringBuffer.toString());
}
} | apache-2.0 |
imasahiro/armeria | core/src/main/java/com/linecorp/armeria/server/HttpHeaderPathMapping.java | 9808 | /*
* Copyright 2017 LINE Corporation
*
* LINE Corporation 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:
*
* https://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.linecorp.armeria.server;
import static java.util.Objects.requireNonNull;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.StringJoiner;
import com.google.common.base.Joiner;
import com.google.common.base.MoreObjects;
import com.google.common.collect.ImmutableList;
import com.linecorp.armeria.common.HttpMethod;
import com.linecorp.armeria.common.HttpStatus;
import com.linecorp.armeria.common.MediaType;
/**
* A {@link PathMapping} based on {@link HttpMethod} and {@link MediaType}.
*/
final class HttpHeaderPathMapping implements PathMapping {
private static final List<MediaType> ANY_TYPE = ImmutableList.of(MediaType.ANY_TYPE);
private static final Joiner loggerNameJoiner = Joiner.on('_');
private static final Joiner meterTagJoiner = Joiner.on(',');
private final PathMapping pathStringMapping;
private final Set<HttpMethod> supportedMethods;
private final List<MediaType> consumeTypes;
private final List<MediaType> produceTypes;
private final String loggerName;
private final String meterTag;
private final int complexity;
HttpHeaderPathMapping(PathMapping pathStringMapping, Set<HttpMethod> supportedMethods,
List<MediaType> consumeTypes, List<MediaType> produceTypes) {
this.pathStringMapping = requireNonNull(pathStringMapping, "pathStringMapping");
this.supportedMethods = requireNonNull(supportedMethods, "supportedMethods");
this.consumeTypes = requireNonNull(consumeTypes, "consumeTypes");
this.produceTypes = requireNonNull(produceTypes, "produceTypes");
loggerName = generateLoggerName(pathStringMapping.loggerName(),
supportedMethods, consumeTypes, produceTypes);
meterTag = generateMeterTag(pathStringMapping.meterTag(),
supportedMethods, consumeTypes, produceTypes);
// Starts with 1 due to the HTTP method mapping.
int complexity = 1;
if (!consumeTypes.isEmpty()) {
complexity += 2;
}
if (!produceTypes.isEmpty()) {
complexity += 4;
}
this.complexity = complexity;
}
@Override
public PathMappingResult apply(PathMappingContext mappingCtx) {
final PathMappingResult result = pathStringMapping.apply(mappingCtx);
if (!result.isPresent()) {
return PathMappingResult.empty();
}
// We need to check the method at the last in order to return '405 Method Not Allowed'.
if (!supportedMethods.contains(mappingCtx.method())) {
// '415 Unsupported Media Type' and '406 Not Acceptable' is more specific than
// '405 Method Not Allowed'. So 405 would be set if there is no status code set before.
if (!mappingCtx.delayedThrowable().isPresent()) {
mappingCtx.delayThrowable(HttpStatusException.of(HttpStatus.METHOD_NOT_ALLOWED));
}
return PathMappingResult.empty();
}
if (!consumeTypes.isEmpty()) {
final MediaType type = mappingCtx.consumeType();
boolean found = false;
if (type != null) {
for (MediaType mediaType : consumeTypes) {
found = type.belongsTo(mediaType);
if (found) {
break;
}
}
}
if (!found) {
mappingCtx.delayThrowable(HttpStatusException.of(HttpStatus.UNSUPPORTED_MEDIA_TYPE));
return PathMappingResult.empty();
}
}
// If a request does not have 'Accept' header, it would be handled the same as 'Accept: */*'.
// So there is a '*/*' at least in the 'mappingCtx.produceTypes()' if the virtual host supports
// the media type negotiation.
final List<MediaType> types = mappingCtx.produceTypes();
if (types == null) {
// Media type negotiation is not supported on this virtual host.
return result;
}
// Also, the missing '@ProduceTypes' would be handled the same as '@ProduceTypes({"*/*"})'.
final List<MediaType> producibleTypes = produceTypes.isEmpty() ? ANY_TYPE : produceTypes;
for (MediaType produceType : producibleTypes) {
for (int i = 0; i < types.size(); i++) {
if (produceType.belongsTo(types.get(i))) {
// To early stop path mapping traversal,
// we set the score as the best score when the index is 0.
result.setScore(i == 0 ? PathMappingResult.HIGHEST_SCORE : -1 * i);
if (!produceTypes.isEmpty()) {
result.setNegotiatedProduceType(produceType);
}
return result;
}
}
}
mappingCtx.delayThrowable(HttpStatusException.of(HttpStatus.NOT_ACCEPTABLE));
return PathMappingResult.empty();
}
@Override
public Set<String> paramNames() {
return pathStringMapping.paramNames();
}
@Override
public String loggerName() {
return loggerName;
}
@Override
public String meterTag() {
return meterTag;
}
@Override
public Optional<String> exactPath() {
return pathStringMapping.exactPath();
}
@Override
public Optional<String> prefix() {
return pathStringMapping.prefix();
}
@Override
public Optional<String> triePath() {
return pathStringMapping.triePath();
}
@Override
public int complexity() {
return complexity;
}
public Set<HttpMethod> supportedMethods() {
return supportedMethods;
}
public List<MediaType> consumeTypes() {
return consumeTypes;
}
public List<MediaType> produceTypes() {
return produceTypes;
}
@Override
public String toString() {
final StringBuilder buf = new StringBuilder();
buf.append('[');
buf.append(pathStringMapping);
buf.append(", ");
buf.append(MoreObjects.toStringHelper("")
.add("supportedMethods", supportedMethods)
.add("consumeTypes", consumeTypes)
.add("produceTypes", produceTypes));
buf.append(']');
return buf.toString();
}
private static String generateLoggerName(String prefix, Set<HttpMethod> supportedMethods,
List<MediaType> consumeTypes, List<MediaType> produceTypes) {
final StringJoiner name = new StringJoiner(".");
name.add(prefix);
name.add(loggerNameJoiner.join(supportedMethods.stream().sorted().iterator()));
// The following three cases should be different to each other.
// Each name would be produced as follows:
//
// consumeTypes: text/plain, text/html -> consumes.text_plain.text_html
// consumeTypes: text/plain, produceTypes: text/html -> consumes.text_plain.produces.text_html
// produceTypes: text/plain, text/html -> produces.text_plain.text_html
if (!consumeTypes.isEmpty()) {
name.add("consumes");
consumeTypes.forEach(e -> name.add(e.type() + '_' + e.subtype()));
}
if (!produceTypes.isEmpty()) {
name.add("produces");
produceTypes.forEach(e -> name.add(e.type() + '_' + e.subtype()));
}
return name.toString();
}
private static String generateMeterTag(String parentTag, Set<HttpMethod> supportedMethods,
List<MediaType> consumeTypes, List<MediaType> produceTypes) {
final StringJoiner name = new StringJoiner(",");
name.add(parentTag);
name.add("methods:" + meterTagJoiner.join(supportedMethods.stream().sorted().iterator()));
// The following three cases should be different to each other.
// Each name would be produced as follows:
//
// consumeTypes: text/plain, text/html -> "consumes:text/plain,text/html"
// consumeTypes: text/plain, produceTypes: text/html -> "consumes:text/plain,produces:text/html"
// produceTypes: text/plain, text/html -> "produces:text/plain,text/html"
addMediaTypes(name, "consumes", consumeTypes);
addMediaTypes(name, "produces", produceTypes);
return name.toString();
}
private static void addMediaTypes(StringJoiner builder, String prefix, List<MediaType> mediaTypes) {
if (!mediaTypes.isEmpty()) {
final StringBuilder buf = new StringBuilder();
buf.append(prefix).append(':');
for (MediaType t : mediaTypes) {
buf.append(t.type());
buf.append('/');
buf.append(t.subtype());
buf.append(',');
}
buf.setLength(buf.length() - 1);
builder.add(buf.toString());
}
}
}
| apache-2.0 |
Keboo/PebbleSharp | PebbleSharp.Core.Tests/AbstractTests/BaseCrc32Tests.cs | 967 | using Microsoft.VisualStudio.TestTools.UnitTesting;
using PebbleSharp.Core.Bundles;
using PebbleSharp.Core.Tests.Resources;
namespace PebbleSharp.Core.Tests.AbstractTests
{
public abstract class BaseCrc32Tests
{
protected abstract IZip GetZip();
public abstract void GeneratesCorrectChecksumForApp();
public abstract void GeneratesCorrectChecksumForFirmware();
protected void RunGeneratesCorrectChecksumForApp()
{
var bundle = new AppBundle();
bundle.Load(GetZip(),SoftwarePlatform.UNKNOWN);
Assert.AreEqual(bundle.Manifest.Application.CRC, Crc32.Calculate(bundle.App));
}
protected void RunGeneratesCorrectChecksumForFirmware()
{
var bundle = new FirmwareBundle();
bundle.Load(GetZip(),SoftwarePlatform.UNKNOWN);
Assert.AreEqual(bundle.Manifest.Firmware.CRC, Crc32.Calculate(bundle.Firmware));
}
}
}
| apache-2.0 |
maxml/sample-apps | photoframe/source/src/org/kaaproject/kaa/demo/photoframe/event/StopPlayEvent.java | 820 | /**
* Copyright 2014-2016 CyberVision, 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 org.kaaproject.kaa.demo.photoframe.event;
/**
* An event class which is used to notify UI components
* of a received command to stop the album playback.
*/
public class StopPlayEvent {
}
| apache-2.0 |
LukasVyhlidka/HomeAutomator | server/src/main/java/org/vyhlidka/homeautomation/domain/BoilerChange.java | 1604 | package org.vyhlidka.homeautomation.domain;
import org.apache.commons.lang3.Validate;
import java.time.LocalDateTime;
/**
* Created by lucky on 26.12.16.
*/
public class BoilerChange {
public final String boilerId;
public final LocalDateTime dateTime;
public final Boiler.BoilerState state;
public BoilerChange(final String boilerId, final LocalDateTime dateTime, final Boiler.BoilerState state) {
Validate.notNull(boilerId, "boilerId can not be null;");
Validate.notNull(dateTime, "dateTime can not be null;");
Validate.notNull(state, "state can not be null;");
this.boilerId = boilerId;
this.dateTime = dateTime;
this.state = state;
}
public BoilerChange(final String boilerId, final Boiler.BoilerState state) {
this(boilerId, LocalDateTime.now(), state);
}
@Override
public boolean equals(final Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
final BoilerChange that = (BoilerChange) o;
if (boilerId != null ? !boilerId.equals(that.boilerId) : that.boilerId != null) return false;
if (dateTime != null ? !dateTime.equals(that.dateTime) : that.dateTime != null) return false;
return state == that.state;
}
@Override
public int hashCode() {
int result = boilerId != null ? boilerId.hashCode() : 0;
result = 31 * result + (dateTime != null ? dateTime.hashCode() : 0);
result = 31 * result + (state != null ? state.hashCode() : 0);
return result;
}
}
| apache-2.0 |
xevious99/google-api-php-client | src/Google/Service/YouTube/Search/Resource.php | 7838 | <?php
namespace Google\Service\YouTube\Search;
/*
* Copyright 2010 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.
*/
/**
* The "search" collection of methods.
* Typical usage is:
* <code>
* $youtubeService = new Google_Service_YouTube(...);
* $search = $youtubeService->search;
* </code>
*/
class Resource extends \Google\Service\Resource
{
/**
* Returns a collection of search results that match the query parameters
* specified in the API request. By default, a search result set identifies
* matching video, channel, and playlist resources, but you can also configure
* queries to only retrieve a specific type of resource. (search.listSearch)
*
* @param string $part
* The part parameter specifies a comma-separated list of one or more search resource properties
* that the API response will include. The part names that you can include in the parameter value
* are id and snippet.
If the parameter identifies a property that contains child properties, the
* child properties will be included in the response. For example, in a search result, the snippet
* property contains other properties that identify the result's title, description, and so forth.
* If you set part=snippet, the API response will also contain all of those nested properties.
* @param array $optParams Optional parameters.
*
* @opt_param string eventType
* The eventType parameter restricts a search to broadcast events.
* @opt_param string channelId
* The channelId parameter indicates that the API response should only contain resources created by
* the channel
* @opt_param string videoSyndicated
* The videoSyndicated parameter lets you to restrict a search to only videos that can be played
* outside youtube.com.
* @opt_param string channelType
* The channelType parameter lets you restrict a search to a particular type of channel.
* @opt_param string videoCaption
* The videoCaption parameter indicates whether the API should filter video search results based on
* whether they have captions.
* @opt_param string publishedAfter
* The publishedAfter parameter indicates that the API response should only contain resources
* created after the specified time. The value is an RFC 3339 formatted date-time value
* (1970-01-01T00:00:00Z).
* @opt_param string onBehalfOfContentOwner
* Note: This parameter is intended exclusively for YouTube content partners.
The
* onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify
* a YouTube CMS user who is acting on behalf of the content owner specified in the parameter
* value. This parameter is intended for YouTube content partners that own and manage many
* different YouTube channels. It allows content owners to authenticate once and get access to all
* their video and channel data, without having to provide authentication credentials for each
* individual channel. The CMS account that the user authenticates with must be linked to the
* specified YouTube content owner.
* @opt_param string pageToken
* The pageToken parameter identifies a specific page in the result set that should be returned. In
* an API response, the nextPageToken and prevPageToken properties identify other pages that could
* be retrieved.
* @opt_param bool forContentOwner
* Note: This parameter is intended exclusively for YouTube content partners.
The forContentOwner
* parameter restricts the search to only retrieve resources owned by the content owner specified
* by the onBehalfOfContentOwner parameter. The user must be authenticated using a CMS account
* linked to the specified content owner and onBehalfOfContentOwner must be provided.
* @opt_param string regionCode
* The regionCode parameter instructs the API to return search results for the specified country.
* The parameter value is an ISO 3166-1 alpha-2 country code.
* @opt_param string videoType
* The videoType parameter lets you restrict a search to a particular type of videos.
* @opt_param string type
* The type parameter restricts a search query to only retrieve a particular type of resource. The
* value is a comma-separated list of resource types.
* @opt_param string topicId
* The topicId parameter indicates that the API response should only contain resources associated
* with the specified topic. The value identifies a Freebase topic ID.
* @opt_param string publishedBefore
* The publishedBefore parameter indicates that the API response should only contain resources
* created before the specified time. The value is an RFC 3339 formatted date-time value
* (1970-01-01T00:00:00Z).
* @opt_param string videoDimension
* The videoDimension parameter lets you restrict a search to only retrieve 2D or 3D videos.
* @opt_param string videoLicense
* The videoLicense parameter filters search results to only include videos with a particular
* license. YouTube lets video uploaders choose to attach either the Creative Commons license or
* the standard YouTube license to each of their videos.
* @opt_param string maxResults
* The maxResults parameter specifies the maximum number of items that should be returned in the
* result set.
* @opt_param string relatedToVideoId
* The relatedToVideoId parameter retrieves a list of videos that are related to the video that the
* parameter value identifies. The parameter value must be set to a YouTube video ID and, if you
* are using this parameter, the type parameter must be set to video.
* @opt_param string videoDefinition
* The videoDefinition parameter lets you restrict a search to only include either high definition
* (HD) or standard definition (SD) videos. HD videos are available for playback in at least 720p,
* though higher resolutions, like 1080p, might also be available.
* @opt_param string videoDuration
* The videoDuration parameter filters video search results based on their duration.
* @opt_param bool forMine
* The forMine parameter restricts the search to only retrieve videos owned by the authenticated
* user. If you set this parameter to true, then the type parameter's value must also be set to
* video.
* @opt_param string q
* The q parameter specifies the query term to search for.
* @opt_param string safeSearch
* The safeSearch parameter indicates whether the search results should include restricted content
* as well as standard content.
* @opt_param string videoEmbeddable
* The videoEmbeddable parameter lets you to restrict a search to only videos that can be embedded
* into a webpage.
* @opt_param string videoCategoryId
* The videoCategoryId parameter filters video search results based on their category.
* @opt_param string order
* The order parameter specifies the method that will be used to order resources in the API
* response.
* @return \Google\Service\YouTube\SearchListResponse
*/
public function listSearch($part, $optParams = array())
{
$params = array('part' => $part);
$params = array_merge($params, $optParams);
return $this->call('list', array($params), "\Google\Service\YouTube\SearchListResponse");
}
}
| apache-2.0 |
shahmishal/swift | lib/SILOptimizer/Transforms/MergeCondFail.cpp | 4516 | //===--- MergeCondFail.cpp - Merge cond_fail instructions ----------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "merge-cond_fail"
#include "swift/SILOptimizer/Analysis/Analysis.h"
#include "swift/SILOptimizer/PassManager/Passes.h"
#include "swift/SILOptimizer/PassManager/Transforms.h"
#include "swift/SILOptimizer/Utils/Local.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SIL/SILInstruction.h"
#include "llvm/Support/Debug.h"
using namespace swift;
/// Return true if the operand of the cond_fail instruction looks like
/// the overflow bit of an arithmetic instruction.
static bool hasOverflowConditionOperand(CondFailInst *CFI) {
if (auto *TEI = dyn_cast<TupleExtractInst>(CFI->getOperand()))
if (isa<BuiltinInst>(TEI->getOperand()))
return true;
return false;
}
namespace {
/// Merge cond_fail instructions.
///
/// We can merge cond_fail instructions if there is no side-effect or memory
/// write in between them.
/// This pass merges cond_fail instructions by building the disjunction of
/// their operands.
class MergeCondFailInsts : public SILFunctionTransform {
public:
MergeCondFailInsts() {}
void run() override {
bool Changed = false;
auto *F = getFunction();
// Merge cond_fail instructions if there is no side-effect or read in
// between them.
for (auto &BB : *F) {
// Per basic block list of cond_fails to merge.
SmallVector<CondFailInst *, 16> CondFailToMerge;
for (auto InstIt = BB.begin(), End = BB.end(); InstIt != End;) {
auto *CurInst = &*InstIt;
++InstIt;
auto *CFI = dyn_cast<CondFailInst>(CurInst);
// Stop merging at side-effects or reads from memory.
if (!CFI && (CurInst->mayHaveSideEffects() ||
CurInst->mayReadFromMemory())) {
// Merge cond_fail.
if (CondFailToMerge.size() > 1) {
Changed |= mergeCondFails(CondFailToMerge);
CondFailToMerge.clear();
continue;
}
}
// Do not process arithmetic overflow checks. We typically generate more
// efficient code with separate jump-on-overflow.
if (CFI && !hasOverflowConditionOperand(CFI) &&
(CondFailToMerge.empty() ||
CFI->getMessage() == CondFailToMerge.front()->getMessage()))
CondFailToMerge.push_back(CFI);
}
// Process any remaining cond_fail instructions in the current basic
// block.
if (CondFailToMerge.size() > 1)
Changed |= mergeCondFails(CondFailToMerge);
}
if (Changed) {
PM->invalidateAnalysis(F, SILAnalysis::InvalidationKind::Instructions);
}
}
/// Try to merge the cond_fail instructions. Returns true if any could
/// be merge.
bool mergeCondFails(SmallVectorImpl<CondFailInst *> &CondFailToMerge) {
assert(CondFailToMerge.size() > 1 &&
"Need at least two cond_fail instructions");
if (CondFailToMerge.size() < 2)
return false;
SILValue MergedCond;
auto *LastCFI = CondFailToMerge.back();
auto InsertPt = ++SILBasicBlock::iterator(LastCFI);
SILBuilderWithScope Builder(InsertPt);
SILLocation Loc = LastCFI->getLoc();
// Merge conditions and remove the merged cond_fail instructions.
for (unsigned I = 0, E = CondFailToMerge.size(); I != E; ++I) {
auto CurCond = CondFailToMerge[I]->getOperand();
if (MergedCond) {
CurCond = Builder.createBuiltinBinaryFunction(Loc, "or",
CurCond->getType(),
CurCond->getType(),
{MergedCond, CurCond});
}
MergedCond = CurCond;
}
// Create a new cond_fail using the merged condition.
Builder.createCondFail(Loc, MergedCond, LastCFI->getMessage());
for (CondFailInst *CFI : CondFailToMerge) {
CFI->eraseFromParent();
}
return true;
}
};
} // end anonymous namespace
SILTransform *swift::createMergeCondFails() {
return new MergeCondFailInsts();
}
| apache-2.0 |
wilsoncampusano/saglo | src/main/java/equipo/once/elizabeth/richard/wilson/usecases/BuscarAreaComunUseCase.java | 1258 | package equipo.once.elizabeth.richard.wilson.usecases;
import equipo.once.elizabeth.richard.wilson.entities.dominio.AreaComun;
import equipo.once.elizabeth.richard.wilson.services.AreaComunService;
import equipo.once.elizabeth.richard.wilson.dtos.BuscarAreaComunRequest;
import equipo.once.elizabeth.richard.wilson.dtos.BuscarAreaComunResponse;
import equipo.once.elizabeth.richard.wilson.usecases.interfaces.AreaComunResponse;
import equipo.once.elizabeth.richard.wilson.usecases.interfaces.AreaComunUseCase;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class BuscarAreaComunUseCase implements AreaComunUseCase {
@Autowired
public AreaComunService areaComunService;
public BuscarAreaComunRequest request;
private BuscarAreaComunResponse response;
@Override
public void solicitar() {
List<AreaComun> areasComunes =
areaComunService.buscarPorPalabra(request.palabraBusqueda.toLowerCase());
BuscarAreaComunResponse response = new BuscarAreaComunResponse();
response.areasComunes = areasComunes;
this.response = response;
}
@Override
public AreaComunResponse obtenerRespuesta() {
return response;
}
}
| apache-2.0 |
zy4kamu/Coda | src/utils/StatCalc/stat-calc.cpp | 14019 | /**
* @file stat-calc.cpp
* @brief source file for StatCalc class for calculating other statics of words and documets
*/
#include "stat-calc-tools.h"
#include "stat-calc.h"
#include "Strings/Splitter.h"
#include "document-processor.h"
#include "ISentenceSplitter.h"
#include <cmath>
using namespace statcalc;
using lemmatizer::ILemmatizer;
StatCalc::StatCalc(shared_ptr<ITokenizer> i_tokenizer, shared_ptr<ILemmatizer> i_lemmatizer, shared_ptr<_sentence_splitter::ISentenceSplitter> i_splitter)
{
m_docProcessor = shared_ptr<DocumentProcessor>(
new DocumentProcessor(i_tokenizer,i_lemmatizer,i_splitter));
m_predefinedVocabulary = false;
}
TDMatrix&
StatCalc::tdmatrix(void)
{
return this->m_tdmatrix;
}
DocID&
StatCalc::docID(void)
{
return this->m_docID;
}
Vocabulary&
StatCalc::vocabulary()
{
return this->m_vocabulary;
}
void
StatCalc::set_vocabulary(const Vocabulary& i_voc)
{
this->m_vocabulary = i_voc;
m_predefinedVocabulary = true;
}
bool &StatCalc::predefinedVocabulary(void)
{
return this->m_predefinedVocabulary;
}
void
StatCalc::clean()
{
this->m_tdmatrix.setZero();
this->m_docID.clear();
this->vocabulary().clear();
this->m_vecTriplets.clear();
}
WordDoubleStat&
StatCalc::df(void)
{
return m_df;
}
WordDoubleStat&
StatCalc::cf(void)
{
return m_cf;
}
IDCategory&
StatCalc::idCategory()
{
return this->m_idCategory;
}
bool
StatCalc::saveTDMatrix(const string& i_filename, bool withDocNames)
{
ofstream oStream(i_filename,ios::binary|ios::out);
if ( !m_tdmatrix.cols() )
{
cout<<"Nothing to store!"<<endl;
return false;
}
if (!oStream.is_open())
{
cout<<"Can\'t open file for writing\n.Filename:"<<i_filename<<endl;
return false;
}
saveTDMatrix_(oStream);
saveIDCategory_(oStream);
saveVocabulary_(oStream);
if (withDocNames)
{
saveDocID_(oStream);
}
oStream.close();
return true;
}
bool
StatCalc::loadTDMatrix(const string& i_filename, bool withDocNames)
{
clean();
ifstream iStream(i_filename,ios::in|ios::binary);
if (!iStream.is_open())
{
cout<<"Can\'t open file for reading\n.Filename:"<<i_filename<<endl;
return false;
}
loadTDMatrix_(iStream);
loadIDCategory_(iStream);
loadVocabulary_(iStream);
if (withDocNames)
{
loadDocID_(iStream);
}
iStream.close();
return true;
}
void
StatCalc::saveTDMatrix_(ofstream& i_oStream)
{
eigentools::saveSparseMatrixBinary(m_tdmatrix,i_oStream);
}
void
StatCalc::saveDocID_(ofstream& i_oStream)
{
int size = (int)m_docID.size();
i_oStream.write((char*)& size,4);
for (auto it = m_docID.begin(); it != m_docID.end(); it++)
{
Tools::WriteString_Binary(i_oStream,it->first);
i_oStream.write((char*)& it->second,4);
}
}
void
StatCalc::saveIDCategory_(ofstream& i_oStream)
{
int size = (int)m_idCategory.size();
i_oStream.write((char*)& size,4);
for (auto it = m_idCategory.begin(); it != m_idCategory.end(); it++)
{
i_oStream.write((char*)& it->first,4);
it->second.saveBinary(i_oStream);
// i_oStream.write((char*)& it->second,4);
}
}
void
StatCalc::loadTDMatrix_(ifstream& i_iStream)
{
eigentools::loadSparseMatrixBinary(m_tdmatrix,i_iStream);
}
void
StatCalc::loadDocID_(ifstream &i_iStream)
{
int size;
i_iStream.read((char*)& size, 4);
for (int i = 0; i < size; i++)
{
string word;
Tools::ReadString(i_iStream,word);
unsigned int id;
i_iStream.read((char*)& id,4);
m_docID[word] = id;
}
}
void
StatCalc::saveVocabulary_(ofstream& i_oStream)
{
Tools::save_map_binary(i_oStream,m_vocabulary);
}
void
StatCalc::loadVocabulary_(ifstream &i_iStream)
{
Tools::load_map_binary(i_iStream,m_vocabulary);
}
void
StatCalc::loadIDCategory_(ifstream &i_iStream)
{
int size;
i_iStream.read((char*)& size, 4);
for (int i = 0; i < size; i++)
{
unsigned int id;
i_iStream.read((char*)& id,4);
Category domain;
domain.loadBinary(i_iStream);
// i_iStream.read((char*)& domain, 4);
m_idCategory[id] = domain;
}
}
void
StatCalc::loadFileList(const string &i_filelist, const string& prefix)
{
Tools::DocumentPlain filelist(i_filelist);
unsigned int id = 0;
string str;
for ( size_t i = 0; i < filelist.content().size();i++ )
{
if (Tools::ConvertWstringToString(filelist.content()[i], str))
{
str = prefix + str;
if (m_docID.find(str) == m_docID.end())
m_docID[str] = id++;
}
}
}
void
StatCalc::calculateTDMatrix(shared_ptr<Tools::DocumentCreator> i_docCreator)
{
if (m_docID.empty())
{
wcout << L"Error in loaded data. Use loadFilelist() function please"<<endl;
return;
}
unordered_map<int,int> docBOW;
unsigned int count = 0;
for (DocID::iterator itr = m_docID.begin();
itr != m_docID.end();
itr++)
{
shared_ptr<Tools::Document> doc = i_docCreator->loadDocument(itr->first);
// m_vecTriplets.reserve(100000000);
m_idCategory.reserve(m_docID.size());
Category cat;
cat.label() = cat.fromWstring(doc->category());
m_idCategory[itr->second] = cat;
wcout << count << L". Process doc with ID = " << itr->second;
wcout << L". Domain "+doc->category()<<endl;
count += 1;
bool success = m_docProcessor->processDocument(doc,*this);
if (success)
{
unordered_map<int,int>& docBOW = m_docProcessor->docBOW();
for (auto it = docBOW.begin();it != docBOW.end();it++)
{
m_vecTriplets.emplace_back(it->first,itr->second,it->second);
}
}
else
{
wcout<< L"Error in processing plain file. id = " << itr->second << endl;
}
}
m_tdmatrix.derived().resize(m_vocabulary.size(),m_docID.size());
m_tdmatrix.setFromTriplets(m_vecTriplets.begin(),m_vecTriplets.end());
m_vecTriplets.clear();
}
void
StatCalc::calculateTDMatrix(vector<shared_ptr<Tools::Document> >& docVec)
{
if (docVec.empty())
{
wcout << L"Set of input documents is empty" << endl;
return;
}
unordered_map<int, int> docBOW;
unsigned int count = 0;
for (auto& x : docVec)
{
wcout << L"Processing document #" << count << std::endl;
bool success = m_docProcessor->processDocument(x, *this);
if (success)
{
unordered_map<int, int>& docBOW = m_docProcessor->docBOW();
for (auto it = docBOW.begin(); it != docBOW.end(); it++)
{
m_vecTriplets.emplace_back(it->first, count, it->second);
}
m_docID[std::to_string(count)] = count;
count ++;
}
else
{
wcout << L"Error in processing document #" << count << endl;
}
}
m_tdmatrix.derived().resize(m_vocabulary.size(), m_docID.size());
m_tdmatrix.setFromTriplets(m_vecTriplets.begin(), m_vecTriplets.end());
m_vecTriplets.clear();
}
WordDoubleStat&
StatCalc::calculatedf(void)
{
m_df.setZero(this->tdmatrix().rows(),1);
if (!m_tdmatrix.cols())
{
wcout << L"Data is not loaded"<< endl;
return m_df;
}
//calcullation of document frequency
for (int k=0; k<m_tdmatrix.outerSize(); ++k)
{
for (SparseMatrix<double>::InnerIterator it(m_tdmatrix,k); it; ++it)
{
m_df(it.row()) += 1;
}
}
return m_df;
}
WordDoubleStat&
StatCalc::calculateidf(void)
{
m_idf.setZero(m_tdmatrix.rows(),1);
if (!m_tdmatrix.cols())
{
wcout << L"Data is not loaded"<< endl;
return m_idf;
}
if (!m_df.sum())
{
calculatedf();
}
double N = (double)m_idCategory.size();
m_idf = (m_df.array().pow(-1) * N).log();
return m_idf;
}
WordDoubleStat&
StatCalc::calculatecf(Category i_domain)
{
// if (m_docCollection.empty() && m_tdmatrix.empty())
// {
// wcout << L"Data is not loaded"<< endl;
// return m_cf;
// }
// if (m_tdmatrix.empty() && !m_docCollection.empty())
// {
// this->calculateTDMatrix();
// }
// WordIntStat cf;
// for (auto itr = m_tdmatrix.begin(); itr != m_tdmatrix.end(); itr++)
// {
// vector<pair<unsigned int, unsigned int> > v_pair = itr->second;
// unsigned int word_cf = 0;
// for (size_t i = 0; i < v_pair.size(); i++)
// {
// if (m_idCategory[v_pair[i].first]==i_domain)
// {
// word_cf += v_pair[i].second;
// }
// }
// if (word_cf)
// {
// cf[itr->first] = word_cf;
// }
// }
return m_cf;
}
WordDoubleStat&
StatCalc::calculatecf(void)
{
m_cf.setZero(m_tdmatrix.rows(),1);
if (!m_tdmatrix.cols())
{
wcout << L"Data is not loaded"<< endl;
return m_cf;
}
// m_df.reserve(m_tdmatrix.size());
m_cf = m_tdmatrix * eigentools::DenseMat::Ones(m_tdmatrix.cols(),1);
return m_cf;
}
bool StatCalc::loadOldTDMatrix(const string& i_filename, bool withDocNames)
{
clean();
ifstream iStream(i_filename,ios::in|ios::binary);
if (!iStream.is_open())
{
cout<<"Can\'t open file for reading\n.Filename:"<<i_filename<<endl;
return false;
}
loadOldTDMatrix_(iStream);
loadIDCategory_(iStream);
if (withDocNames)
{
loadDocID_(iStream);
}
iStream.close();
return true;
}
void StatCalc::loadOldTDMatrix_(ifstream &i_iStream)
{
#ifdef MSVC
locale loc = std::locale();
#else
locale loc = std::locale("ru_RU.UTF-8");
#endif
int size,vsize,value,col,docNum = 0;
i_iStream.read((char*)& size, 4);
m_vocabulary.reserve(size);
for (int i = 0; i < size; i++)
{
wstring word;
Tools::ReadWString(i_iStream,word,loc);
m_vocabulary[word] = i;
i_iStream.read((char*)& vsize,4);
for (int j = 0; j < vsize; j++)
{
i_iStream.read((char*)& col,4);
i_iStream.read((char*)& value,4);
m_vecTriplets.push_back(Eigen::Triplet<int>(i,col,value));
docNum = (docNum>col)? docNum : col;
}
}
m_tdmatrix.resize(size,docNum+1);
m_tdmatrix.setFromTriplets(m_vecTriplets.begin(),m_vecTriplets.end());
}
vector<WordDoubleStat>&
StatCalc::calculateMI(void)
{
// m_MI.clear();
// if (m_docCollection.empty() && m_tdmatrix.empty())
// {
// wcout << L"Data is not loaded"<< endl;
// return m_MI;
// }
// if (m_tdmatrix.empty() && !m_docCollection.empty())
// {
// this->calculateTDMatrix();
// }
// double N = (double)m_idCategory.size();
// vector<double> NDocDomain((size_t)COUNT_DOMAIN_TYPES,0.0);
// for (auto itr = m_idCategory.begin(); itr != m_idCategory.end(); itr++)
// {
// NDocDomain[(int) itr->second] += 1;
// }
// for (unsigned int domain = 0; domain < (unsigned int)COUNT_DOMAIN_TYPES; domain++)
// {
// double N00,N01,N10,N11,N_0,N_1,N0_,N1_, _N11, _N10, _N01, _N00;
// WordDoubleStat mi_dom;
// N_1 = NDocDomain[domain];
// N_0 = N - N_1;
// for (auto itr = m_tdmatrix.begin(); itr != m_tdmatrix.end(); itr++)
// {
// N1_ = (itr->second).size();
// N0_ = N - N1_;
// N11 = 0;
// for (size_t i = 0; i < itr->second.size(); i++)
// {
// unsigned int docDom = itr->second[i].first;
// if (m_idCategory[docDom]==domain)
// {
// N11 += 1;
// }
// }
// N10 = N1_ - N11;
// N01 = N_1 - N11;
// N00 = N_0 - N10;
// _N11 = (N11==0.0)? 0.0000001 : N11;
// _N01 = (N01==0.0)? 0.0000001 : N01;
// _N10 = (N10==0.0)? 0.0000001 : N10;
// _N00 = (N00==0.0)? 0.0000001 : N00;
// mi_dom[itr->first] =
// (N11/N)*LOG2(_N11*N/(N1_*N_1)) +
// (N01/N)*LOG2(_N01*N/(N0_*N_1)) +
// (N10/N)*LOG2(_N10*N/(N1_*N_0)) +
// (N00/N)*LOG2(_N00*N/(N0_*N_0)) ;
// }
// m_MI.push_back(mi_dom);
// }
return m_MI;
}
double statcalc::LOG2( double n )
{
return log( n ) / log( 2.0 );
}
vector<WordDoubleStat>&
StatCalc::calculateCentroids(void)
{
// m_centroids.clear();
// if (m_docCollection.empty() && m_tdmatrix.empty() )
// {
// wcout << L"Data is not loaded"<< endl;
// return m_centroids;
// }
// if (m_tdmatrix.empty() && !m_docCollection.empty())
// {
// this->calculateTDMatrix();
// }
// calculateidf();
// vector<double> NDocDomain(COUNT_DOMAIN_TYPES,0.0);
// unordered_map<unsigned int, WordDoubleStat> wf_idf;
// for (auto itr = m_docCollection.begin(); itr != m_docCollection.end(); itr++)
// {
// WordDoubleStat doc_wf_idf;
// WordIntStat doc_tf = itr->second;
// Category domain = m_idCategory[itr->first];
// NDocDomain[(int)domain] += 1.0;
// for (auto it = doc_tf.begin(); it != doc_tf.end(); it++)
// {
// doc_wf_idf[it->first] = (1.0 + log((double)(it->second)))*m_idf[it->first];
// }
// wf_idf[itr->first] = doc_wf_idf;
// }
// WordDoubleStat empty_map;
// //empty_map.reserve(m_idf.size());
// for (auto itr = m_idf.begin(); itr != m_idf.end(); itr++)
// empty_map[itr->first] = 0.0;
// m_centroids = vector<WordDoubleStat>(COUNT_DOMAIN_TYPES, empty_map);
// for (auto itr = wf_idf.begin(); itr != wf_idf.end(); itr++)
// {
// Category domain = m_idCategory[itr->first];
// WordDoubleStat doc_wf_idf = itr->second;
// for (auto it = doc_wf_idf.begin(); it != doc_wf_idf.end(); it++)
// {
// m_centroids[(int)domain][it->first] += it->second / NDocDomain[domain];
// }
// }
return m_centroids;
}
| apache-2.0 |
cement/AndroidWebServer | TinyHttpServer/src/com/coment/simple/SimpleTest.java | 580 | package com.coment.simple;
import java.io.IOException;
import com.cement.constants.Settings.MODE;
import com.cement.server.EmbedHttpServer;
public class SimpleTest {
public static void main(String[] args) throws IOException {
EmbedHttpServer server = new EmbedHttpServer(9999);
// server.addHandler(new PostSessionHandler("POST"));
// server.addHandler(new GetSessionHandler2("GET"));
server.setWebRoot("W:\\WebRoot\\static");
server.setNotFindPage("W:\\WebRoot\\static\\page404.html");
server.setVisitMode(MODE.FILE);
server.start();
}
}
| apache-2.0 |
Sargul/dbeaver | plugins/org.jkiss.dbeaver.model/src/org/jkiss/dbeaver/model/qm/QMObjectType.java | 2387 | /*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2021 DBeaver Corp and others
*
* 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.jkiss.dbeaver.model.qm;
import org.jkiss.dbeaver.model.qm.meta.QMMObject;
import org.jkiss.dbeaver.model.qm.meta.QMMSessionInfo;
import org.jkiss.dbeaver.model.qm.meta.QMMStatementInfo;
import org.jkiss.dbeaver.model.qm.meta.QMMTransactionInfo;
import org.jkiss.utils.CommonUtils;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* Object type
*/
public enum QMObjectType {
session("Session", QMMSessionInfo.class),
txn("Transactions", QMMTransactionInfo.class),
query("Queries", QMMStatementInfo.class);
private final String title;
private final Class<? extends QMMObject> type;
QMObjectType(String title, Class<? extends QMMObject> type)
{
this.title = title;
this.type = type;
}
public Class<? extends QMMObject> getType()
{
return type;
}
public String getTitle() {
return title;
}
public static String toString(Collection<QMObjectType> objectTypes)
{
List<String> names = new ArrayList<>(objectTypes.size());
for (QMObjectType type : objectTypes) {
names.add(type.name());
}
return CommonUtils.makeString(names, ',');
}
public static Collection<QMObjectType> fromString(String str)
{
List<QMObjectType> objectTypes = new ArrayList<>();
for (String otName : CommonUtils.splitString(str, ',')) {
try {
objectTypes.add(QMObjectType.valueOf(otName));
} catch (IllegalArgumentException e) {
// just scrip bad names
}
}
return objectTypes;
}
}
| apache-2.0 |
moritalous/LineBot2 | src/main/java/forest/rice/field/k/linebot/function01/pokemon/Pokemon.java | 1594 | package forest.rice.field.k.linebot.function01.pokemon;
public class Pokemon {
private int no;
private String name;
private String captorId;
private String profilePhto;
private String url;
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCaptorId() {
return captorId;
}
public void setCaptorId(String captorId) {
this.captorId = captorId;
}
public void setProfilePhto(String profilePhto) {
this.profilePhto = profilePhto;
}
public String getSmallImageUrl() {
return new StringBuilder().append("http://www.pokemon.jp/zukan/images/s/")
.append(profilePhto.replace("/zukan/images/l/", "")).toString()
.replace("http://www.pokemon.jp/", "https://3yfwsavfy1.execute-api.ap-northeast-1.amazonaws.com/prod/");
}
public String getMiddleImageUrl() {
return new StringBuilder().append("http://www.pokemon.jp/zukan/images/m/")
.append(profilePhto.replace("/zukan/images/l/", "")).toString()
.replace("http://www.pokemon.jp/", "https://3yfwsavfy1.execute-api.ap-northeast-1.amazonaws.com/prod/");
}
public String getLargeImageUrl() {
return new StringBuilder().append("http://www.pokemon.jp/zukan/images/l/")
.append(profilePhto.replace("/zukan/images/l/", "")).toString()
.replace("http://www.pokemon.jp/", "https://3yfwsavfy1.execute-api.ap-northeast-1.amazonaws.com/prod/");
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
| apache-2.0 |
Tetha/bifroest | rewrite-framework/src/main/java/com/goodgame/profiling/rewrite_framework/core/source/handler/SourceHandlerCreator.java | 1371 | package com.goodgame.profiling.rewrite_framework.core.source.handler;
import java.util.ServiceLoader;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.goodgame.profiling.rewrite_framework.core.config.FetchConfiguration;
import com.goodgame.profiling.rewrite_framework.core.source.Source;
public class SourceHandlerCreator<I, U> {
private static final Logger log = LogManager.getLogger();
private final Class<I> inputType;
private final Class<U> unitType;
@SuppressWarnings("rawtypes")
private static final ServiceLoader<SourceHandlerFactory> factories = ServiceLoader.load( SourceHandlerFactory.class );
public SourceHandlerCreator( Class<I> inputType, Class<U> unitType ) {
this.inputType = inputType;
this.unitType = unitType;
}
@SuppressWarnings("unchecked")
public SourceUnitHandler<U> create( Source<U> source, FetchConfiguration<I, U> fetchConfig ) {
for ( SourceHandlerFactory<I, U> factory : factories ) {
if ( !factory.handledInput().isAssignableFrom( inputType ) ) {
continue;
} else if ( !factory.handledUnit().isAssignableFrom( unitType ) ) {
continue;
} else {
return log.exit( factory.create( source, fetchConfig ) );
}
}
throw new IllegalArgumentException( "Cannot handle input type " + inputType.getName() + " and unit type " + unitType.getName() );
}
}
| apache-2.0 |
vjanmey/EpicMudfia | com/planet_ink/coffee_mud/Items/Weapons/Scimitar.java | 1976 | package com.planet_ink.coffee_mud.Items.Weapons;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
/*
Copyright 2000-2014 Bo Zimmerman
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.
*/
public class Scimitar extends Sword
{
@Override public String ID(){ return "Scimitar";}
public Scimitar()
{
super();
setName("an ornate scimitar");
setDisplayText("a rather ornate looking Scimitar leans against the wall.");
setDescription("It has a metallic pommel, and a long curved blade.");
basePhyStats().setAbility(0);
basePhyStats().setLevel(0);
basePhyStats().setWeight(4);
basePhyStats().setAttackAdjustment(0);
basePhyStats().setDamage(8);
baseGoldValue=15;
recoverPhyStats();
material=RawMaterial.RESOURCE_STEEL;
weaponType=TYPE_SLASHING;
}
}
| apache-2.0 |
garygunarman/firanew | admin/emails/order_/_cancel/get.php | 3553 | <?php
/*
* ----------------------------------------------------------------------
* EMAIL - NOTIFICATION BACK ORDER: GET
* ----------------------------------------------------------------------
*/
class EMAIL_GET{
private $conn;
function __construct() {
$this->conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
}
function detail_order($post_order_number){
$sql = "SELECT * FROM tbl_order AS ord LEFT JOIN tbl_order_item AS item ON ord.order_id = item.order_id
LEFT JOIN tbl_user_purchase AS pur ON ord.order_id = pur.order_id
LEFT JOIN tbl_user AS user ON pur.user_id = user.user_id
WHERE `order_number` = '$post_order_number'
";
$query = $this->conn->query($sql);
$result = $query->fetch_object();
return $result;
}
function detail_order_item($post_order_id){
$sql = "SELECT * FROM tbl_order AS ord LEFT JOIN tbl_order_item AS item ON ord.order_id = item.order_id
LEFT JOIN tbl_user_purchase AS pur ON ord.order_id = pur.order_id
LEFT JOIN tbl_user AS user ON pur.user_id = user.user_id
WHERE item.order_id = '$post_order_id'
GROUP BY item.item_id
";
$query = $this->conn->query($sql);
$row = array();
while($result = $query->fetch_object()){
array_push($row, $result);
}
return $row;
}
function order_item($order_id){
$sql = "SELECT
product.product_name, type.type_name, item.stock_name, item.fulfillment_date, item.shipping_number,
item.item_price, item.item_discount_price, item.item_quantity, item.item_id, item.fulfillment_date,
image.img_src,
order_.order_shipping_amount, order_.order_id, order_.shipping_method, order_.fulfillment_status
FROM tbl_order AS order_ LEFT JOIN tbl_order_item AS item ON order_.order_id = item.order_id
LEFT JOIN tbl_product_type AS type ON item.type_id = type.type_id
LEFT JOIN tbl_product AS product ON type.product_id = product.id
LEFT JOIN tbl_product_image AS image ON type.type_id = image.type_id
WHERE item.order_id = '$order_id' AND image_order='1'";
$query = $this->conn->query($sql);
$row = array();
while($result = $query->fetch_object()){
array_push($row, $result);
}
return $row;
}
function detail_order_item_product($type_id, $stock_name, $order_id){
$sql = "SELECT * FROM tbl_product AS prod_ LEFT JOIN tbl_product_type AS type_ ON prod_.id = type_.product_id
LEFT JOIN tbl_product_image AS img_ ON type_.type_id = img_.type_id
LEFT JOIN tbl_product_stock AS stock_ ON type_.type_id = stock_.type_id
LEFT JOIN tbl_order_item AS orditem_ ON type_.type_id = orditem_.type_id
LEFT JOIN tbl_order AS ord_ ON orditem_.order_id = ord_.order_id
LEFT JOIN tbl_promo_item AS disc ON type_.type_id = disc.product_type_id
LEFT JOIN tbl_promo AS promo ON disc.promo_id = promo.promo_id
WHERE type_.type_id = '$type_id' AND `stock_`.`stock_name` = '$stock_name' AND orditem_.order_id = '$order_id'
GROUP BY type_.type_id
";
$query = $this->conn->query($sql);
$result = $query->fetch_object();
return $result;
}
}
?> | apache-2.0 |
CMPUT301W14T07/Team7Project | Team7Project/src/ca/ualberta/team7project/cache/CacheOperation.java | 9968 | package ca.ualberta.team7project.cache;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.UUID;
import android.content.Context;
import ca.ualberta.team7project.location.LocationComparator;
import ca.ualberta.team7project.models.ThreadModel;
import ca.ualberta.team7project.models.ThreadTagModel;
import ca.ualberta.team7project.network.ThreadFetcher.SortMethod;
/**
* Helper class, Cache programming interface<p>
* MemorySyncWithFS(context) probably would be the first function to call,
* if you want the threadModelPool in the memory to be loaded.
* <p>
* this class provides the essential operation for the cache,
* like searching by uuid in the cache in the memory,
* or adding threadModel to cache(this is, these threadModels are cached)
* <p>
* If you worry your memory would lose, like user shutting down the app
* you could call FSSyncWithMemory(context), which make file to be consistent with memory
* <p>
* if you want to have direct access to ThreadModelPool in the Main Memory,
* I have made it to be singleton, which is static and would last in the app as app last,(I guess)
* @author wzhong3
*
*/
public class CacheOperation {
public static int BY_PARENTID = 1;
public static int BY_ITSELFID = 2;
public static int BY_TOPICID =3;
private SortMethod sortMethod = SortMethod.DATE;
private boolean isFilterPicture = false;
private double lat = 0;
private double lon = 0;
private Integer maxResults = 20;
//Various methods for setting up the CacheOperation for a pull
/**
* Set the user's own or desired location to be used for proximity sorting
* @param lat latitude
* @param lon longitude
*/
public void SetLocation(double lat, double lon)
{
this.lat = lat;
this.lon = lon;
}
/**
* Set a sorting method to be applied to all search/pull operations
* @param sortMethod sorting method to be used
*/
public void SetSortMethod(SortMethod sortMethod)
{
this.sortMethod = sortMethod;
}
/**
* Set whether only comments with pictures will be pulled
* @param isFilterPicture true if only pictures with comments should be pulled, else false
*/
public void SetFilterPicture(boolean isFilterPicture)
{
this.isFilterPicture = isFilterPicture;
}
/**
* Set the max number of comments to be pulled for normal operations
* @param maxResults max comment count
*/
public void SetMaxResults(Integer maxResults)
{
this.maxResults = maxResults;
}
/**
* For testing purposes only
* <p>
* Reset the cache operation to its default state
*/
public void RestoreDefaults()
{
lat = 0;
lon = 0;
isFilterPicture = false;
sortMethod = SortMethod.DATE;
maxResults = 20;
}
// SEARCH STRATEGY
// filter first
// then perform the search
// then do the sort
// then return the top some number of threads
/**
* Retrieves a <i>copy</i> of the current cache pool and returns it after applying the picture filter
* @return filtered list of comments that were in the pool
*/
private ArrayList<ThreadModel> grabCurrentPool()
{
ArrayList<ThreadModel> pool = new ArrayList<ThreadModel>(ThreadModelPool.threadModelPool);
if(isFilterPicture)
{
ArrayList<ThreadModel> filteredPool = new ArrayList<ThreadModel>();
for(ThreadModel thread : pool)
{
if(thread.getImage() != null)
filteredPool.add(thread);
}
return filteredPool;
}
return pool;
}
/**
* Sort a pool of threads by the current sorting method
* <p>
* The passed pool should be post-filter and post-search
* @param unsorted pool
* @return sorted pool
*/
private ArrayList<ThreadModel> sortPool(ArrayList<ThreadModel> pool)
{
ArrayList<ThreadModel> poolCopy = new ArrayList<ThreadModel>(pool);
switch(sortMethod)
{
case DATE:
//sort the poolCopy by date
Collections.sort(poolCopy, new Comparator<ThreadModel>(){
@Override
public int compare(ThreadModel model1, ThreadModel model2) {
Date date1 = model1.getTimestamp();
Date date2 = model2.getTimestamp();
return date2.compareTo(date1);
}
});
break;
case LOCATION:
//use the geocalc
//LocationComparator is in the location package
//override the comparator
Collections.sort(poolCopy, new LocationComparator(lat, lon));
break;
case NO_SORT:
default:
//do nothing (just return the argument)
break;
}
return poolCopy;
}
/**
* Return only the top maxResults items in a pool of threads
* <p>
* Should be called after filtering, searching, and sorting have been done on the pool
* @param pool a list of threads
* @return top maxResults items in the passed list
*/
private ArrayList<ThreadModel> getTop(ArrayList<ThreadModel> pool)
{
//TODO: get the top <maxResults> threads
if(pool.size() > maxResults)
{
return new ArrayList<ThreadModel>(pool.subList(0, maxResults -1 ));
}
else
return pool;
}
/**
* Pull favorited comments from the cache
* @param favorites list of favorite UUID's
* @return list of favorited comments
*/
public ArrayList<ThreadModel> searchFavorites(ArrayList<UUID> favorites)
{
ArrayList<ThreadModel> pool = grabCurrentPool();
ArrayList<ThreadModel> favoritePool = new ArrayList<ThreadModel>();
for(ThreadModel thread : pool)
{
if(favorites.contains(thread.getUniqueID()))
favoritePool.add(thread);
}
favoritePool = sortPool(favoritePool);
return favoritePool; //return all in the case of favorites only
}
/**
* Pull child comments from the cache
* @param parent
* @return list of child comments
*/
public ArrayList<ThreadModel> searchChildren(UUID parent)
{
ArrayList<ThreadModel> pool = grabCurrentPool();
ArrayList<ThreadModel> childPool = new ArrayList<ThreadModel>();
for(ThreadModel thread : pool)
{
if(thread.getParentUUID().equals(parent))
childPool.add(thread);
}
childPool = sortPool(childPool);
return getTop(childPool);
}
/**
* Pull comments globally from the cache
* @return list of comments
*/
public ArrayList<ThreadModel> searchAll()
{
ArrayList<ThreadModel> pool = grabCurrentPool();
pool = sortPool(pool);
return getTop(pool);
}
/**
* Pull comments matching a set of tags from the cache
* <p>
* Pulls only comments that contain <i>all</i> the specified tags
* @param tags list of tags to match
* @return list of comments matching the passed tags
*/
public ArrayList<ThreadModel> searchTags(ArrayList<String> tags)
{
ArrayList<ThreadModel> pool = grabCurrentPool();
ArrayList<ThreadModel> tagPool = new ArrayList<ThreadModel>();
for(ThreadModel thread: pool){
ThreadTagModel tagModel = thread.getTags();
for(String tag: tags){
if(tagModel.contains(tag)){
tagPool.add(thread);
break;
}
}
}
tagPool = sortPool(tagPool);
return getTop(tagPool);
}
/**
* Make ThreadModelPool in the memory synchronized to the pool in the File System<p>
* Technically, if there is no network connected, this is the first function to call to set the cache up
* @param context
*/
public void loadFile(Context context)
{
MemoryToFileOperation transferTool = new MemoryToFileOperation(context);
transferTool.loadFromFile();
}
/**
* Make threadModelPool in the file synchronized to the pool in the current memory<p>
* Call this when you want ThreadModelPool in file system to be consistent with the one in memory
* @param context
*/
public void saveFile(Context context)
{
MemoryToFileOperation transferTool = new MemoryToFileOperation(context);
transferTool.saveInFile();
}
/**
* Search the threadModelPool by UUID and mode<p>
* it has three modes, by_parentid, by_itselfid, and by_topicid.
* And these mode can be referred by the class name, since they are static
* return Collection of threadModel
* @param uuid
* @param mode
* @return
*/
public Collection<ThreadModel> searchByUUID(UUID uuid, int mode)
{
Collection<ThreadModel> collection = new ArrayList<ThreadModel>();
if(mode == BY_PARENTID){
for(ThreadModel threadModel: ThreadModelPool.threadModelPool){
if(threadModel.getParentUUID().equals(uuid)){
collection.add(threadModel);
}
}
}
else if(mode == BY_ITSELFID){
for(ThreadModel threadModel: ThreadModelPool.threadModelPool){
if(threadModel.getUniqueID().equals(uuid)){
collection.add(threadModel);
}
}
}
else if(mode == BY_TOPICID){
for(ThreadModel threadModel: ThreadModelPool.threadModelPool){
if(threadModel.getTopicUUID().equals(uuid)){
collection.add(threadModel);
}
}
}
return collection;
}
/**
* Insert a single threadModel to the pool in the memory<p>
* don't worry about inserting a duplicated threadModel in the pool.
* it would check the UUID, and prevent from inserting a duplicated threadModel.
* @param threadModel
*/
public void saveThread(ThreadModel threadModel)
{
if(threadModel == null)
return;
//we can assume the inserted threadModel is always the latest model
//if an older/identical version of the thread already exists in pool, remove it
for(ThreadModel thread : ThreadModelPool.threadModelPool)
{
if(threadModel.getUniqueID().equals(thread.getUniqueID()))
{
ThreadModelPool.threadModelPool.remove(thread);
break;
}
}
//add the up-to-date version of the thread to the pool
ThreadModelPool.threadModelPool.add(threadModel);
}
/**
* Inset a collection of threadModels to the pool in the memory<p>
* the same as inserting the single one, except for collection this time
* @param collection
*/
public void saveCollection(Collection<ThreadModel> collection)
{
if(collection != null)
{
for(ThreadModel threadModel: collection)
{
saveThread(threadModel);
}
}
}
}
| apache-2.0 |
go-swagger/go-swagger | cmd/swagger/commands/generate/support_test.go | 1230 | package generate_test
import (
"io/ioutil"
"log"
"os"
"path/filepath"
"testing"
"github.com/go-swagger/go-swagger/cmd/swagger/commands/generate"
flags "github.com/jessevdk/go-flags"
)
func TestGenerateSupport(t *testing.T) {
testGenerateSupport(t, false)
}
func TestGenerateSupportStrict(t *testing.T) {
testGenerateSupport(t, true)
}
func testGenerateSupport(t *testing.T, strict bool) {
specs := []string{
"tasklist.basic.yml",
}
log.SetOutput(ioutil.Discard)
defer log.SetOutput(os.Stdout)
base := filepath.FromSlash("../../../../")
for i, spec := range specs {
_ = t.Run(spec, func(t *testing.T) {
path := filepath.Join(base, "fixtures/codegen", spec)
generated, err := ioutil.TempDir(filepath.Dir(path), "generated")
if err != nil {
t.Fatalf("TempDir()=%s", generated)
}
defer func() {
_ = os.RemoveAll(generated)
}()
m := &generate.Support{}
if i == 0 {
m.Shared.CopyrightFile = flags.Filename(filepath.Join(base, "LICENSE"))
}
_, _ = flags.Parse(m)
m.Shared.Spec = flags.Filename(path)
m.Shared.Target = flags.Filename(generated)
m.Shared.StrictResponders = strict
if err := m.Execute([]string{}); err != nil {
t.Error(err)
}
})
}
}
| apache-2.0 |
yeastrc/paws_Protein_Annotation_Web_Services | Protein_Annotation_Jobcenter_Modules/JobcenterModulesCommon/src/org/yeastrc/paws/utils/CreateShellScriptToRun.java | 2989 | package org.yeastrc.paws.utils;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import org.apache.log4j.Logger;
import org.yeastrc.paws.constants.ShellScriptToRunConstants;
/**
*
*
*/
public class CreateShellScriptToRun {
private static Logger log = Logger.getLogger(CreateShellScriptToRun.class);
/**
* @param commandToRun
* @param commandRunDirectory
* @return full path the shell script to run including name
* @throws Exception
*/
public static String createShellScriptToRun(
String commandToRun,
File commandRunDirectory
) throws Exception {
String directoryRunCommandInString = commandRunDirectory.getAbsolutePath();
String shellScriptFilename = ShellScriptToRunConstants.SHELL_SCRIPT_TO_RUN_FILENAME;
File shellScriptToRunFile = new File( commandRunDirectory, shellScriptFilename );
String shellScriptToRunFileWithPath = shellScriptToRunFile.getAbsolutePath(); // Returned from this method
StringBuilder commandRunInRunScriptSB = new StringBuilder();
commandRunInRunScriptSB.append( commandToRun );
commandRunInRunScriptSB.append( " > " );
commandRunInRunScriptSB.append( ShellScriptToRunConstants.SYSOUT_FILENAME );
commandRunInRunScriptSB.append( " 2> " );
commandRunInRunScriptSB.append( ShellScriptToRunConstants.SYSERR_FILENAME );
String finalCommandRunInRunScriptString = commandRunInRunScriptSB.toString();
BufferedWriter writer = null;
try {
writer = new BufferedWriter( new FileWriter( shellScriptToRunFile ) );
// Build the full shell script
writer.write( "#!/bin/bash" );
writer.newLine();
writer.newLine();
writer.write( "cd " );
writer.write( directoryRunCommandInString );
writer.newLine();
writer.write( "RETVAL=$?" );
writer.newLine();
writer.write( "if [ $RETVAL -ne 0 ]; then" );
writer.newLine();
writer.write( " echo failed cd " );
writer.write( directoryRunCommandInString );
writer.newLine();
writer.write( " exit 1" );
writer.newLine();
writer.write( "fi" );
writer.newLine();
writer.newLine();
writer.write( finalCommandRunInRunScriptString );
writer.newLine();
writer.newLine();
writer.write( "RETVAL=$?" );
writer.newLine();
writer.write( "if [ $RETVAL -ne 0 ]; then" );
writer.newLine();
writer.write( " echo failed run of command RETVAL: $RETVAL" );
writer.newLine();
writer.write( " exit $RETVAL" );
writer.newLine();
writer.write( "fi" );
writer.newLine();
writer.write( "" );
writer.newLine();
} finally {
if ( writer != null ) {
writer.close();
}
}
if ( ! shellScriptToRunFile.setExecutable( true ) ) {
String msg = "Failed to change generated shell script to executable";
log.error( msg );
throw new Exception( msg );
}
return shellScriptToRunFileWithPath;
}
}
| apache-2.0 |
centideo/bolt | storage/driver.azure/src/retry_policies.cpp | 5817 | // -----------------------------------------------------------------------------------------
// <copyright file="retry_policies.cpp" company="Microsoft">
// Copyright 2013 Microsoft Corporation
//
// 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.
// </copyright>
// -----------------------------------------------------------------------------------------
#include "stdafx.h"
#include "was/common.h"
#include "was/retry_policies.h"
namespace azure {
namespace storage {
retry_info retry_policy::evaluate(const retry_context& retry_context, operation_context context)
{
if (m_policy != nullptr)
{
return m_policy->evaluate(retry_context, context);
}
return retry_info();
}
retry_info basic_no_retry_policy::evaluate(const retry_context& retry_context, operation_context context)
{
UNREFERENCED_PARAMETER(retry_context);
UNREFERENCED_PARAMETER(context);
return retry_info();
}
retry_info basic_common_retry_policy::evaluate(const retry_context& retry_context, operation_context context)
{
if (retry_context.current_retry_count() >= m_max_attempts)
{
return retry_info();
}
// Retry interval of a request to a location must take the time spent sending requests
// to other locations into account. For example, assume a request was sent to the primary
// location first, then to the secondary, and then to the primary again. If it
// was supposed to wait 10 seconds between requests to the primary and the request to
// the secondary took 3 seconds in total, retry interval should only be 7 seconds, because
// in total, the requests will be 10 seconds apart from the primary locations' point of view.
// For this calculation, current instance of the retry policy stores timestamp of the last
// request to a specific location.
switch (retry_context.last_request_result().target_location())
{
case azure::storage::storage_location::primary:
m_last_primary_attempt = retry_context.last_request_result().end_time();
break;
case azure::storage::storage_location::secondary:
m_last_secondary_attempt = retry_context.last_request_result().end_time();
break;
}
bool secondary_not_found = (retry_context.last_request_result().http_status_code() == web::http::status_codes::NotFound) &&
(retry_context.last_request_result().target_location() == storage_location::secondary);
// Anything between 300 and 500 other than 408 should not be retried
if (retry_context.last_request_result().http_status_code() >= 300 &&
retry_context.last_request_result().http_status_code() < 500 &&
retry_context.last_request_result().http_status_code() != web::http::status_codes::RequestTimeout &&
!secondary_not_found)
{
return retry_info();
}
// Explicitly handle some 500 level status codes
if ((retry_context.last_request_result().http_status_code() == web::http::status_codes::NotImplemented) ||
(retry_context.last_request_result().http_status_code() == web::http::status_codes::HttpVersionNotSupported))
{
return retry_info();
}
retry_info result(retry_context);
if (secondary_not_found && (retry_context.current_location_mode() != location_mode::secondary_only))
{
result.set_updated_location_mode(location_mode::primary_only);
result.set_target_location(storage_location::primary);
}
return result;
}
void basic_common_retry_policy::align_retry_interval(retry_info& retry_info)
{
utility::datetime last_attempt;
switch (retry_info.target_location())
{
case azure::storage::storage_location::primary:
last_attempt = m_last_primary_attempt;
break;
case azure::storage::storage_location::secondary:
last_attempt = m_last_secondary_attempt;
break;
default:
return;
}
if (last_attempt.is_initialized())
{
auto since_last_attempt = std::chrono::seconds(utility::datetime::utc_now() - last_attempt);
retry_info.set_retry_interval(std::max(std::chrono::milliseconds::zero(), retry_info.retry_interval() - since_last_attempt));
}
else
{
retry_info.set_retry_interval(std::chrono::milliseconds::zero());
}
}
retry_info basic_linear_retry_policy::evaluate(const retry_context& retry_context, operation_context context)
{
auto result = basic_common_retry_policy::evaluate(retry_context, context);
if (result.should_retry())
{
result.set_retry_interval(m_delta_backoff);
align_retry_interval(result);
}
return result;
}
retry_info basic_exponential_retry_policy::evaluate(const retry_context& retry_context, operation_context context)
{
auto result = basic_common_retry_policy::evaluate(retry_context, context);
if (result.should_retry())
{
auto random_backoff = m_rand_distribution(m_rand_engine);
std::chrono::milliseconds increment(static_cast<std::chrono::milliseconds::rep>((std::pow(2, retry_context.current_retry_count()) - 1) * random_backoff * 1000));
auto interval = increment < std::chrono::milliseconds::zero() ? max_exponential_retry_interval : min_exponential_retry_interval + increment;
result.set_retry_interval(std::min(interval, max_exponential_retry_interval));
align_retry_interval(result);
}
return result;
}
}
} // namespace azure::storage | apache-2.0 |
infanprodigy/blog-iz | BlogEngine.Tests/PageTemplates/Admin/Profile.cs | 1725 | using WatiN.Core;
namespace BlogEngine.Tests.PageTemplates.Admin
{
public class Profile : Page
{
public string Url
{
get { return Constants.Root + "/admin/Users/Profile.aspx?id={0}"; }
}
public TextField FirstName { get { return Document.TextField(Find.ById("txtFirstName")); } }
public TextField LastName { get { return Document.TextField(Find.ById("txtLastName")); } }
public TextField MiddleName { get { return Document.TextField(Find.ById("txtMiddleName")); } }
public TextField DisplayName { get { return Document.TextField(Find.ById("txtDispalayName")); } }
public TextField Email { get { return Document.TextField(Find.ById("txtEmail")); } }
public TextField Birthday { get { return Document.TextField(Find.ById("txtBirthday")); } }
public TextField Photo { get { return Document.TextField(Find.ById("txtPhotoURL")); } }
public TextField Mobile { get { return Document.TextField(Find.ById("txtMobile")); } }
public TextField City { get { return Document.TextField(Find.ById("txtCity")); } }
public TextField MainPhone { get { return Document.TextField(Find.ById("txtMainPhone")); } }
public TextField State { get { return Document.TextField(Find.ById("txtState")); } }
public TextField Fax { get { return Document.TextField(Find.ById("txtFax")); } }
public TextField Country { get { return Document.TextField(Find.ById("txtCountry")); } }
public TextField Biography { get { return Document.TextField(Find.ById("biography")); } }
public Button BtnSave { get { return Document.Button(Find.ById("btnSave")); } }
}
}
| apache-2.0 |
exon-it/redmine-scala-client | client-api/src/main/scala/by/exonit/redmine/client/SavedQuery.scala | 878 | /*
* Copyright 2017 Exon IT
*
* 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 by.exonit.redmine.client
trait SavedQueryIdLike extends Identifiable[BigInt]
case class SavedQueryId(id: BigInt) extends SavedQueryIdLike
case class SavedQuery(
id: BigInt,
name: String,
project: Option[ProjectId],
isPublic: Option[Boolean]) extends SavedQueryIdLike
| apache-2.0 |
iotalking/mqtt-broker | www/dashboard/webpack.base.config.js | 1614 | const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
entry: {
main: './src/main',
vendors: './src/vendors'
},
output: {
path: path.join(__dirname, './dist')
},
module: {
rules: [{
test: /\.vue$/,
loader: 'vue-loader',
options: {
loaders: {
css: ExtractTextPlugin.extract({
use: ['css-loader', 'autoprefixer-loader'],
fallback: 'vue-style-loader'
})
}
}
},
{
test: /iview\/.*?js$/,
loader: 'babel-loader'
},
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
use: ['css-loader?minimize', 'autoprefixer-loader'],
fallback: 'style-loader'
})
},
{
test: /\.(gif|jpg|png|woff|svg|eot|ttf)\??.*$/,
loader: 'url-loader?limit=1024'
},
{
test: /\.(html|tpl)$/,
loader: 'html-loader'
}
]
},
resolve: {
extensions: ['.js', '.vue'],
alias: {
'vue': 'vue/dist/vue.esm.js'
}
}
}; | apache-2.0 |
bupt1987/JgFramework | src/main/java/com/zhaidaosi/game/jgframework/Boot.java | 15833 | package com.zhaidaosi.game.jgframework;
import com.zhaidaosi.game.jgframework.common.BaseIp;
import com.zhaidaosi.game.jgframework.common.BaseRunTimer;
import com.zhaidaosi.game.jgframework.common.BaseString;
import com.zhaidaosi.game.jgframework.common.cache.BaseLocalCached;
import com.zhaidaosi.game.jgframework.common.encrpt.BaseDes;
import com.zhaidaosi.game.jgframework.common.encrpt.BaseRsa;
import com.zhaidaosi.game.jgframework.common.spring.ServiceManager;
import com.zhaidaosi.game.jgframework.connector.AuthConnector;
import com.zhaidaosi.game.jgframework.connector.ManagerConnector;
import com.zhaidaosi.game.jgframework.connector.ServiceConnector;
import com.zhaidaosi.game.jgframework.model.action.ActionManager;
import com.zhaidaosi.game.jgframework.model.area.AreaManager;
import com.zhaidaosi.game.jgframework.model.entity.BasePlayerFactory;
import com.zhaidaosi.game.jgframework.model.entity.IBasePlayerFactory;
import com.zhaidaosi.game.jgframework.session.SessionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Properties;
import java.util.TimeZone;
public class Boot {
public static String BASE_PACKAGE_NAME;
public static String SDM_BASE_PACKAGE_NAME;
public static String SERVER_RSYNC_PACKAGE_PATH;
public static String SERVER_HANDLER_PACKAGE_PATH;
private static final Logger log = LoggerFactory.getLogger(Boot.class);
private final static String SERVER_PROPERTIES = "jgframework.properties";
private final static String ALL_STRING = "all";
private final static String SERVICE_STRING = "service";
private final static String AUTH_STRING = "auth";
private static String actionPackage;
private static String areaPackage;
private static int servicePort = 28080;
private static String serviceMode = ServiceConnector.MODE_WEB_SOCKET;
private static long serviceSyncPeriod = 60000;
private static int serviceThreadCount = 0;
private static int serviceHeartbeatTime = 60;
private static int serviceMaxLoginUser = 0;
private static ArrayList<String> serviceIps = new ArrayList<>();
private static int authPort = 18080;
private static int authThreadCount = 0;
private static String authHandler;
private static boolean debug = true;
private static ArrayList<String> memcacheServers = new ArrayList<>();
private static String memcacheKeyPrefix = "jg-";
private static Charset charset = Charset.forName("UTF-8");
private static int managerPort = 38080;
private static ArrayList<Long[]> managerAllowIps = new ArrayList<>();
private static String managerUser = "admin";
private static String managerPassword = "admin";
private static ServiceConnector serviceConnector = null;
private static ManagerConnector managerConnector = null;
private static AuthConnector authConnector = null;
private static String args = null;
private static IBasePlayerFactory playerFactory = new BasePlayerFactory();
private static boolean useSpring = true;
private static boolean init = false;
/**
* 初始化参数
* @return
*/
private static boolean init() {
if (init) {
return true;
}
boolean error = false;
try {
Properties pps = new Properties();
pps.load(Boot.class.getClassLoader().getResourceAsStream(SERVER_PROPERTIES));
BASE_PACKAGE_NAME = pps.getProperty("base.package.name");
if (BaseString.isEmpty(BASE_PACKAGE_NAME)) {
error = true;
log.error("base.package.name 必须填写");
}
SDM_BASE_PACKAGE_NAME = BASE_PACKAGE_NAME + ".sdm";
SERVER_RSYNC_PACKAGE_PATH = BASE_PACKAGE_NAME + ".rsync";
SERVER_HANDLER_PACKAGE_PATH = BASE_PACKAGE_NAME + ".handler";
//设置默认时间
if (!BaseString.isEmpty(pps.getProperty("time.zone"))) {
TimeZone.setDefault(TimeZone.getTimeZone(pps.getProperty("time.zone")));
}
//是否使用spring
if (!BaseString.isEmpty(pps.getProperty("useSpring"))) {
useSpring = pps.getProperty("useSpring").equals("true");
}
//设置运行模式
debug = "debug".equals(pps.getProperty("run.mode"));
if (debug) {
BaseRunTimer.toActive();
}
if (ALL_STRING.equals(args) || SERVICE_STRING.equals(args)) {
//service端
if (!BaseString.isEmpty(pps.getProperty("service.port"))) {
servicePort = Integer.valueOf(pps.getProperty("service.port"));
}
if (!BaseString.isEmpty(pps.getProperty("service.mode"))) {
serviceMode = pps.getProperty("service.mode");
}
if (!BaseString.isEmpty(pps.getProperty("service.threadCount"))) {
serviceThreadCount = Integer.valueOf(pps.getProperty("service.threadCount"));
}
if (!BaseString.isEmpty(pps.getProperty("service.syncPeriod"))) {
serviceSyncPeriod = Integer.valueOf(pps.getProperty("service.syncPeriod"));
if (serviceSyncPeriod < 3) {
error = true;
log.error("service.syncPeriod 必须大于3秒");
}
serviceSyncPeriod = serviceSyncPeriod * 1000;
}
if (!BaseString.isEmpty(pps.getProperty("service.heartbeatTime"))) {
serviceHeartbeatTime = Integer.valueOf(pps.getProperty("service.heartbeatTime"));
}
if (!BaseString.isEmpty(pps.getProperty("service.maxLoginUser"))) {
serviceMaxLoginUser = Integer.valueOf(pps.getProperty("service.maxLoginUser"));
}
}
if (ALL_STRING.equals(args) || AUTH_STRING.equals(args)) {
//auth端
if (!BaseString.isEmpty(pps.getProperty("service.ips"))) {
Collections.addAll(serviceIps, pps.getProperty("service.ips").split(";"));
} else {
error = true;
log.error("service.ips 必须填写");
}
if (!BaseString.isEmpty(pps.getProperty("auth.port"))) {
authPort = Integer.valueOf(pps.getProperty("auth.port"));
}
if (!BaseString.isEmpty(pps.getProperty("auth.threadCount"))) {
authThreadCount = Integer.valueOf(pps.getProperty("auth.threadCount"));
}
if (!BaseString.isEmpty(pps.getProperty("auth.handler"))) {
authHandler = pps.getProperty("auth.handler");
} else {
error = true;
log.error("auth.handler 必须填写");
}
}
//manager端
if (!BaseString.isEmpty(pps.getProperty("manager.port"))) {
managerPort = Integer.valueOf(pps.getProperty("manager.port"));
}
if (!BaseString.isEmpty(pps.getProperty("manager.user"))) {
managerUser = pps.getProperty("manager.user");
}
if (!BaseString.isEmpty(pps.getProperty("manager.password"))) {
managerPassword = pps.getProperty("manager.password");
}
String[] ips;
if (!BaseString.isEmpty(pps.getProperty("manager.allowIps"))) {
ips = pps.getProperty("manager.allowIps").split(";");
} else {
ips = new String[]{"127.0.0.1"};
}
setManagerAllowIps(ips);
//memcache
if (!BaseString.isEmpty(pps.getProperty("memcache.servers"))) {
Collections.addAll(memcacheServers, pps.getProperty("memcache.servers").split(";"));
} else {
memcacheServers.add("127.0.0.1:11211,1");
}
if (!BaseString.isEmpty(pps.getProperty("memcache.keyPrefix"))) {
memcacheKeyPrefix = pps.getProperty("memcache.keyPrefix");
}
//des密钥
if (!BaseString.isEmpty(pps.getProperty("des.key"))) {
BaseDes.setDesKey(pps.getProperty("des.key"));
}
//rsa密钥
if (!BaseString.isEmpty(pps.getProperty("rsa.publicKey")) && !BaseString.isEmpty(pps.getProperty("rsa.privateKey"))) {
BaseRsa.init(pps.getProperty("rsa.publicKey"), pps.getProperty("rsa.privateKey"));
}
//系统字符集
if (!BaseString.isEmpty(pps.getProperty("charset"))) {
charset = Charset.forName(pps.getProperty("charset"));
}
} catch (Exception e) {
error = true;
log.error("系统启动失败", e);
}
if (!error) {
init = true;
}
return init;
}
/**
* 设置允许ip段
* @param ips
*/
private static void setManagerAllowIps(String[] ips) {
for (String ip : ips) {
managerAllowIps.add(BaseIp.stringToIp(ip));
}
}
/**
* 设置扫描action的包路径,例如:com.zhaidaosi.game.server.model.action
* @param actionPackage
*/
public static void setActionPackage(String actionPackage) {
Boot.actionPackage = actionPackage;
}
/**
* 设置扫描area的包路径,例如:com.zhaidaosi.game.server.model.area
* @param areaPackage
*/
public static void setAreaPackage(String areaPackage) {
Boot.areaPackage = areaPackage;
}
/**
* 获取player的工厂,默认是BasePlayerFactory
* @return
*/
public static IBasePlayerFactory getPlayerFactory() {
return playerFactory;
}
/**
* 设置player的工厂,默认是BasePlayerFactory
* @param playerFactory
*/
public static void setPlayerFactory(IBasePlayerFactory playerFactory) {
Boot.playerFactory = playerFactory;
}
/**
* 设置mc的前缀
* @return
*/
public static String getMemcacheKeyPrefix() {
return memcacheKeyPrefix;
}
/**
* 获取service的连接对象
* @return
*/
public static ServiceConnector getServiceConnector() {
return serviceConnector;
}
/**
* 获取auth的连接对象
* @return
*/
public static AuthConnector getAuthConnector() {
return authConnector;
}
/**
* 获取manager服务端口
* @return
*/
public static int getManagerPort() {
return managerPort;
}
/**
* 获取manager允许访问的ip段
* @return
*/
public static ArrayList<Long[]> getManagerAllowIps() {
return managerAllowIps;
}
/**
* 获取manager的登录用户
* @return
*/
public static String getManagerUser() {
return managerUser;
}
/**
* 获取manager的用户密码
* @return
*/
public static String getManagerPassword() {
return managerPassword;
}
/**
* 获取默认字符集
* @return
*/
public static Charset getCharset() {
return charset;
}
/**
* service服务器工作线程数
* @return
*/
public static int getServiceThreadCount() {
return serviceThreadCount;
}
/**
* 认证服务器工作线程数
* @return
*/
public static int getAuthThreadCount() {
return authThreadCount;
}
/**
* 返回所有的memcache配置
* @return
*/
public static ArrayList<String> getMemcacheServers() {
return memcacheServers;
}
/**
* 返回所有service服务器ip
* @return
*/
public static ArrayList<String> getServiceIps() {
return serviceIps;
}
/**
* 返回认证服务的所有handler
* @return
*/
public static String getAuthHandler() {
return authHandler;
}
/**
* 返回服务器端口
* @return
*/
public static int getServicePort() {
return servicePort;
}
/**
* 返回service服务器个数
* @return
*/
public static int getServiceCount() {
return serviceIps.size();
}
/**
* 返回service的同步间隔
* @return
*/
public static long getServiceSyncPeriod() {
return serviceSyncPeriod;
}
/**
* 获取心跳检查时间
* @return
*/
public static int getServiceHeartbeatTime() {
return serviceHeartbeatTime;
}
/**
* 通过ip返回service的连接地址
* @param ip
* @return
*/
public static String getServiceAddress(String ip) {
if (serviceMode.equals(ServiceConnector.MODE_SOCKET)) {
return ip + ":" + servicePort;
} else {
return "ws://" + ip + ":" + servicePort + ServiceConnector.WEB_SOCKET_PATH;
}
}
/**
* 是否开启debug模式
* @return
*/
public static boolean getDebug() {
return debug;
}
/**
* 重启服务
*/
public static void restart() {
stop();
start();
}
/**
* 停止服务
*/
public static void stop() {
BaseLocalCached.cancelTimer();
if (authConnector != null) {
authConnector.stop();
}
if (serviceConnector != null) {
serviceConnector.stop();
}
if (managerConnector != null) {
managerConnector.stop();
}
}
/**
* 启动服务
*/
public static void start() {
start(Boot.args);
}
/**
* 启动服务
* @param args ALL_STRING,SERVICE_STRING,AUTH_STRING
*/
public static void start(String args) {
if (Boot.args == null) {
Boot.args = args == null ? ALL_STRING : args;
}
if (!Boot.ALL_STRING.equals(Boot.args) && !Boot.SERVICE_STRING.equals(Boot.args) & !Boot.AUTH_STRING.equals(Boot.args)) {
Boot.args = args = ALL_STRING;
}
//初始化参数
if (init()) {
//加载spring
if (useSpring) {
ServiceManager.init();
}
//开启本地缓存清理任务
BaseLocalCached.startTimer();
//加载路由
Router.init();
if (args == null || args.equals(ALL_STRING) || args.equals(SERVICE_STRING)) {
//加载动作
ActionManager.initAction(actionPackage);
//加载区域
AreaManager.initArea(areaPackage);
if (serviceMaxLoginUser > 0) {
SessionManager.setMaxUser(serviceMaxLoginUser);
} else {
serviceMaxLoginUser = 0;
}
if (serviceConnector == null) {
serviceConnector = new ServiceConnector(servicePort, serviceSyncPeriod, serviceMode);
}
serviceConnector.start();
if (managerConnector == null) {
managerConnector = new ManagerConnector(managerPort);
}
managerConnector.start();
}
if (args == null || args.equals(ALL_STRING) || args.equals(AUTH_STRING)) {
if (authConnector == null) {
authConnector = new AuthConnector(authPort);
}
authConnector.start();
}
}
}
}
| apache-2.0 |
mcoblenz/Glacier | tests/glacier/ImmutablePrimitiveContainer.java | 194 | import edu.cmu.cs.glacier.qual.Immutable;
@Immutable
public class ImmutablePrimitiveContainer {
int x;
public void setX(int x) {
// ::error: (glacier.assignment)
this.x = x;
}
}
| apache-2.0 |
stdlib-js/www | lib/server/lib/routes/package_tree_array.js | 1862 | /**
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib 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.
*/
'use strict';
// MODULES //
var resolve = require( 'path' ).resolve;
var fs = require( 'fs' );
// VARIABLES //
var FOPTS = {
'encoding': 'utf8'
};
// MAIN //
/**
* Defines a route handler for returning package tree array for a requested documentation version.
*
* @private
* @param {Options} opts - options
* @param {string} opts.root - root documentation directory
* @returns {Object} route declaration
*/
function route( opts ) {
var schema = {
'method': 'GET',
'url': '/docs/api/:version/package_tree_array.json',
'schema': {
'response': {
'200': {
'type': 'string'
}
}
},
'handler': onRequest
};
return schema;
/**
* Callback invoked upon receiving an HTTP request.
*
* @private
* @param {Object} request - request object
* @param {Object} reply - reply object
* @returns {void}
*/
function onRequest( request, reply ) {
var p;
var v;
v = request.params.version;
request.log.info( 'Version: %s', v );
p = resolve( opts.root, v, 'package_tree_array.json' );
request.log.info( 'Resolved path: %s', p );
request.log.info( 'Returning file.' );
reply.type( 'application/json' );
reply.send( fs.createReadStream( p, FOPTS ) );
}
}
// EXPORTS //
module.exports = route;
| apache-2.0 |
zhi6666/coolweather | app/src/main/java/com/coolweather/android/MainActivity.java | 2126 | package com.coolweather.android;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import com.coolweather.android.util.BaseActivity;
import com.coolweather.android.util.LogUtil;
public class MainActivity extends BaseActivity implements ChooseAreaFragment.BackHandlerInterface{
private static final String TAG = "MainActivity";
private ChooseAreaFragment chooseAreaFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Build.VERSION.SDK_INT >= 21) {
View decorView = getWindow().getDecorView();
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
getWindow().setStatusBarColor(Color.TRANSPARENT);
}
setContentView(R.layout.activity_main);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
LogUtil.d(TAG, "onCreate: " + preferences.getString(WeatherActivity.WEATHER_INFO_BODY, null));
//在程序一启动时就先从 SharedPreferences 文件读取缓存数据,如果不为 null 则说明之前已经请求过天气数据了,就可以跳过再次选择城市跳转到 WeatherActivity
if (preferences.getString(WeatherActivity.WEATHER_INFO_BODY, null) != null) {
Intent intent = new Intent(this, WeatherActivity.class);
intent.putExtra("activity_name", "MainActivity");
startActivity(intent);
finish();
}
}
@Override
public void setSelectedFragment(ChooseAreaFragment chooseAreaFragment) {
this.chooseAreaFragment = chooseAreaFragment;
}
@Override
public void onBackPressed() {
if (chooseAreaFragment == null || !chooseAreaFragment.onBackPressed()) {
super.onBackPressed();
}
}
}
| apache-2.0 |
pierreyves-jegou/CloneManager | CloneManager-GUI/src/main/java/caillou/company/clonemanager/gui/bean/impl/VisitDirectoriesResult.java | 885 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package caillou.company.clonemanager.gui.bean.impl;
import caillou.company.clonemanager.background.bean.applicationFile.contract.ApplicationFile;
import java.util.Set;
/**
*
* @author pierre
*/
public class VisitDirectoriesResult {
private Long byteToTreat;
private Set<ApplicationFile> filesToTreat;
public Long getByteToTreat() {
return byteToTreat;
}
public void setByteToTreat(Long byteToTreat) {
this.byteToTreat = byteToTreat;
}
public Set<ApplicationFile> getFilesToTreat() {
return filesToTreat;
}
public void setFilesToTreat(Set<ApplicationFile> filesToTreat) {
this.filesToTreat = filesToTreat;
}
}
| apache-2.0 |
otto-de/flummi | src/test/java/de/otto/flummi/IndicesAdminClientTest.java | 17270 | package de.otto.flummi;
import com.google.gson.JsonObject;
import de.otto.flummi.request.CreateIndexRequestBuilder;
import de.otto.flummi.request.DeleteIndexRequestBuilder;
import de.otto.flummi.request.IndicesExistsRequestBuilder;
import de.otto.flummi.response.HttpServerErrorException;
import de.otto.flummi.util.HttpClientWrapper;
import org.asynchttpclient.BoundRequestBuilder;
import org.asynchttpclient.ListenableFuture;
import org.asynchttpclient.Response;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.List;
import java.util.concurrent.ExecutionException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.*;
public class IndicesAdminClientTest {
private IndicesAdminClient indicesAdminClient;
private HttpClientWrapper httpClient;
private BoundRequestBuilder boundRequestBuilder;
@BeforeMethod
public void setup() {
httpClient = mock(HttpClientWrapper.class);
indicesAdminClient = new IndicesAdminClient(httpClient);
boundRequestBuilder = mock(BoundRequestBuilder.class);
when(httpClient.prepareGet(anyString())).thenReturn(boundRequestBuilder);
/* when(asyncHttpClient.prepareDelete(anyString())).thenReturn(boundRequestBuilder);
when(asyncHttpClient.preparePost(anyString())).thenReturn(boundRequestBuilder);
when(boundRequestBuilder.setBody(anyString())).thenReturn(boundRequestBuilder);
*/
}
@Test
public void shouldPrepareCreate() throws ExecutionException, InterruptedException, IOException {
//Given
when(httpClient.preparePut(anyString())).thenReturn(boundRequestBuilder);
when(boundRequestBuilder.setBody(anyString())).thenReturn(boundRequestBuilder);
when(boundRequestBuilder.setCharset(Charset.forName("UTF-8"))).thenReturn(boundRequestBuilder);
when(boundRequestBuilder.addHeader(anyString(),anyString())).thenReturn(boundRequestBuilder);
final ListenableFuture<Response> listenableFuture = mock(ListenableFuture.class);
when(boundRequestBuilder.execute()).thenReturn(listenableFuture);
final Response response = mock(Response.class);
when(listenableFuture.get()).thenReturn(response);
when(response.getStatusCode()).thenReturn(200);
when(response.getResponseBody()).thenReturn("{\"acknowledged\":\"true\"}");
final CreateIndexRequestBuilder createIndexRequestBuilder = indicesAdminClient.prepareCreate("someIndexName");
//When
createIndexRequestBuilder.execute();
//Then
verify(httpClient).preparePut("/someIndexName");
}
@Test
public void shouldPrepareExists() throws ExecutionException, InterruptedException, IOException {
//Given
when(httpClient.prepareHead(anyString())).thenReturn(boundRequestBuilder);
when(boundRequestBuilder.setBody(anyString())).thenReturn(boundRequestBuilder);
when(boundRequestBuilder.addHeader(anyString(),anyString())).thenReturn(boundRequestBuilder);
final ListenableFuture<Response> listenableFuture = mock(ListenableFuture.class);
when(boundRequestBuilder.execute()).thenReturn(listenableFuture);
final Response response = mock(Response.class);
when(listenableFuture.get()).thenReturn(response);
when(response.getStatusCode()).thenReturn(200);
final IndicesExistsRequestBuilder indicesExistsRequestBuilder = indicesAdminClient.prepareExists("someIndexName");
//When
indicesExistsRequestBuilder.execute();
//Then
verify(httpClient).prepareHead("/someIndexName");
}
@Test
public void shouldPrepareDelete() throws ExecutionException, InterruptedException {
//Given
when(httpClient.prepareDelete(anyString())).thenReturn(boundRequestBuilder);
when(boundRequestBuilder.setBody(anyString())).thenReturn(boundRequestBuilder);
when(boundRequestBuilder.addHeader(anyString(),anyString())).thenReturn(boundRequestBuilder);
final ListenableFuture<Response> listenableFuture = mock(ListenableFuture.class);
when(boundRequestBuilder.execute()).thenReturn(listenableFuture);
final Response response = mock(Response.class);
when(listenableFuture.get()).thenReturn(response);
when(response.getStatusCode()).thenReturn(200);
final DeleteIndexRequestBuilder deleteIndexRequestBuilder = indicesAdminClient.prepareDelete("someIndexName");
//When
deleteIndexRequestBuilder.execute();
//Then
verify(httpClient).prepareDelete("/someIndexName");
}
@Test
public void shouldReturnAliasExists() throws ExecutionException, InterruptedException, IOException {
//Given
when(boundRequestBuilder.addHeader(anyString(),anyString())).thenReturn(boundRequestBuilder);
when(boundRequestBuilder.execute()).thenReturn(new CompletedFuture(new MockResponse(200, "OK", "{\"someIndexName\":{\"aliases\": {\"someAlias\": {}}}}")));
//When
final boolean aliasExists = indicesAdminClient.aliasExists("someAlias");
//Then
assertThat(aliasExists, is(true));
verify(httpClient).prepareGet("/_aliases");
}
@Test
public void shouldReturnAliasNotExists() throws ExecutionException, InterruptedException, IOException {
//Given
when(boundRequestBuilder.addHeader(anyString(),anyString())).thenReturn(boundRequestBuilder);
when(boundRequestBuilder.execute()).thenReturn(new CompletedFuture(new MockResponse(200, "OK", "{\"someIndexName\":{\"aliases\": {\"someOtherAlias\": {}}}}")));
//When
final boolean aliasExists = indicesAdminClient.aliasExists("someAlias");
//Then
assertThat(aliasExists, is(false));
verify(httpClient).prepareGet("/_aliases");
}
@Test(expectedExceptions = HttpServerErrorException.class)
public void shouldReturnAliasNotExistsFor500() throws ExecutionException, InterruptedException, IOException {
//Given
when(boundRequestBuilder.addHeader(anyString(),anyString())).thenReturn(boundRequestBuilder);
when(boundRequestBuilder.execute()).thenReturn(new CompletedFuture(new MockResponse(500, "Internal Server Error", "{\"someIndexName\":{\"aliases\": {\"someAlias\": {}}}}")));
//When
indicesAdminClient.aliasExists("someAlias");
}
@Test
public void shouldGetAllIndexNames() throws ExecutionException, InterruptedException, IOException {
//Given
when(boundRequestBuilder.addHeader(anyString(),anyString())).thenReturn(boundRequestBuilder);
when(boundRequestBuilder.execute()).thenReturn(new CompletedFuture(new MockResponse(200, "OK", "{\"someIndexName\":{}, \"someIndexName2\":{}, \"someIndexName3\":{}}")));
//When
final List<String> allIndexNames = indicesAdminClient.getAllIndexNames();
//Then
verify(httpClient).prepareGet("/_all");
assertThat(allIndexNames, hasSize(3));
assertThat(allIndexNames.get(0), is("someIndexName"));
assertThat(allIndexNames.get(1), is("someIndexName2"));
assertThat(allIndexNames.get(2), is("someIndexName3"));
}
@Test
public void shouldNotGetAllIndexNamesForEmptyResponse() throws ExecutionException, InterruptedException, IOException {
//Given
when(boundRequestBuilder.addHeader(anyString(),anyString())).thenReturn(boundRequestBuilder);
when(boundRequestBuilder.execute()).thenReturn(new CompletedFuture(new MockResponse(200, "OK", "{}")));
//When
final List<String> allIndexNames = indicesAdminClient.getAllIndexNames();
//Then
verify(httpClient).prepareGet("/_all");
assertThat(allIndexNames, hasSize(0));
}
@Test(expectedExceptions = HttpServerErrorException.class)
public void shouldNotGetAllIndexNamesForErrorResponseCode() throws ExecutionException, InterruptedException, IOException {
//Given
when(boundRequestBuilder.addHeader(anyString(),anyString())).thenReturn(boundRequestBuilder);
when(boundRequestBuilder.execute()).thenReturn(new CompletedFuture(new MockResponse(500, "OK", "{}")));
//When
indicesAdminClient.getAllIndexNames();
}
@Test
public void shouldGetIndexSettings() throws ExecutionException, InterruptedException, IOException {
//Given
when(boundRequestBuilder.addHeader(anyString(),anyString())).thenReturn(boundRequestBuilder);
when(boundRequestBuilder.execute()).thenReturn(new CompletedFuture(new MockResponse(200, "OK", "{\"jobs-test\": {\n" +
" \"settings\": {\n" +
" \"index\": {\n" +
" \"creation_date\": \"1461567339233\",\n" +
" \"number_of_shards\": \"5\",\n" +
" \"number_of_replicas\": \"0\",\n" +
" \"version\": {\n" +
" \"created\": \"1070199\"\n" +
" },\n" +
" \"uuid\": \"Ua_7izawQUaSYclxHyWxUA\"\n" +
" }\n" +
" }\n" +
" }}")));
//When
final JsonObject indexSettings = indicesAdminClient.getIndexSettings();
//Then
final JsonObject indexJsonObject = indexSettings.get("jobs-test").getAsJsonObject().get("settings").getAsJsonObject().get("index").getAsJsonObject();
assertThat(indexJsonObject.get("creation_date").getAsString(), is("1461567339233"));
assertThat(indexJsonObject.get("number_of_shards").getAsString(), is("5"));
assertThat(indexJsonObject.get("number_of_replicas").getAsString(), is("0"));
assertThat(indexJsonObject.get("uuid").getAsString(), is("Ua_7izawQUaSYclxHyWxUA"));
assertThat(indexJsonObject.get("version").getAsJsonObject().get("created").getAsString(), is("1070199"));
verify(httpClient).prepareGet("/_all/_settings");
}
@Test(expectedExceptions = HttpServerErrorException.class)
public void shouldGetIndexSettingsForErrorResponseCode() throws ExecutionException, InterruptedException, IOException {
//Given
when(boundRequestBuilder.addHeader(anyString(),anyString())).thenReturn(boundRequestBuilder);
when(boundRequestBuilder.execute()).thenReturn(new CompletedFuture(new MockResponse(500, "Internal Server Error", "{\"jobs-test\": {\n" +
" \"settings\": {\n" +
" \"index\": {\n" +
" \"creation_date\": \"1461567339233\",\n" +
" \"number_of_shards\": \"5\",\n" +
" \"number_of_replicas\": \"0\",\n" +
" \"version\": {\n" +
" \"created\": \"1070199\"\n" +
" },\n" +
" \"uuid\": \"Ua_7izawQUaSYclxHyWxUA\"\n" +
" }\n" +
" }\n" +
" }}")));
//When
indicesAdminClient.getIndexSettings();
}
@Test
public void shouldGetIndexSettingsForEmptyResponse() throws ExecutionException, InterruptedException, IOException {
//Given
when(boundRequestBuilder.addHeader(anyString(),anyString())).thenReturn(boundRequestBuilder);
when(boundRequestBuilder.execute()).thenReturn(new CompletedFuture(new MockResponse(200, "OK", "{}")));
//When
final JsonObject indexSettings = indicesAdminClient.getIndexSettings();
//Then
assertThat(indexSettings.entrySet().size(), is(0));
}
@Test
public void shouldGetIndexMapping() throws ExecutionException, InterruptedException, IOException {
//Given
when(boundRequestBuilder.addHeader(anyString(),anyString())).thenReturn(boundRequestBuilder);
when(boundRequestBuilder.execute()).thenReturn(new CompletedFuture(new MockResponse(200, "OK", ""+
"{\"mapping-test\" : {\n" +
" \"mappings\" : {\n" +
" \"default\" : {\n" +
" \"properties\" : {\n" +
" \"test-string\" : {\n" +
" \"type\" : \"string\"\n" +
" }\n" +
" }\n" +
" }\n" +
" }\n" +
" }}")));
//When
final JsonObject indexSettings = indicesAdminClient.getIndexMapping("mapping-test");
//Then
final JsonObject indexJsonObject = indexSettings
.get("mapping-test").getAsJsonObject()
.get("mappings").getAsJsonObject()
.get("default").getAsJsonObject()
.get("properties").getAsJsonObject();
assertThat(indexJsonObject.get("test-string").getAsJsonObject().get("type").getAsString(), is("string"));
verify(httpClient).prepareGet("/mapping-test/_mapping");
}
@Test
public void shouldRefreshIndex() throws ExecutionException, InterruptedException {
when(httpClient.preparePost(anyString())).thenReturn(boundRequestBuilder);
when(boundRequestBuilder.addHeader(anyString(),anyString())).thenReturn(boundRequestBuilder);
when(boundRequestBuilder.execute()).thenReturn(new CompletedFuture(new MockResponse(200, "OK", "{}")));
//When
indicesAdminClient.prepareRefresh("someIndexName").execute();
//Then
verify(httpClient).preparePost("/someIndexName/_refresh");
}
@Test
public void shouldForceMergeOfIndex() throws ExecutionException, InterruptedException {
when(httpClient.preparePost(anyString())).thenReturn(boundRequestBuilder);
when(boundRequestBuilder.addHeader(anyString(),anyString())).thenReturn(boundRequestBuilder);
when(boundRequestBuilder.execute()).thenReturn(new CompletedFuture(new MockResponse(200, "OK", "{}")));
//When
indicesAdminClient.forceMerge("someIndexName").execute();
//Then
verify(httpClient).preparePost("/someIndexName/_forcemerge");
}
@Test(expectedExceptions = HttpServerErrorException.class)
public void shouldFailToRefreshIndexForErrorResponse() throws ExecutionException, InterruptedException {
when(httpClient.preparePost(anyString())).thenReturn(boundRequestBuilder);
when(boundRequestBuilder.addHeader(anyString(),anyString())).thenReturn(boundRequestBuilder);
when(boundRequestBuilder.execute()).thenReturn(new CompletedFuture(new MockResponse(500, "Internal Server Error", "{\"errors\":\"true\"}")));
//When
indicesAdminClient.prepareRefresh("someIndexName").execute();
}
@Test
public void shouldPointProductAliasToCurrentIndex() throws ExecutionException, InterruptedException, IOException {
//Given
when(httpClient.preparePost(anyString())).thenReturn(boundRequestBuilder);
when(boundRequestBuilder.setBody(anyString())).thenReturn(boundRequestBuilder);
when(boundRequestBuilder.addHeader(anyString(),anyString())).thenReturn(boundRequestBuilder);
when(boundRequestBuilder.execute()).thenReturn(new CompletedFuture(new MockResponse(200, "OK", "{\"acknowledged\":true}")));
//When
indicesAdminClient.pointAliasToCurrentIndex("someAliasName", "someIndexName");
//Then
verify(httpClient).preparePost("/_aliases");
verify(boundRequestBuilder).setBody("{\"actions\":[{\"remove\":{\"index\":\"*\",\"alias\":\"someAliasName\"}},{\"add\":{\"index\":\"someIndexName\",\"alias\":\"someAliasName\"}}]}");
}
@Test(expectedExceptions = RuntimeException.class)
public void shouldNotPointProductAliasToCurrentIndexForAcknowledgedFalse() throws ExecutionException, InterruptedException, IOException {
//Given
when(boundRequestBuilder.addHeader(anyString(),anyString())).thenReturn(boundRequestBuilder);
when(boundRequestBuilder.execute()).thenReturn(new CompletedFuture(new MockResponse(200, "OK", "{\"acknowledged\":false}")));
//When
indicesAdminClient.pointAliasToCurrentIndex("someAliasName", "someIndexName");
}
@Test(expectedExceptions = HttpServerErrorException.class)
public void shouldNotPointProductAliasToCurrentIndexForErrorResponseCode() throws ExecutionException, InterruptedException, IOException {
//Given
when(httpClient.preparePost(anyString())).thenReturn(boundRequestBuilder);
when(boundRequestBuilder.setBody(anyString())).thenReturn(boundRequestBuilder);
when(boundRequestBuilder.addHeader(anyString(),anyString())).thenReturn(boundRequestBuilder);
when(boundRequestBuilder.execute()).thenReturn(new CompletedFuture(new MockResponse(500, "Internal Server Error", "{\"errors\":\"true\"}")));
//When
indicesAdminClient.pointAliasToCurrentIndex("someAliasName", "someIndexName");
}
} | apache-2.0 |
tensorflow/java | tensorflow-core/tensorflow-core-api/src/gen/java/org/tensorflow/proto/distruntime/ClusterDefOrBuilder.java | 1352 | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: tensorflow/core/protobuf/cluster.proto
package org.tensorflow.proto.distruntime;
public interface ClusterDefOrBuilder extends
// @@protoc_insertion_point(interface_extends:tensorflow.ClusterDef)
com.google.protobuf.MessageOrBuilder {
/**
* <pre>
* The jobs that comprise the cluster.
* </pre>
*
* <code>repeated .tensorflow.JobDef job = 1;</code>
*/
java.util.List<org.tensorflow.proto.distruntime.JobDef>
getJobList();
/**
* <pre>
* The jobs that comprise the cluster.
* </pre>
*
* <code>repeated .tensorflow.JobDef job = 1;</code>
*/
org.tensorflow.proto.distruntime.JobDef getJob(int index);
/**
* <pre>
* The jobs that comprise the cluster.
* </pre>
*
* <code>repeated .tensorflow.JobDef job = 1;</code>
*/
int getJobCount();
/**
* <pre>
* The jobs that comprise the cluster.
* </pre>
*
* <code>repeated .tensorflow.JobDef job = 1;</code>
*/
java.util.List<? extends org.tensorflow.proto.distruntime.JobDefOrBuilder>
getJobOrBuilderList();
/**
* <pre>
* The jobs that comprise the cluster.
* </pre>
*
* <code>repeated .tensorflow.JobDef job = 1;</code>
*/
org.tensorflow.proto.distruntime.JobDefOrBuilder getJobOrBuilder(
int index);
}
| apache-2.0 |
marcovc/casper | test/getResults.py | 829 | #!/usr/bin/env python
# -*- coding: iso-8859-1 -*-
def getTestsField(filename,field):
from Ft.Xml import Parse
r = dict()
doc = Parse(filename)
testsuite = doc.documentElement
tests = testsuite.xpath('.//test')
for test in tests:
if test.xpath('string(result)')=="ok":
testName=test.xpath('string(name)')
r[testName]=test.xpath(field)
return r
def getTime(file1):
secs1=getTestsField(file1,"number(secs)")
for i in secs1.keys():
print i,
for i in secs1.keys():
print secs1[i],
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description='Get timings from BenchmarkResults.xml file')
parser.add_argument('xml', nargs=1,
help='path to the source BenchmarkResults.xml file to store')
args = parser.parse_args()
getTime(args.xml[0])
| apache-2.0 |
nano-projects/nano-framework | nano-orm/nano-orm-jedis/src/test/java/org/nanoframework/orm/jedis/cluster/SetTests.java | 3621 | /*
* Copyright 2015-2016 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.nanoframework.orm.jedis.cluster;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;
import org.junit.Assert;
import org.junit.Test;
import org.nanoframework.commons.support.logging.Logger;
import org.nanoframework.commons.support.logging.LoggerFactory;
import org.nanoframework.orm.jedis.RedisClientInitialize;
import com.alibaba.fastjson.TypeReference;
import com.google.common.collect.Lists;
import redis.clients.jedis.ScanParams;
import redis.clients.jedis.ScanResult;
/**
*
* @author yanghe
* @since 0.0.1
*/
public class SetTests extends RedisClientInitialize {
protected static final Logger LOGGER = LoggerFactory.getLogger(SetTests.class);
@Test
public void setTest() {
try {
final TypeReference<Integer> type = new TypeReference<Integer>() {
};
Assert.assertEquals(redisClient.sadd("setTest", 1, 2, 3), 3);
Assert.assertEquals(redisClient.sreplace("setTest", Lists.newArrayList(1, 2, 3), Lists.newArrayList(4, 5, 6)), 3);
Assert.assertEquals(redisClient.scard("setTest"), 3);
Assert.assertEquals(redisClient.sismember("setTest", 5), true);
final Set<Integer> members = redisClient.smembers("setTest", type);
Assert.assertEquals(members.size(), 3);
Integer member = redisClient.spop("setTest", type);
Assert.assertNotNull(member);
Integer member2 = redisClient.srandmember("setTest", type);
Assert.assertNotNull(member2);
List<Integer> member3 = redisClient.srandmember("setTest", 2, type);
Assert.assertEquals(member3.size(), 2);
Assert.assertEquals(redisClient.sadd("setTest", 1, 2, 3), 3);
Assert.assertEquals(redisClient.srem("setTest", 2, 3), 2);
Assert.assertEquals(redisClient.del("setTest"), 1);
} catch (final Throwable e) {
if (e instanceof AssertionError) {
throw e;
}
LOGGER.error(e.getMessage());
}
}
@Test
public void sscanTest() {
final String key = "sscan.test";
final String prefix = "sscan.test-";
try {
final List<String> values = Lists.newArrayList();
for (int idx = 0; idx < 1000; idx++) {
values.add(prefix + idx);
}
redisClient.sadd(key, values.toArray(new String[values.size()]));
final AtomicLong cursor = new AtomicLong(-1);
final ScanParams params = new ScanParams().count(10);
while (cursor.get() == -1 || cursor.get() > 0) {
if (cursor.get() == -1) {
cursor.set(0);
}
final ScanResult<String> res = redisClient.sscan(key, cursor.get(), params);
cursor.set(Long.valueOf(res.getStringCursor()));
}
} finally {
redisClient.del(key);
}
}
}
| apache-2.0 |
jlpedrosa/camel | components/camel-kafka/src/main/java/org/apache/camel/component/kafka/KafkaConstants.java | 2009 | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.apache.camel.component.kafka;
public final class KafkaConstants {
public static final String PARTITION_KEY = "kafka.PARTITION_KEY";
public static final String PARTITION = "kafka.EXCHANGE_NAME";
public static final String KEY = "kafka.CONTENT_TYPE";
public static final String TOPIC = "kafka.TOPIC";
public static final String OFFSET = "kafka.OFFSET";
public static final String KAFKA_DEFAULT_ENCODER = "kafka.serializer.DefaultEncoder";
public static final String KAFKA_STRING_ENCODER = "kafka.serializer.StringEncoder";
public static final String KAFKA_DEFAULT_SERIALIZER = "org.apache.kafka.common.serialization.StringSerializer";
public static final String KAFKA_DEFAULT_DESERIALIZER = "org.apache.kafka.common.serialization.StringDeserializer";
public static final String KAFKA_DEFAULT_PARTITIONER = "org.apache.kafka.clients.producer.internals.DefaultPartitioner";
public static final String PARTITIONER_RANGE_ASSIGNOR = "org.apache.kafka.clients.consumer.RangeAssignor";
public static final String KAFKA_RECORDMETA = "org.apache.kafka.clients.producer.RecordMetadata";
private KafkaConstants() {
// Utility class
}
}
| apache-2.0 |
cargografias/cargo-admin-panel | public/app/controllers/organizationEdit.js | 2912 | angular.module('cargoNgApp')
.controller('OrganizationEditController', function($scope, $modalInstance, $http, item) {
$scope.item = {};
var mode = $scope.mode = item ? 'edit' : 'add';
if("edit" == mode){
loadItem(item.id);
}
function loadOrganizationName(){
var url = "https://" + window.__bootstrapData.user.popitUrl + "/api/v0.1/organizations/" + item.parent_id + "?embed="
$http.get(url).then(function(response){
$scope.organization_name = response.data.result.name
})
}
$scope.save = function(){
var itemToSave = angular.extend({}, $scope.item);
var url = "/proxy/organizations" + ( 'edit' == mode ? ( "/" + item.id) : '' ) ;
$http({
method: 'edit' == mode ? 'PUT' : 'POST',
url: url,
data: itemToSave,
}).success(function(result){
if("ok" != result.status){
if(result.errors){
alert(result.errors.join('\n'))
}else{
console.log("Error saving organization")
console.log(result);
alert('Error saving organization')
}
}else{
$modalInstance.close("add" == mode ? result.id : null);
}
}).error(function(){
console.log('Error saving organization', arguments)
alert('Error saving organization')
});
};
$scope.cancel = function(){
$modalInstance.close();
};
function loadItem(itemId){
var url = "https://" + window.__bootstrapData.user.popitUrl + "/api/v0.1/organizations/" + itemId + "?embed="
$http.get(url).then(function(response){
$scope.item = response.data.result;
loadOrganizationName();
})
}
$scope.removeName = function(ix){
$scope.item.other_names.splice(ix, 1);
};
$scope.addName = function(){
$scope.item.other_names = $scope.item.other_names || [];
$scope.item.other_names.push({});
}
$scope.addContact = function(){
$scope.item.contact_details = $scope.item.contact_details || [];
$scope.item.contact_details.push({});
};
$scope.removeContact = function(ix){
$scope.item.contact_details.splice(ix, 1);
}
$scope.getOrganizations = function(val) {
return $http.get('https://' + window.__bootstrapData.user.popitUrl + '/api/v0.1/search/organizations', {
params: {
q: "name:" + val + "*",
embed: ""
}
}).then(function(response){
return response.data.result.map(function(item){
return {id: item.id, name: item.name};
});
});
};
$scope.selectOrganization = function($item, $model, $label){
$scope.item.parent_id = $model.id;
$scope.organization_name = $model.name;
$scope.orgSearch = false;
};
});
| apache-2.0 |
phatboyg/Machete | src/Machete.HL7Schema/Generated/V26/Components/FN.cs | 1293 | // This file was automatically generated and may be regenerated at any
// time. To ensure any changes are retained, modify the tool with any segment/component/group/field name
// or type changes.
namespace Machete.HL7Schema.V26
{
using HL7;
/// <summary>
/// FN (Component) - Family Name
/// </summary>
public interface FN :
HL7V26Component
{
/// <summary>
/// FN-1 Surname
/// </summary>
/// <returns>The string value</returns>
Value<string> Surname { get; }
/// <summary>
/// FN-2 Own Surname Prefix
/// </summary>
/// <returns>The string value</returns>
Value<string> OwnSurnamePrefix { get; }
/// <summary>
/// FN-3 Own Surname
/// </summary>
/// <returns>The string value</returns>
Value<string> OwnSurname { get; }
/// <summary>
/// FN-4 Surname Prefix from Partner/Spouse
/// </summary>
/// <returns>The string value</returns>
Value<string> SurnamePrefixFromPartnerSpouse { get; }
/// <summary>
/// FN-5 Surname from Partner/Spouse
/// </summary>
/// <returns>The string value</returns>
Value<string> SurnameFromPartnerSpouse { get; }
}
} | apache-2.0 |
EixoX/Jetfuel-Java | com.eixox.jetfuel/src/main/java/com/eixox/restrictions/Length.java | 223 | package com.eixox.restrictions;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface Length {
public int min();
public int max();
}
| apache-2.0 |
gpolitis/jitsi-meet | react/features/chat/components/native/ChatMessage.js | 6130 | // @flow
import React from 'react';
import { Text, View } from 'react-native';
import { Avatar } from '../../../base/avatar';
import { ColorSchemeRegistry } from '../../../base/color-scheme';
import { translate } from '../../../base/i18n';
import { Linkify } from '../../../base/react';
import { connect } from '../../../base/redux';
import { type StyleType } from '../../../base/styles';
import { MESSAGE_TYPE_ERROR, MESSAGE_TYPE_LOCAL } from '../../constants';
import { replaceNonUnicodeEmojis } from '../../functions';
import AbstractChatMessage, { type Props as AbstractProps } from '../AbstractChatMessage';
import PrivateMessageButton from '../PrivateMessageButton';
import styles from './styles';
type Props = AbstractProps & {
/**
* The color-schemed stylesheet of the feature.
*/
_styles: StyleType
};
/**
* Renders a single chat message.
*/
class ChatMessage extends AbstractChatMessage<Props> {
/**
* Implements {@code Component#render}.
*
* @inheritdoc
*/
render() {
const { _styles, message } = this.props;
const localMessage = message.messageType === MESSAGE_TYPE_LOCAL;
const { privateMessage } = message;
// Style arrays that need to be updated in various scenarios, such as
// error messages or others.
const detailsWrapperStyle = [
styles.detailsWrapper
];
const messageBubbleStyle = [
styles.messageBubble
];
if (localMessage) {
// This is a message sent by the local participant.
// The wrapper needs to be aligned to the right.
detailsWrapperStyle.push(styles.ownMessageDetailsWrapper);
// The bubble needs some additional styling
messageBubbleStyle.push(_styles.localMessageBubble);
} else if (message.messageType === MESSAGE_TYPE_ERROR) {
// This is a system message.
// The bubble needs some additional styling
messageBubbleStyle.push(styles.systemMessageBubble);
} else {
// This is a remote message sent by a remote participant.
// The bubble needs some additional styling
messageBubbleStyle.push(_styles.remoteMessageBubble);
}
if (privateMessage) {
messageBubbleStyle.push(_styles.privateMessageBubble);
}
return (
<View style = { styles.messageWrapper } >
{ this._renderAvatar() }
<View style = { detailsWrapperStyle }>
<View style = { messageBubbleStyle }>
<View style = { styles.textWrapper } >
{ this._renderDisplayName() }
<Linkify linkStyle = { styles.chatLink }>
{ replaceNonUnicodeEmojis(this._getMessageText()) }
</Linkify>
{ this._renderPrivateNotice() }
</View>
{ this._renderPrivateReplyButton() }
</View>
{ this._renderTimestamp() }
</View>
</View>
);
}
_getFormattedTimestamp: () => string;
_getMessageText: () => string;
_getPrivateNoticeMessage: () => string;
/**
* Renders the avatar of the sender.
*
* @returns {React$Element<*>}
*/
_renderAvatar() {
const { message } = this.props;
return (
<View style = { styles.avatarWrapper }>
{ this.props.showAvatar && <Avatar
displayName = { message.displayName }
participantId = { message.id }
size = { styles.avatarWrapper.width } />
}
</View>
);
}
/**
* Renders the display name of the sender if necessary.
*
* @returns {React$Element<*> | null}
*/
_renderDisplayName() {
const { _styles, message, showDisplayName } = this.props;
if (!showDisplayName) {
return null;
}
return (
<Text style = { _styles.displayName }>
{ message.displayName }
</Text>
);
}
/**
* Renders the message privacy notice, if necessary.
*
* @returns {React$Element<*> | null}
*/
_renderPrivateNotice() {
const { _styles, message } = this.props;
if (!message.privateMessage) {
return null;
}
return (
<Text style = { _styles.privateNotice }>
{ this._getPrivateNoticeMessage() }
</Text>
);
}
/**
* Renders the private reply button, if necessary.
*
* @returns {React$Element<*> | null}
*/
_renderPrivateReplyButton() {
const { _styles, message } = this.props;
const { messageType, privateMessage } = message;
if (!privateMessage || messageType === MESSAGE_TYPE_LOCAL) {
return null;
}
return (
<View style = { _styles.replyContainer }>
<PrivateMessageButton
participantID = { message.id }
reply = { true }
showLabel = { false }
toggledStyles = { _styles.replyStyles } />
</View>
);
}
/**
* Renders the time at which the message was sent, if necessary.
*
* @returns {React$Element<*> | null}
*/
_renderTimestamp() {
if (!this.props.showTimestamp) {
return null;
}
return (
<Text style = { styles.timeText }>
{ this._getFormattedTimestamp() }
</Text>
);
}
}
/**
* Maps part of the redux state to the props of this component.
*
* @param {Object} state - The Redux state.
* @returns {Props}
*/
function _mapStateToProps(state) {
return {
_styles: ColorSchemeRegistry.get(state, 'Chat')
};
}
export default translate(connect(_mapStateToProps)(ChatMessage));
| apache-2.0 |
cmaere/lwb | templates/protostar/index1fc7.php | 747 | <?xml version="1.0" encoding="utf-8"?>
<OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/"><ShortName>National Water Supply and Drainage Board</ShortName><Description>National Water Supply and Drainage Board</Description><InputEncoding>UTF-8</InputEncoding><Image type="image/vnd.microsoft.icon" width="16" height="16">http://waterboard.lk/web/templates/poora_temp/favicon.ico</Image><Url type="application/opensearchdescription+xml" rel="self" template="http://waterboard.lk/web/index.php?option=com_search&view=remind&Itemid=263&lang=en&format=opensearch"/><Url type="text/html" template="http://waterboard.lk/web/index.php?option=com_search&searchword={searchTerms}&Itemid=188"/></OpenSearchDescription>
| apache-2.0 |
VahidN/AutoMapperSamples | Sample04/Properties/AssemblyInfo.cs | 1353 | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Sample04")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Sample04")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("ecf57dfd-ba41-4f25-a130-43911588d5ed")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| apache-2.0 |
perpetual-motion/clrplus | Crypto/X509StoreExtensions.cs | 1207 | //-----------------------------------------------------------------------
// <copyright company="CoApp Project">
// Copyright (c) 2011 Eric Schultz. All rights reserved.
// </copyright>
// <license>
// The software is licensed under the Apache 2.0 License (the "License")
// You may not use the software except in compliance with the License.
// </license>
//-----------------------------------------------------------------------
namespace ClrPlus.Crypto {
using System.Linq;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
public static class X509StoreExtensions {
public const string CODE_SIGNING_OID = "1.3.6.1.5.5.7.3.3";
public static X509Certificate2 FindCodeSigningCert(this X509Store pfx) {
return (from c in pfx.Certificates.Cast<X509Certificate2>()
where c.HasPrivateKey
from ext in c.Extensions.Cast<X509Extension>().OfType<X509EnhancedKeyUsageExtension>()
from oid in ext.EnhancedKeyUsages.Cast<Oid>()
where oid.Value == CODE_SIGNING_OID
select c).FirstOrDefault();
}
}
} | apache-2.0 |
googleapis/google-api-ruby-client | google-api-client/generated/google/apis/cloudresourcemanager_v1/representations.rb | 31444 | # Copyright 2015 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.
require 'date'
require 'google/apis/core/base_service'
require 'google/apis/core/json_representation'
require 'google/apis/core/hashable'
require 'google/apis/errors'
module Google
module Apis
module CloudresourcemanagerV1
class Ancestor
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class AuditConfig
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class AuditLogConfig
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class Binding
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class BooleanConstraint
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class BooleanPolicy
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class ClearOrgPolicyRequest
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class CloudresourcemanagerGoogleCloudResourcemanagerV2alpha1FolderOperation
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class CloudresourcemanagerGoogleCloudResourcemanagerV2beta1FolderOperation
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class Constraint
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class CreateFolderMetadata
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class CreateProjectMetadata
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class CreateTagKeyMetadata
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class CreateTagValueMetadata
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class DeleteFolderMetadata
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class DeleteOrganizationMetadata
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class DeleteProjectMetadata
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class DeleteTagKeyMetadata
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class DeleteTagValueMetadata
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class Empty
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class Expr
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class FolderOperation
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class FolderOperationError
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class GetAncestryRequest
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class GetAncestryResponse
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class GetEffectiveOrgPolicyRequest
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class GetIamPolicyRequest
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class GetOrgPolicyRequest
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class GetPolicyOptions
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class Lien
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class ListAvailableOrgPolicyConstraintsRequest
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class ListAvailableOrgPolicyConstraintsResponse
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class ListConstraint
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class ListLiensResponse
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class ListOrgPoliciesRequest
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class ListOrgPoliciesResponse
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class ListPolicy
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class ListProjectsResponse
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class MoveFolderMetadata
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class MoveProjectMetadata
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class Operation
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class OrgPolicy
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class Organization
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class OrganizationOwner
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class Policy
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class Project
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class ProjectCreationStatus
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class ResourceId
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class RestoreDefault
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class SearchOrganizationsRequest
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class SearchOrganizationsResponse
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class SetIamPolicyRequest
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class SetOrgPolicyRequest
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class Status
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class TestIamPermissionsRequest
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class TestIamPermissionsResponse
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class UndeleteFolderMetadata
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class UndeleteOrganizationMetadata
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class UndeleteProjectMetadata
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class UndeleteProjectRequest
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class UpdateFolderMetadata
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class UpdateProjectMetadata
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class UpdateTagKeyMetadata
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class UpdateTagValueMetadata
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class Ancestor
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :resource_id, as: 'resourceId', class: Google::Apis::CloudresourcemanagerV1::ResourceId, decorator: Google::Apis::CloudresourcemanagerV1::ResourceId::Representation
end
end
class AuditConfig
# @private
class Representation < Google::Apis::Core::JsonRepresentation
collection :audit_log_configs, as: 'auditLogConfigs', class: Google::Apis::CloudresourcemanagerV1::AuditLogConfig, decorator: Google::Apis::CloudresourcemanagerV1::AuditLogConfig::Representation
property :service, as: 'service'
end
end
class AuditLogConfig
# @private
class Representation < Google::Apis::Core::JsonRepresentation
collection :exempted_members, as: 'exemptedMembers'
property :log_type, as: 'logType'
end
end
class Binding
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :condition, as: 'condition', class: Google::Apis::CloudresourcemanagerV1::Expr, decorator: Google::Apis::CloudresourcemanagerV1::Expr::Representation
collection :members, as: 'members'
property :role, as: 'role'
end
end
class BooleanConstraint
# @private
class Representation < Google::Apis::Core::JsonRepresentation
end
end
class BooleanPolicy
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :enforced, as: 'enforced'
end
end
class ClearOrgPolicyRequest
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :constraint, as: 'constraint'
property :etag, :base64 => true, as: 'etag'
end
end
class CloudresourcemanagerGoogleCloudResourcemanagerV2alpha1FolderOperation
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :destination_parent, as: 'destinationParent'
property :display_name, as: 'displayName'
property :operation_type, as: 'operationType'
property :source_parent, as: 'sourceParent'
end
end
class CloudresourcemanagerGoogleCloudResourcemanagerV2beta1FolderOperation
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :destination_parent, as: 'destinationParent'
property :display_name, as: 'displayName'
property :operation_type, as: 'operationType'
property :source_parent, as: 'sourceParent'
end
end
class Constraint
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :boolean_constraint, as: 'booleanConstraint', class: Google::Apis::CloudresourcemanagerV1::BooleanConstraint, decorator: Google::Apis::CloudresourcemanagerV1::BooleanConstraint::Representation
property :constraint_default, as: 'constraintDefault'
property :description, as: 'description'
property :display_name, as: 'displayName'
property :list_constraint, as: 'listConstraint', class: Google::Apis::CloudresourcemanagerV1::ListConstraint, decorator: Google::Apis::CloudresourcemanagerV1::ListConstraint::Representation
property :name, as: 'name'
property :version, as: 'version'
end
end
class CreateFolderMetadata
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :display_name, as: 'displayName'
property :parent, as: 'parent'
end
end
class CreateProjectMetadata
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :create_time, as: 'createTime'
property :gettable, as: 'gettable'
property :ready, as: 'ready'
end
end
class CreateTagKeyMetadata
# @private
class Representation < Google::Apis::Core::JsonRepresentation
end
end
class CreateTagValueMetadata
# @private
class Representation < Google::Apis::Core::JsonRepresentation
end
end
class DeleteFolderMetadata
# @private
class Representation < Google::Apis::Core::JsonRepresentation
end
end
class DeleteOrganizationMetadata
# @private
class Representation < Google::Apis::Core::JsonRepresentation
end
end
class DeleteProjectMetadata
# @private
class Representation < Google::Apis::Core::JsonRepresentation
end
end
class DeleteTagKeyMetadata
# @private
class Representation < Google::Apis::Core::JsonRepresentation
end
end
class DeleteTagValueMetadata
# @private
class Representation < Google::Apis::Core::JsonRepresentation
end
end
class Empty
# @private
class Representation < Google::Apis::Core::JsonRepresentation
end
end
class Expr
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :description, as: 'description'
property :expression, as: 'expression'
property :location, as: 'location'
property :title, as: 'title'
end
end
class FolderOperation
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :destination_parent, as: 'destinationParent'
property :display_name, as: 'displayName'
property :operation_type, as: 'operationType'
property :source_parent, as: 'sourceParent'
end
end
class FolderOperationError
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :error_message_id, as: 'errorMessageId'
end
end
class GetAncestryRequest
# @private
class Representation < Google::Apis::Core::JsonRepresentation
end
end
class GetAncestryResponse
# @private
class Representation < Google::Apis::Core::JsonRepresentation
collection :ancestor, as: 'ancestor', class: Google::Apis::CloudresourcemanagerV1::Ancestor, decorator: Google::Apis::CloudresourcemanagerV1::Ancestor::Representation
end
end
class GetEffectiveOrgPolicyRequest
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :constraint, as: 'constraint'
end
end
class GetIamPolicyRequest
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :options, as: 'options', class: Google::Apis::CloudresourcemanagerV1::GetPolicyOptions, decorator: Google::Apis::CloudresourcemanagerV1::GetPolicyOptions::Representation
end
end
class GetOrgPolicyRequest
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :constraint, as: 'constraint'
end
end
class GetPolicyOptions
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :requested_policy_version, as: 'requestedPolicyVersion'
end
end
class Lien
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :create_time, as: 'createTime'
property :name, as: 'name'
property :origin, as: 'origin'
property :parent, as: 'parent'
property :reason, as: 'reason'
collection :restrictions, as: 'restrictions'
end
end
class ListAvailableOrgPolicyConstraintsRequest
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :page_size, as: 'pageSize'
property :page_token, as: 'pageToken'
end
end
class ListAvailableOrgPolicyConstraintsResponse
# @private
class Representation < Google::Apis::Core::JsonRepresentation
collection :constraints, as: 'constraints', class: Google::Apis::CloudresourcemanagerV1::Constraint, decorator: Google::Apis::CloudresourcemanagerV1::Constraint::Representation
property :next_page_token, as: 'nextPageToken'
end
end
class ListConstraint
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :suggested_value, as: 'suggestedValue'
property :supports_under, as: 'supportsUnder'
end
end
class ListLiensResponse
# @private
class Representation < Google::Apis::Core::JsonRepresentation
collection :liens, as: 'liens', class: Google::Apis::CloudresourcemanagerV1::Lien, decorator: Google::Apis::CloudresourcemanagerV1::Lien::Representation
property :next_page_token, as: 'nextPageToken'
end
end
class ListOrgPoliciesRequest
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :page_size, as: 'pageSize'
property :page_token, as: 'pageToken'
end
end
class ListOrgPoliciesResponse
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :next_page_token, as: 'nextPageToken'
collection :policies, as: 'policies', class: Google::Apis::CloudresourcemanagerV1::OrgPolicy, decorator: Google::Apis::CloudresourcemanagerV1::OrgPolicy::Representation
end
end
class ListPolicy
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :all_values, as: 'allValues'
collection :allowed_values, as: 'allowedValues'
collection :denied_values, as: 'deniedValues'
property :inherit_from_parent, as: 'inheritFromParent'
property :suggested_value, as: 'suggestedValue'
end
end
class ListProjectsResponse
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :next_page_token, as: 'nextPageToken'
collection :projects, as: 'projects', class: Google::Apis::CloudresourcemanagerV1::Project, decorator: Google::Apis::CloudresourcemanagerV1::Project::Representation
end
end
class MoveFolderMetadata
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :destination_parent, as: 'destinationParent'
property :display_name, as: 'displayName'
property :source_parent, as: 'sourceParent'
end
end
class MoveProjectMetadata
# @private
class Representation < Google::Apis::Core::JsonRepresentation
end
end
class Operation
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :done, as: 'done'
property :error, as: 'error', class: Google::Apis::CloudresourcemanagerV1::Status, decorator: Google::Apis::CloudresourcemanagerV1::Status::Representation
hash :metadata, as: 'metadata'
property :name, as: 'name'
hash :response, as: 'response'
end
end
class OrgPolicy
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :boolean_policy, as: 'booleanPolicy', class: Google::Apis::CloudresourcemanagerV1::BooleanPolicy, decorator: Google::Apis::CloudresourcemanagerV1::BooleanPolicy::Representation
property :constraint, as: 'constraint'
property :etag, :base64 => true, as: 'etag'
property :list_policy, as: 'listPolicy', class: Google::Apis::CloudresourcemanagerV1::ListPolicy, decorator: Google::Apis::CloudresourcemanagerV1::ListPolicy::Representation
property :restore_default, as: 'restoreDefault', class: Google::Apis::CloudresourcemanagerV1::RestoreDefault, decorator: Google::Apis::CloudresourcemanagerV1::RestoreDefault::Representation
property :update_time, as: 'updateTime'
property :version, as: 'version'
end
end
class Organization
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :creation_time, as: 'creationTime'
property :display_name, as: 'displayName'
property :lifecycle_state, as: 'lifecycleState'
property :name, as: 'name'
property :owner, as: 'owner', class: Google::Apis::CloudresourcemanagerV1::OrganizationOwner, decorator: Google::Apis::CloudresourcemanagerV1::OrganizationOwner::Representation
end
end
class OrganizationOwner
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :directory_customer_id, as: 'directoryCustomerId'
end
end
class Policy
# @private
class Representation < Google::Apis::Core::JsonRepresentation
collection :audit_configs, as: 'auditConfigs', class: Google::Apis::CloudresourcemanagerV1::AuditConfig, decorator: Google::Apis::CloudresourcemanagerV1::AuditConfig::Representation
collection :bindings, as: 'bindings', class: Google::Apis::CloudresourcemanagerV1::Binding, decorator: Google::Apis::CloudresourcemanagerV1::Binding::Representation
property :etag, :base64 => true, as: 'etag'
property :version, as: 'version'
end
end
class Project
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :create_time, as: 'createTime'
hash :labels, as: 'labels'
property :lifecycle_state, as: 'lifecycleState'
property :name, as: 'name'
property :parent, as: 'parent', class: Google::Apis::CloudresourcemanagerV1::ResourceId, decorator: Google::Apis::CloudresourcemanagerV1::ResourceId::Representation
property :project_id, as: 'projectId'
property :project_number, :numeric_string => true, as: 'projectNumber'
end
end
class ProjectCreationStatus
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :create_time, as: 'createTime'
property :gettable, as: 'gettable'
property :ready, as: 'ready'
end
end
class ResourceId
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :id, as: 'id'
property :type, as: 'type'
end
end
class RestoreDefault
# @private
class Representation < Google::Apis::Core::JsonRepresentation
end
end
class SearchOrganizationsRequest
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :filter, as: 'filter'
property :page_size, as: 'pageSize'
property :page_token, as: 'pageToken'
end
end
class SearchOrganizationsResponse
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :next_page_token, as: 'nextPageToken'
collection :organizations, as: 'organizations', class: Google::Apis::CloudresourcemanagerV1::Organization, decorator: Google::Apis::CloudresourcemanagerV1::Organization::Representation
end
end
class SetIamPolicyRequest
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :policy, as: 'policy', class: Google::Apis::CloudresourcemanagerV1::Policy, decorator: Google::Apis::CloudresourcemanagerV1::Policy::Representation
property :update_mask, as: 'updateMask'
end
end
class SetOrgPolicyRequest
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :policy, as: 'policy', class: Google::Apis::CloudresourcemanagerV1::OrgPolicy, decorator: Google::Apis::CloudresourcemanagerV1::OrgPolicy::Representation
end
end
class Status
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :code, as: 'code'
collection :details, as: 'details'
property :message, as: 'message'
end
end
class TestIamPermissionsRequest
# @private
class Representation < Google::Apis::Core::JsonRepresentation
collection :permissions, as: 'permissions'
end
end
class TestIamPermissionsResponse
# @private
class Representation < Google::Apis::Core::JsonRepresentation
collection :permissions, as: 'permissions'
end
end
class UndeleteFolderMetadata
# @private
class Representation < Google::Apis::Core::JsonRepresentation
end
end
class UndeleteOrganizationMetadata
# @private
class Representation < Google::Apis::Core::JsonRepresentation
end
end
class UndeleteProjectMetadata
# @private
class Representation < Google::Apis::Core::JsonRepresentation
end
end
class UndeleteProjectRequest
# @private
class Representation < Google::Apis::Core::JsonRepresentation
end
end
class UpdateFolderMetadata
# @private
class Representation < Google::Apis::Core::JsonRepresentation
end
end
class UpdateProjectMetadata
# @private
class Representation < Google::Apis::Core::JsonRepresentation
end
end
class UpdateTagKeyMetadata
# @private
class Representation < Google::Apis::Core::JsonRepresentation
end
end
class UpdateTagValueMetadata
# @private
class Representation < Google::Apis::Core::JsonRepresentation
end
end
end
end
end
| apache-2.0 |
JeffLi1993/springdream | spring/springdream-ioc/src/main/java/org/spring/resource/FileSourceExample.java | 2927 | package org.spring.resource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.util.FileCopyUtils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
/*
* Copyright [2015] [Jeff Lee]
*
* 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.
*/
/**
* @author Jeff Lee
* @since 2015-12-1 20:31:54
* Spring的Resource获取文件信息
*/
public class FileSourceExample {
public static void main(String[] args) {
try {
String filePath = "E:\\JEELearning\\ideaworlplace\\springdream\\springdream.ioc\\src\\main\\resources\\FileSource.txt";
// 使用系统文件路径方式加载文件
Resource res1 = new FileSystemResource(filePath);
// 使用类路径方式加载文件
Resource res2 = new ClassPathResource("FileSource.txt");
System.out.println("系统文件路径方式:" + res1.getFilename());
System.out.println("类路径方式:" + res2.getFilename());
InputStream in1 = res1.getInputStream();
InputStream in2 = res2.getInputStream();
// System.out.println("系统文件路径方式:" + read(in1));
// System.out.println("类路径方式:" + read(in2));
System.out.println("系统文件路径方式:" + new String(FileCopyUtils.copyToByteArray(in1)));
System.out.println("类路径方式:" + new String(FileCopyUtils.copyToByteArray(in2)));
} catch (IOException e) {
e.printStackTrace();
}
}
// 读取文件内容,返回内容字符串
public static String read(InputStream inputStream) {
StringBuilder sb = new StringBuilder();
try {
// 创建缓存字符输入流
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
try {
String s;
// 读取一个文本行
while ((s = in.readLine()) != null) {
sb.append(s);
sb.append("\n");
}
} finally {
in.close();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return sb.toString();
}
}
| apache-2.0 |
linzhaoming/origin | pkg/apps/apiserver/registry/deploylog/wait.go | 2910 | package deploylog
import (
"context"
"errors"
"fmt"
"time"
"github.com/golang/glog"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/watch"
corev1client "k8s.io/client-go/kubernetes/typed/core/v1"
watchtools "k8s.io/client-go/tools/watch"
appsv1 "github.com/openshift/api/apps/v1"
appsutil "github.com/openshift/origin/pkg/apps/util"
)
var (
// ErrUnknownDeploymentPhase is returned for WaitForRunningDeployment if an unknown phase is returned.
ErrUnknownDeploymentPhase = errors.New("unknown deployment phase")
ErrTooOldResourceVersion = errors.New("too old resource version")
)
// WaitForRunningDeployment waits until the specified deployment is no longer New or Pending. Returns true if
// the deployment became running, complete, or failed within timeout, false if it did not, and an error if any
// other error state occurred. The last observed deployment state is returned.
func WaitForRunningDeployment(rn corev1client.ReplicationControllersGetter, observed *corev1.ReplicationController, timeout time.Duration) (*corev1.ReplicationController, bool, error) {
options := metav1.SingleObject(observed.ObjectMeta)
w, err := rn.ReplicationControllers(observed.Namespace).Watch(options)
if err != nil {
return observed, false, err
}
defer w.Stop()
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
if _, err := watchtools.UntilWithoutRetry(ctx, w, func(e watch.Event) (bool, error) {
if e.Type == watch.Error {
// When we send too old resource version in observed replication controller to
// watcher, restart the watch with latest available controller.
switch t := e.Object.(type) {
case *metav1.Status:
if t.Reason == metav1.StatusReasonGone {
glog.V(5).Infof("encountered error while watching for replication controller: %v (retrying)", t)
return false, ErrTooOldResourceVersion
}
}
return false, fmt.Errorf("encountered error while watching for replication controller: %v", e.Object)
}
obj, isController := e.Object.(*corev1.ReplicationController)
if !isController {
return false, fmt.Errorf("received unknown object while watching for deployments: %v", obj)
}
observed = obj
switch appsutil.DeploymentStatusFor(observed) {
case appsv1.DeploymentStatusRunning, appsv1.DeploymentStatusFailed, appsv1.DeploymentStatusComplete:
return true, nil
case appsv1.DeploymentStatusNew, appsv1.DeploymentStatusPending:
return false, nil
default:
return false, ErrUnknownDeploymentPhase
}
}); err != nil {
if err == ErrTooOldResourceVersion {
latestRC, err := rn.ReplicationControllers(observed.Namespace).Get(observed.Name, metav1.GetOptions{})
if err != nil {
return observed, false, err
}
return WaitForRunningDeployment(rn, latestRC, timeout)
}
return observed, false, err
}
return observed, true, nil
}
| apache-2.0 |
cityindex-attic/TradingApi.Client.CS | Source/Dev/Source/Clients/CIAPI.CS/TradingApi.Client.Framework.DTOs/ListNewsHeadlinesResponseDTO.cs | 335 | namespace TradingApi.Client.Framework.DTOs
{
/// <summary>
/// The response from a GET request for News headlines
/// </summary>
public class ListNewsHeadlinesResponseDTO
{
/// <summary>
/// A list of News headlines
/// </summary>
public NewsDTO[] Headlines { get; set; }
}
} | apache-2.0 |
coolaj86/fxos-angular-demo | scripts/services/fx-msg.js | 6839 | 'use strict';
/**
* @ngdoc service
* @name fxos.msg
* @description
* # msg
* Service in the fxos.
*/
angular.module('fxos', [])
.service('fxMsg', ['$rootScope', '$q', '$window', function msg($rootScope, $q, $window) {
// AngularJS will instantiate a singleton by calling "new" on this function
// https://developer.mozilla.org/en-US/docs/Web/API/MozSmsManager (1.3 API?)
// https://developer.mozilla.org/en-US/docs/Web/API/MozMobileMessageManager (2.0 API?)
var MsgMngr = $window.navigator.mozMobileMessage
// events => [deliveryerror, deliverysuccess, received, sent, sending, failed]
// are these delivery events receipts?
;
// https://developer.mozilla.org/en-US/docs/Web/API/WebSMS_API
// navigator.mozMobileMessage
// navigator.mozMobileMessage.send("+1 (801) 360-4427", "Test") // works 1.3
// navigator.mozSetMessageHandler
// window.MozMobileMessageManager
// .send("+1 (801) 360-4427", "Test") // 1.3 doesn't work
// window.MozSmsSegmentInfo
// window.MozSmsMessage
// window.MozSmsFilter
// window.MozSmsEvent
// window.MozMmsMessage
// window.MozMmsEvent
// window.MozMobileMessageManager
// window.MozMobileMessageThread
function Msg() {
}
/*
Msg.create = function (url, $scope) {
//Msg.$scope = $scope || $rootScope;
return Msg;
};
*/
Msg.$scope = $rootScope;
Msg.on = function (eventname, fn) {
// events:
// received
MsgMngr.addEventListener(eventname, function (msg) {
// https://developer.mozilla.org/en-US/docs/Web/API/MozSmsMessage
//console.log("SMS received");
//console.log(JSON.stringify(msg));
console.log('msg');
console.log(msg);
console.log('this.result');
console.log(this.result);
getById(msg.id || this.id || this.result && this.result.id).then(function (res) {
// handled by getById
//Msg.$scope.$apply(function () {
fn.call(null, res);
//});
});
});
};
Msg.addEventListener = Msg.on;
function smsToJSON(msg) {
return {
// observed
body: msg.body
, delivery: msg.delivery // received (sender) sent / sending error
, deliveryStatus: msg.deliveryStatus // success (receiver) not-applicable error
, deliveryTimestamp: msg.deliveryTimestamp
, iccId: msg.iccId
, id: msg.id
, messageClass: msg.messageClass // normal, class-1 (i.e. short code messages from provider)
, read: msg.read
, receiver: msg.receiver // empty (should show which SIM this is from). Sad Day.
, sender: msg.sender
, threadId: msg.threadId
, timestamp: msg.timestamp
, type: msg.type
// supposedly on mmsg
, subject: msg.subject
// for debugging
, _original: msg
};
}
function getById(id) {
var defer = $q.defer()
;
var x = MsgMngr.getMessage(id);
x.onsuccess = function (/*ev*/) {
// this.result === ev.target.result
defer.resolve(smsToJSON(this.result));
};
x.onerror = function (/*ev*/) {
defer.reject(this.error);
};
return defer.promise;
}
function get(opts) {
opts = opts || {};
// https://developer.mozilla.org/en-US/docs/Web/API/MozSmsFilter
var filter = new $window.MozSmsFilter()
// threadId, read, startDate, endDate, numbers, delivery
, cursor
, defer = $q.defer()
, ps = []
, reverse
, limit = 20
, offset = 0
, count = 0
;
if ('undefined' !== typeof opts.threadId) {
filter.threadId = opts.threadId;
}
if ('undefined' !== typeof opts.limit) {
limit = opts.limit;
}
if ('undefined' !== typeof opts.offset) {
offset = opts.offset;
}
if ('undefined' !== typeof opts.read) {
filter.read = opts.read;
}
if ('undefined' !== typeof opts.reverse) {
reverse = opts.reverse;
} else {
// default to newest first
reverse = true;
}
if ('undefined' !== typeof opts.numbers) {
filter.numbers = opts.numbers;
}
cursor = MsgMngr.getMessages(filter, reverse);
cursor.onsuccess = function (/*thing?*/) {
if (this.done || count >= (offset + limit)) {
defer.resolve(ps);
return;
}
var msg = this.result
;
if (count >= offset) {
// copy DOM object to javascript so that console.log will show something meaningful
ps.push(smsToJSON(msg));
}
count += 1;
this.continue();
};
return defer.promise;
}
function send(to, text) {
var requests
, ps = []
;
requests = MsgMngr.send(to, text);
if (!Array.isArray(to)) {
requests = [requests];
}
requests.forEach(function (request) {
var defer = $q.defer()
;
request.onsuccess = function () {
// TODO send confirm
console.log('[sent]');
console.log(this.result);
defer.resolve(this.result || this);
};
request.onerror = function () {
// TODO send error
console.error('[error] ' + this.result);
console.error(this.error.name + ':' + this.error.message);
console.error(JSON.stringify(this.error));
console.error(this.error.toString());
defer.resolve({ error: this.error || this });
};
ps.push(defer.promise);
});
return $q.all(ps).then(function (results) {
// TODO get javascript version of results / errors
if (Array.isArray(to)) {
return results;
} else {
return results[0] || null;
}
});
}
function setRead(msg, read) {
var id = msg.id || id
, defer = $q.defer()
, r
;
r = MsgMngr.markMessageRead(id, read);
r.onsuccess = function () {
defer.resolve();
};
r.onerror = function () {
defer.reject();
};
return defer.promise;
}
function del(msg) {
var id = msg.id || msg
, defer = $q.defer()
, r
;
r = MsgMngr.delete(id);
r.onsuccess = function () {
defer.resolve();
};
r.onerror = function () {
defer.reject();
};
return defer.promise;
}
function multipart() {
// .getSegmentInfoForText(text)
}
return {
get: get
, getById: getById
, on: Msg.on
, send: send
, setRead: setRead
, delete: del
};
}]);
| apache-2.0 |
googlefonts/fluid | src/demos/WaveDemo.js | 5138 | /** @license
* Copyright 2019 Google LLC
*
* 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.
*/
const fls = require("../helpers/FluidSimulation")
const objP = require("../helpers/ObjectPool")
var gravity = new b2Vec2(0, -10);
world = new b2World(gravity);
class WaveDemo {
constructor() {
this.animationRequest = null;
this.demoWidth = document.getElementById("demo").clientWidth;
this.demoHeight = document.getElementById("demo").clientHeight;
//DOM elements
this.container = document.getElementById("water-container");
this.containerRect = this.container.getBoundingClientRect();
this.mouseSquare = document.getElementById("mouse-square");
this.mouseSquareRect = this.mouseSquare.getBoundingClientRect();
//setup fluid sim
let gravity = new b2Vec2(0, -10);
let timeStep = 1.0 / 60.0;
let velocityIterations = 8;
let positionIterations = 3;
let baselineAmtPerCell = 5;
this.fluidSim = new fls.FluidSimulation(world, timeStep, velocityIterations, positionIterations);
this.fontSize = this.demoWidth / (35); //TODO - needs refinement for viewport
this.waveXPositionOffset = this.demoWidth / 2 - this.fontSize / 2;
this.waveXPositionScale = this.demoWidth / 2.5 * 1.1;
this.waveYPositionOffset = this.demoHeight + this.fontSize / 2;
this.waveYPositionScale = (this.demoWidth / 2.5) * 1.15;
this.objectPool = new objP.ObjectPool(this.fontSize, 45, 100, 5, 100, 900, 100, this.fluidSim.getNumParticles(), baselineAmtPerCell, this.container);
this.container.addEventListener("mousemove", (ele) => this.mouseMoveHandler(ele));
}
mouseMoveHandler(ele) {
const x = ele.clientX - this.containerRect.left;
const y = ele.clientY - this.containerRect.top;
this.mouseSquare.style.transform = `translate3d(${x - (this.mouseSquareRect.right - this.mouseSquareRect.left)/2}px, ${y}px, 0)`;
this.fluidSim.moveMouse((x - this.waveXPositionOffset) / this.waveXPositionScale, (this.waveYPositionOffset - y) / this.waveXPositionScale);
}
start() {
this.animationRequest = window.requestAnimationFrame(() => this.step());
this.recomputeBounds();
}
stop() {
window.cancelAnimationFrame(this.animationRequest);
}
recomputeBounds() {
this.containerRect = this.container.getBoundingClientRect();
this.mouseSquareRect = this.mouseSquare.getBoundingClientRect();
this.demoWidth = document.getElementById("demo").clientWidth;
this.demoHeight = document.getElementById("demo").clientHeight;
this.waveXPositionOffset = this.demoWidth / 2 - this.fontSize / 2;
this.waveXPositionScale = this.demoWidth / 2.5 * 1.1;
this.waveYPositionOffset = this.demoHeight + this.fontSize / 2;
this.waveYPositionScale = (this.demoWidth / 2.5) * 1.15;
}
drawParticleSystem(system) {
let particles = system.GetPositionBuffer();
let maxParticles = particles.length;
this.objectPool.cellsInUse.map(cell => {
cell[3].style.transform = 'translate3D( 0px, 2000px, 0px)'
cell[0] = true;
})
this.objectPool.cellsInUse = []
for (let i = 0; i < maxParticles; i += 2) {
let positionVectorX = particles[i] * this.waveXPositionScale + this.waveXPositionOffset;
let positionVectorY = -particles[i + 1] * this.waveYPositionScale + this.waveYPositionOffset;
let partOneH = this.demoHeight * 1 / 2;
let partTwoH = this.demoHeight - partOneH;
let partOneW = this.demoWidth;
let partTwoW = this.demoWidth - partOneH;
let weight = 800 * (objP.clampNumber(positionVectorY, partTwoH, this.demoHeight) - partTwoH) / (partOneH) + 100;
let width = 55 * (objP.clampNumber(positionVectorX, 0, this.demoWidth)) / (this.demoWidth) + 45;
let currentElement = this.objectPool.grabCorrectObject(width, weight);
currentElement[3].style.transform = 'translate3D(' + Math.floor(positionVectorX) + 'px,' + Math.floor(positionVectorY) + 'px, 1px)';
currentElement[0] = false;
this.objectPool.cellsInUse.push(currentElement);
}
}
step() {
this.fluidSim.step();
this.drawParticleSystem(world.particleSystems[0]);
this.animationRequest = window.requestAnimationFrame(() => this.step());
}
onResize() {
this.recomputeBounds();
}
}
module.exports.WaveDemo = WaveDemo; | apache-2.0 |
idefav/IdefavOAuth2Demo | WCFRescourcesServer/Code/IdefavAuthorizationManager.cs | 4538 | using System;
using System.Collections.Generic;
using System.IdentityModel.Policy;
using System.Linq;
using System.Net.Http;
using System.Security.Cryptography;
using System.Security.Principal;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Security;
using System.ServiceModel.Web;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using DotNetOpenAuth.Messaging;
using DotNetOpenAuth.OAuth2;
using ProtocolException = System.ServiceModel.ProtocolException;
namespace WCFRescourcesServer.Code
{
public class IdefavAuthorizationManager : ServiceAuthorizationManager
{
public IdefavAuthorizationManager()
{
}
protected override bool CheckAccessCore(OperationContext operationContext)
{
if (!base.CheckAccessCore(operationContext))
{
return false;
}
var httpDetails = operationContext.RequestContext.RequestMessage.Properties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;
var requestUri = operationContext.RequestContext.RequestMessage.Properties.Via;
return Task.Run(async delegate
{
ProtocolFaultResponseException exception = null;
try
{
var principal = await VerifyOAuth2Async(
httpDetails,
requestUri,
operationContext.IncomingMessageHeaders.Action ?? operationContext.IncomingMessageHeaders.To.AbsolutePath);
if (principal != null)
{
var policy = new OAuthPrincipalAuthorizationPolicy(principal);
var policies = new List<IAuthorizationPolicy> { policy };
var securityContext = new ServiceSecurityContext(policies.AsReadOnly());
if (operationContext.IncomingMessageProperties.Security != null)
{
operationContext.IncomingMessageProperties.Security.ServiceSecurityContext = securityContext;
}
else
{
operationContext.IncomingMessageProperties.Security = new SecurityMessageProperty
{
ServiceSecurityContext = securityContext,
};
}
securityContext.AuthorizationContext.Properties["Identities"] = new List<IIdentity> { principal.Identity, };
return true;
}
else
{
return false;
}
}
catch (ProtocolFaultResponseException ex)
{
exception = ex;
}
catch (ProtocolException ex)
{
}
if (exception != null)
{
// Return the appropriate unauthorized response to the client.
var outgoingResponse = await exception.CreateErrorResponseAsync(CancellationToken.None);
if (WebOperationContext.Current != null)
this.Respond(WebOperationContext.Current.OutgoingResponse, outgoingResponse);
}
return false;
}).GetAwaiter().GetResult();
}
private static async Task<IPrincipal> VerifyOAuth2Async(HttpRequestMessageProperty httpDetails, Uri requestUri, params string[] requiredScopes)
{
var resourceServer = new ResourceServer(new StandardAccessTokenAnalyzer((RSACryptoServiceProvider)Common.Configuration.SigningCertificate.PublicKey.Key, (RSACryptoServiceProvider)Common.Configuration.EncryptionCertificate.PrivateKey));
return await resourceServer.GetPrincipalAsync(httpDetails, requestUri, requiredScopes: requiredScopes);
}
private void Respond(OutgoingWebResponseContext responseContext, HttpResponseMessage responseMessage)
{
responseContext.StatusCode = responseMessage.StatusCode;
responseContext.SuppressEntityBody = true;
foreach (var header in responseMessage.Headers)
{
responseContext.Headers[header.Key] = header.Value.First();
}
}
}
} | apache-2.0 |
chenyang78/souper | lib/Pass/Pass.cpp | 13273 | // Copyright 2014 The Souper 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.
#define DEBUG_TYPE "souper"
#include "llvm/ADT/Statistic.h"
#include "llvm/Analysis/DemandedBits.h"
#include "llvm/Analysis/LoopInfo.h"
#include "llvm/Analysis/TargetLibraryInfo.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Module.h"
#include "llvm/Pass.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Transforms/IPO/PassManagerBuilder.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
#include "llvm/Transforms/Utils/ModuleUtils.h"
#include "souper/KVStore/KVStore.h"
#include "souper/SMTLIB2/Solver.h"
#include "souper/Tool/GetSolverFromArgs.h"
#include "souper/Tool/CandidateMapUtils.h"
#include "set"
STATISTIC(InstructionReplaced, "Number of instructions replaced by another instruction");
STATISTIC(DominanceCheckFailed, "Number of failed replacement due to dominance check");
using namespace souper;
using namespace llvm;
namespace {
std::unique_ptr<Solver> S;
unsigned ReplaceCount;
KVStore *KV;
static cl::opt<bool> DebugSouperPass("souper-debug", cl::Hidden,
cl::init(false), cl::desc("Debug Souper"));
static cl::opt<unsigned> DebugLevel("souper-debug-level", cl::Hidden,
cl::init(1),
cl::desc("Control the verbose level of debug output (default=1). "
"The larger the number is, the more fine-grained debug "
"information will be printed."));
static cl::opt<bool> DynamicProfile("souper-dynamic-profile", cl::init(false),
cl::desc("Dynamic profiling of Souper optimizations (default=false)"));
static cl::opt<bool> StaticProfile("souper-static-profile", cl::init(false),
cl::desc("Static profiling of Souper optimizations (default=false)"));
static cl::opt<unsigned> FirstReplace("souper-first-opt", cl::Hidden,
cl::init(0),
cl::desc("First Souper optimization to perform (default=0)"));
static cl::opt<unsigned> LastReplace("souper-last-opt", cl::Hidden,
cl::init(std::numeric_limits<unsigned>::max()),
cl::desc("Last Souper optimization to perform (default=infinite)"));
static bool dumpAllReplacements() {
return DebugSouperPass && (DebugLevel > 1);
}
#ifdef DYNAMIC_PROFILE_ALL
static const bool DynamicProfileAll = true;
#else
static const bool DynamicProfileAll = false;
#endif
struct SouperPass : public ModulePass {
static char ID;
public:
SouperPass() : ModulePass(ID) {
if (!S) {
S = GetSolverFromArgs(KV);
if (StaticProfile && !KV)
KV = new KVStore;
if (!S)
report_fatal_error("Souper requires a solver to be specified");
}
}
void getAnalysisUsage(AnalysisUsage &Info) const {
Info.addRequired<LoopInfoWrapperPass>();
Info.addRequired<DominatorTreeWrapperPass>();
Info.addRequired<DemandedBitsWrapperPass>();
Info.addRequired<TargetLibraryInfoWrapperPass>();
}
void dynamicProfile(Function *F, CandidateReplacement &Cand) {
std::string Str;
llvm::raw_string_ostream Loc(Str);
Instruction *I = Cand.Origin.getInstruction();
I->getDebugLoc().print(Loc);
ReplacementContext Context;
std::string LHS = GetReplacementLHSString(Cand.BPCs, Cand.PCs,
Cand.Mapping.LHS, Context);
LLVMContext &C = F->getContext();
Module *M = F->getParent();
Function *RegisterFunc = M->getFunction("_souper_profile_register");
if (!RegisterFunc) {
Type *RegisterArgs[] = {
PointerType::getInt8PtrTy(C),
PointerType::getInt8PtrTy(C),
PointerType::getInt64PtrTy(C),
};
FunctionType *RegisterType = FunctionType::get(Type::getVoidTy(C),
RegisterArgs, false);
RegisterFunc = Function::Create(RegisterType, Function::ExternalLinkage,
"_souper_profile_register", M);
}
// todo: should check if this string exists before creating it
Constant *Repl = ConstantDataArray::getString(C, LHS, true);
Constant *ReplVar = new GlobalVariable(*M, Repl->getType(), true,
GlobalValue::PrivateLinkage, Repl, "");
Constant *ReplPtr = ConstantExpr::getPointerCast(ReplVar,
PointerType::getInt8PtrTy(C));
Constant *Field = ConstantDataArray::getString(C, "dprofile " + Loc.str(),
true);
Constant *FieldVar = new GlobalVariable(*M, Field->getType(), true,
GlobalValue::PrivateLinkage, Field,
"");
Constant *FieldPtr = ConstantExpr::getPointerCast(FieldVar,
PointerType::getInt8PtrTy(C));
Constant *CntVar = new GlobalVariable(*M, Type::getInt64Ty(C), false,
GlobalValue::PrivateLinkage,
ConstantInt::get(C, APInt(64, 0)),
"_souper_profile_cnt");
FunctionType *CtorType = FunctionType::get(Type::getVoidTy(C), false);
Function *Ctor = Function::Create(CtorType, GlobalValue::InternalLinkage,
"_souper_profile_ctor", M);
BasicBlock *BB = BasicBlock::Create(C, "entry", Ctor);
IRBuilder<> Builder(BB);
Value *Args[] = { ReplPtr, FieldPtr, CntVar };
Builder.CreateCall(RegisterFunc, Args);
Builder.CreateRetVoid();
appendToGlobalCtors(*M, Ctor, 0);
BasicBlock::iterator BI(I);
while (isa<PHINode>(*BI))
++BI;
new AtomicRMWInst(AtomicRMWInst::Add, CntVar,
ConstantInt::get(C, APInt(64, 1)), AtomicOrdering::Monotonic,
SyncScope::System, I);
}
Value *getValue(Inst *I, Instruction *ReplacedInst,
ExprBuilderContext &EBC, DominatorTree &DT,
Module *M) {
Type *T = Type::getIntNTy(ReplacedInst->getContext(), I->Width);
if (I->K == Inst::Const) {
return ConstantInt::get(T, I->Val);
} else if (EBC.Origins.count(I) != 0) {
// if there's an Origin, we're connecting to existing code
auto It = EBC.Origins.equal_range(I);
for (auto O = It.first; O != It.second; ++O) {
Value *V = O->second;
if (V->getType() != T)
continue;
if (auto IP = dyn_cast<Instruction>(V)) {
// Dominance check
if (DT.dominates(IP, ReplacedInst)) {
++InstructionReplaced;
return V;
} else {
++DominanceCheckFailed;
}
} else if (isa<Argument>(V) || isa<Constant>(V)) {
return V;
} else {
report_fatal_error("Unhandled LLVM instruction in getValue()");
}
}
return 0;
}
report_fatal_error((std::string)"Unhandled Souper instruction " +
Inst::getKindName(I->K) + " in getValue()");
}
bool runOnFunction(Function *F) {
bool Changed = false;
InstContext IC;
ExprBuilderContext EBC;
CandidateMap CandMap;
LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>(*F).getLoopInfo();
if (!LI)
report_fatal_error("getLoopInfo() failed");
auto &DT = getAnalysis<DominatorTreeWrapperPass>(*F).getDomTree();
DemandedBits *DB = &getAnalysis<DemandedBitsWrapperPass>(*F).getDemandedBits();
if (!DB)
report_fatal_error("getDemandedBits() failed");
TargetLibraryInfo* TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
if (!TLI)
report_fatal_error("getTLI() failed");
FunctionCandidateSet CS = ExtractCandidatesFromPass(F, LI, DB, TLI, IC, EBC);
std::string FunctionName;
if (F->hasLocalLinkage()) {
FunctionName =
(F->getParent()->getModuleIdentifier() + ":" + F->getName()).str();
} else {
FunctionName = F->getName();
}
if (dumpAllReplacements()) {
errs() << "\n";
errs() << "; Listing all replacements for " << FunctionName << "\n";
}
for (auto &B : CS.Blocks) {
for (auto &R : B->Replacements) {
if (dumpAllReplacements()) {
Instruction *I = R.Origin.getInstruction();
errs() << "\n; *****";
errs() << "\n; For LLVM instruction:\n;";
I->print(errs());
errs() << "\n; Generating replacement:\n";
ReplacementContext Context;
PrintReplacementLHS(errs(), R.BPCs, R.PCs, R.Mapping.LHS, Context);
}
AddToCandidateMap(CandMap, R);
}
}
if (DebugSouperPass) {
errs() << "\n";
errs() << "; Listing applied replacements for " << FunctionName << "\n";
errs() << "; Using solver: " << S->getName() << '\n';
}
for (auto &Cand : CandMap) {
if (StaticProfile) {
std::string Str;
llvm::raw_string_ostream Loc(Str);
Instruction *I = Cand.Origin.getInstruction();
I->getDebugLoc().print(Loc);
std::string HField = "sprofile " + Loc.str();
ReplacementContext Context;
KV->hIncrBy(GetReplacementLHSString(Cand.BPCs, Cand.PCs,
Cand.Mapping.LHS, Context),
HField, 1);
}
if (DynamicProfileAll) {
dynamicProfile(F, Cand);
Changed = true;
continue;
}
if (std::error_code EC =
S->infer(Cand.BPCs, Cand.PCs, Cand.Mapping.LHS,
Cand.Mapping.RHS, IC)) {
if (EC == std::errc::timed_out ||
EC == std::errc::value_too_large) {
continue;
} else {
report_fatal_error("Unable to query solver: " + EC.message() + "\n");
}
}
if (!Cand.Mapping.RHS)
continue;
// TODO: add non-const instruction support
Instruction *I = Cand.Origin.getInstruction();
Instruction *ReplacedInst = Cand.Origin.getInstruction();
Value *NewVal = getValue(Cand.Mapping.RHS, ReplacedInst, EBC, DT,
F->getParent());
if (!NewVal) {
if (DebugSouperPass)
errs() << "\"\n; replacement failed\n";
continue;
}
if (DebugSouperPass) {
errs() << "\n";
errs() << "; Replacing \"";
I->print(errs());
errs() << "\"\n; from \"";
I->getDebugLoc().print(errs());
errs() << "\"\n; with \"";
NewVal->print(errs());
errs() << "\" in:\n";
PrintReplacement(errs(), Cand.BPCs, Cand.PCs, Cand.Mapping);
errs() << "\"\n; with \"";
NewVal->print(errs());
errs() << "\"\n";
}
EBC.Origins.erase(Cand.Mapping.LHS);
EBC.Origins.insert(std::pair<Inst *, Value *>(Cand.Mapping.LHS, NewVal));
if (ReplaceCount >= FirstReplace && ReplaceCount <= LastReplace) {
if (DynamicProfile)
dynamicProfile(F, Cand);
I->replaceAllUsesWith(NewVal);
Changed = true;
} else {
if (DebugSouperPass)
errs() << "Skipping this replacement (number " << ReplaceCount <<
")\n";
}
if (ReplaceCount < std::numeric_limits<unsigned>::max())
++ReplaceCount;
}
return Changed;
}
bool runOnModule(Module &M) {
bool Changed = false;
// get the list first since the dynamic profiling adds functions as it goes
std::vector<Function *> FL;
for (auto &I : M)
FL.push_back((Function *)&I);
for (auto *F : FL)
if (!F->isDeclaration())
Changed = runOnFunction(F) || Changed;
return Changed;
}
};
char SouperPass::ID = 0;
}
namespace llvm {
void initializeSouperPassPass(llvm::PassRegistry &);
}
INITIALIZE_PASS_BEGIN(SouperPass, "souper", "Souper super-optimizer pass",
false, false)
INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
INITIALIZE_PASS_END(SouperPass, "souper", "Souper super-optimizer pass", false,
false)
static struct Register {
Register() {
initializeSouperPassPass(*llvm::PassRegistry::getPassRegistry());
}
} X;
static void registerSouperPass(
const llvm::PassManagerBuilder &Builder, llvm::legacy::PassManagerBase &PM) {
PM.add(new SouperPass);
}
static llvm::RegisterStandardPasses
#ifdef DYNAMIC_PROFILE_ALL
RegisterSouperOptimizer(llvm::PassManagerBuilder::EP_OptimizerLast,
registerSouperPass);
#else
RegisterSouperOptimizer(llvm::PassManagerBuilder::EP_Peephole,
registerSouperPass);
#endif
| apache-2.0 |
srdc/cda2fhir | src/main/java/tr/com/srdc/cda2fhir/transform/IValueSetsTransformer.java | 11124 | package tr.com.srdc.cda2fhir.transform;
/*
* #%L
* CDA to FHIR Transformer Library
* %%
* Copyright (C) 2016 SRDC Yazilim Arastirma ve Gelistirme ve Danismanlik Tic. A.S.
* %%
* 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.
* #L%
*/
import ca.uhn.fhir.model.dstu2.valueset.*;
import org.openhealthtools.mdht.uml.hl7.datatypes.CD;
import org.openhealthtools.mdht.uml.hl7.vocab.EntityClassRoot;
import org.openhealthtools.mdht.uml.hl7.vocab.EntityNameUse;
import org.openhealthtools.mdht.uml.hl7.vocab.NullFlavor;
import org.openhealthtools.mdht.uml.hl7.vocab.PostalAddressUse;
import org.openhealthtools.mdht.uml.hl7.vocab.TelecommunicationAddressUse;
import ca.uhn.fhir.model.dstu2.composite.CodeableConceptDt;
import ca.uhn.fhir.model.dstu2.composite.CodingDt;
public interface IValueSetsTransformer {
/**
* Transforms a CDA AdministrativeGenderCode string to a FHIR AdministrativeGenderEnum.
* @param cdaAdministrativeGenderCode A CDA AdministrativeGenderCode string
* @return A value from the FHIR valueset AdministrativeGenderEnum
*/
AdministrativeGenderEnum tAdministrativeGenderCode2AdministrativeGenderEnum(String cdaAdministrativeGenderCode);
/**
* Transforms a CDA AgeObservationUnit string to a FHIR AgeUnit string.
* @param cdaAgeObservationUnit A CDA AgeObservationUnit string
* @return A FHIR AgeUnit string
*/
String tAgeObservationUnit2AgeUnit(String cdaAgeObservationUnit);
/**
* Transforms a CDA AllergyCategoryCode string to a FHIR AllergyIntoleranceCategoryEnum.
* @param cdaAllergyCategoryCode A CDA AllergyCategoryCode string
* @return A value from the FHIR valueset AllergyIntoleranceCategoryEnum
*/
AllergyIntoleranceCategoryEnum tAllergyCategoryCode2AllergyIntoleranceCategoryEnum(String cdaAllergyCategoryCode);
/**
* Transforms a CDA CriticalityObservation's value's code string to a FHIR AllergyIntoleranceCriticalityEnum.
* @param cdaCriticalityObservationValue A CDA CriticalityObservation's value's code string
* @return A value from the FHIR valueset AllergyIntolerancecriticalityEnum
*/
AllergyIntoleranceCriticalityEnum tCriticalityObservationValue2AllergyIntoleranceCriticalityEnum(String cdaCriticalityObservationValue);
/**
* Transforms a CDA EncounterCode string to a FHIR EncounterClassEnum.
* @param cdaEncounterCode A CDA EncounterCode string
* @return A value from the FHIR valueset EncounterClassEnum
*/
EncounterClassEnum tEncounterCode2EncounterClassEnum(String cdaEncounterCode);
/**
* Transforms a CDA EntityClassRoot vocable to a value from the FHIR valueset GroupTypeEnum.
* @param cdaEntityClassRoot A CDA EntityClassRoot vocable
* @return A value from the FHIR valueset GroupTypeEnum
*/
GroupTypeEnum tEntityClassRoot2GroupTypeEnum(EntityClassRoot cdaEntityClassRoot);
/**
* Transforms a CDA EntityNameUse vocable to a value from the FHIR valueset NameUseEnum.
* @param cdaEntityNameUse A CDA EntityNameUse vocable
* @return A value from the FHIR valueset NameUseEnum
*/
NameUseEnum tEntityNameUse2NameUseEnum(EntityNameUse cdaEntityNameUse);
/**
* Transforms a CDA FamilyHistoryOrganizerStatusCode string to a value from the FHIR valueset FamilyHistoryStatusEnum.
* @param cdaFamilyHistoryOrganizerStatusCode A CDA FamilyHistoryOrganizerStatusCode string
* @return A value from the FHIR valueset FamilyHistoryStatusEnum
*/
FamilyHistoryStatusEnum tFamilyHistoryOrganizerStatusCode2FamilyHistoryStatusEnum(String cdaFamilyHistoryOrganizerStatusCode);
/**
* Transforms a CDA MaritalStatusCode string to a value from the FHIR valueset MaritalStatusCodesEnum.
* @param cdaMaritalStatusCode A CDA MaritalStatusCode string
* @return A value from the FHIR valueset MaritalStatusCodesEnum
*/
MaritalStatusCodesEnum tMaritalStatusCode2MaritalStatusCodesEnum(String cdaMaritalStatusCode);
/**
* Transforms a CDA NullFlavor vocable to a FHIR CodingDt composite datatype which includes the code about DataAbsentReason.
* @param cdaNullFlavor A CDA NullFlavor vocable
* @return A FHIR CodingDt composite datatype which includes the code about DataAbsentReason.
*/
CodingDt tNullFlavor2DataAbsentReasonCode(NullFlavor cdaNullFlavor);
/**
* Transforms a CDA Observation Interpretation Code to a FHIR CodeableConceptDt composite datatype which includes the code about Observation Interpretation.
* @param cdaObservationInterpretationCode A CDA Observation Interpretation Code
* @return A FHIR CodeableConceptDt composite datatype which includes the code about Observation Interpretation
*/
CodeableConceptDt tObservationInterpretationCode2ObservationInterpretationCode(CD cdaObservationInterpretationCode);
/**
* Transforms a CDA ObservationStatusCode string to a value from the FHIR valueset ObservationStatusEnum.
* @param cdaObservationStatusCode A CDA ObservationStatusCode string
* @return A value from the FHIR valueset ObservationStatusEnum
*/
ObservationStatusEnum tObservationStatusCode2ObservationStatusEnum(String cdaObservationStatusCode);
/**
* Transforms a CodeSystem string to a URL string.
* @param codeSystem a CodeSystem string
* @return A URL string
*/
String tOid2Url(String codeSystem);
/**
* Transforms a CDA ParticipationType vocable to a FHIR CodingDt composite datatype which includes the code about ParticipationType.
* @param cdaParticipationType A CDA ParticipationType vocable
* @return A FHIR CodingDt composite datatype which includes the code about ParticipationType
*/
CodingDt tParticipationType2ParticipationTypeCode(org.openhealthtools.mdht.uml.hl7.vocab.ParticipationType cdaParticipationType);
/**
* Transforms a CDA PeriodUnit string to a value from the FHIR valueset UnitsOfTimeEnum.
* @param cdaPeriodUnit A CDA PeriodUnit string
* @return A value from the FHIR valueset UnitsOfTimeEnum.
*/
UnitsOfTimeEnum tPeriodUnit2UnitsOfTimeEnum(String cdaPeriodUnit);
/**
* Transforms a CDA PostalAddressUse vocable to a value from the FHIR valueset AddressTypeEnum.
* @param cdaPostalAddressUse A CDA PostalAddressUse vocable
* @return A value from the FHIR valueset AddressTypeEnum
*/
AddressTypeEnum tPostalAddressUse2AddressTypeEnum(PostalAddressUse cdaPostalAddressUse);
/**
* Transforms a CDA PostalAddressUse vocable to a value from the FHIR valueset AddressUseEnum.
* @param cdaPostalAddressUse A CDA PostalAddressUse vocable
* @return A value from the FHIR valueset AddressUseEnum
*/
AddressUseEnum tPostalAdressUse2AddressUseEnum(PostalAddressUse cdaPostalAddressUse);
/**
* Transforms a CDA ProblemType string to a value from the FHIR valuset ConditionCategoryCodesEnum.
* @param cdaProblemType A CDA ProblemType string
* @return A value from the FHIR valuset ConditionCategoryCodesEnum
*/
ConditionCategoryCodesEnum tProblemType2ConditionCategoryCodesEnum(String cdaProblemType);
/**
* Transforms a CDA ResultOrganizer StatusCode string to a value from the FHIR valueset DiagnosticReportStatusEnum
* @param cdaResultOrganizerStatusCode A CDA ResultOrganizer StatusCode string
* @return A value from the FHIR valueset DiagnosticReportStatusEnum
*/
DiagnosticReportStatusEnum tResultOrganizerStatusCode2DiagnosticReportStatusEnum(String cdaResultOrganizerStatusCode);
/**
* Transforms a CDA RoleCode string to a FHIR CodingDt composite datatype which includes the code about PatientContactRelationship.
* @param cdaRoleCode A CDA RoleCode string
* @return A FHIR CodingDt composite datatype which includes the code about PatientContactRelationship
*/
CodingDt tRoleCode2PatientContactRelationshipCode(String cdaRoleCode);
/**
* Transforms a CDA SeverityCode string to a value from the FHIR valueset AllergyIntoleranceSeverityEnum.
* @param cdaSeverityCode A CDA SeverityCode string
* @return A value from the FHIR valueset AllergyIntoleranceSeverityEnum.
*/
AllergyIntoleranceSeverityEnum tSeverityCode2AllergyIntoleranceSeverityEnum(String cdaSeverityCode);
/**
* Transforms a CDA StatusCode string to a value from the FHIR valueset AllergyIntoleranceStatusEnum.
* @param cdaStatusCode A CDA StatusCode string
* @return A value from the FHIR valueset AllergyIntoleranceStatusEnum
*/
AllergyIntoleranceStatusEnum tStatusCode2AllergyIntoleranceStatusEnum(String cdaStatusCode);
/**
* Transforms a CDA StatusCode string to a value from the FHIR valueset ConditionClinicalStatusCodesEnum.
* @param cdaStatusCode A CDA StatusCode string
* @return A value from the FHIR valueset ConditionClinicalStatusCodesEnum
*/
ConditionClinicalStatusCodesEnum tStatusCode2ConditionClinicalStatusCodesEnum(String cdaStatusCode);
/**
* Transforms a CDA StatusCode string to a value from the FHIR valueset EncounterStateEnum.
* @param cdaStatusCode A CDA StatusCode string
* @return A value from the FHIR valueset EncounterStateEnum
*/
EncounterStateEnum tStatusCode2EncounterStatusEnum(String cdaStatusCode);
/**
* Transforms a CDA StatusCode string to a value from the FHIR valueset MedicationDispenseStatusEnum.
* @param cdaStatusCode A CDA StatusCode string
* @return A value from the FHIR valueset MedicationDispenseStatusEnum
*/
MedicationDispenseStatusEnum tStatusCode2MedicationDispenseStatusEnum(String cdaStatusCode);
/**
* Transforms a CDA StatusCode string to a value from the FHIR valueset MedicationStatementStatusEnum.
* @param cdaStatusCode A CDA StatusCode string
* @return A value from the FHIR valueset MedicationStatementStatusEnum
*/
MedicationStatementStatusEnum tStatusCode2MedicationStatementStatusEnum(String cdaStatusCode);
/**
* Transforms a CDA StatusCode string to a value from the FHIR valueset ProcedureStatusEnum.
* @param cdaStatusCode A CDA StatusCode string
* @return A value from the FHIR valueset ProcedureStatusEnum
*/
ProcedureStatusEnum tStatusCode2ProcedureStatusEnum(String cdaStatusCode);
/**
* Transforms a CDA TelecommunicationAddressUse vocable to a value from the FHIR valueset ContactPointUseEnum.
* @param cdaTelecommunicationAddressUse A CDA TelecommunicationAddressUse vocable
* @return A value from the FHIR valueset ContactPointUseEnum
*/
ContactPointUseEnum tTelecommunicationAddressUse2ContactPointUseEnum(TelecommunicationAddressUse cdaTelecommunicationAddressUse);
/**
* Transforms a CDA TelValue string to a value from the FHIR valueset ContactPointSystemEnum.
* @param cdaTelValue A CDA TelValue string
* @return A value from the FHIR valueset ContactPointSystemEnum.
*/
ContactPointSystemEnum tTelValue2ContactPointSystemEnum(String cdaTelValue);
} | apache-2.0 |
datastax/spark-cassandra-connector | connector/src/main/scala/org/apache/spark/sql/cassandra/TimeUUIDPredicateRules.scala | 2451 | /*
* Copyright DataStax, Inc.
*
* Please see the included license file for details.
*/
package org.apache.spark.sql.cassandra
import com.datastax.spark.connector.cql.TableDef
import com.datastax.spark.connector.types.TimeUUIDType
import com.datastax.spark.connector.util.Logging
import org.apache.spark.SparkConf
import org.apache.spark.sql.cassandra.PredicateOps.FilterOps
import org.apache.spark.sql.sources.Filter
/** All non-equal predicates on a TimeUUID column are going to fail and fail
* in silent way. The basic issue here is that when you use a comparison on
* a time UUID column in C* it compares based on the Time portion of the UUID. When
* Spark executes this filter (unhandled behavior) it will compare lexically, this
* will lead to results being incorrectly filtered out of the set. As long as the
* range predicate is handled completely by the connector the correct result
* will be obtained.
*/
object TimeUUIDPredicateRules extends CassandraPredicateRules with Logging {
private def isTimeUUIDNonEqualPredicate(tableDef: TableDef, predicate: Filter): Boolean = {
if (FilterOps.isSingleColumnPredicate(predicate)) {
// extract column name only from single column predicates, otherwise an exception is thrown
val columnName = FilterOps.columnName(predicate)
val isRange = FilterOps.isRangePredicate(predicate)
val isTimeUUID = tableDef.columnByName.get(columnName).exists(_.columnType == TimeUUIDType)
isRange && isTimeUUID
} else {
false
}
}
override def apply(predicates: AnalyzedPredicates, tableDef: TableDef, conf: SparkConf): AnalyzedPredicates = {
val unhandledTimeUUIDNonEqual = predicates.handledBySpark.filter(isTimeUUIDNonEqualPredicate(tableDef, _))
require(unhandledTimeUUIDNonEqual.isEmpty,
s"""
| You are attempting to do a non-equality comparison on a TimeUUID column in Spark.
| Spark can only compare TimeUUIDs Lexically which means that the comparison will be
| different than the comparison done in C* which is done based on the Time Portion of
| TimeUUID. This will in almost all cases lead to incorrect results. If possible restrict
| doing a TimeUUID comparison only to columns which can be pushed down to Cassandra.
| https://datastax-oss.atlassian.net/browse/SPARKC-405.
|
| $unhandledTimeUUIDNonEqual
""".stripMargin)
predicates
}
}
| apache-2.0 |
msmiteu/java-uuid-v1-generator | src/main/java/eu/msmit/uuid/v1/ParallelGenerator.java | 2190 | /**
* Copyright 2015 Marijn Smit (info@msmit.eu)
*
* 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 eu.msmit.uuid.v1;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
/**
* Will rotate between a pool of {@link DefaultGenerator} instances. This will
* improve speed, but also create more random results.
*
* @author Marijn Smit (info@msmit.eu)
* @since Mar 25, 2015
*/
public class ParallelGenerator implements Generator {
private static final int DEFAULT_CONCURRENCY = 4;
private final Generator[] pool_;
private final int concurrency_;
private volatile int pointer_ = 0;
/**
* Create a new {@link ParallelGenerator} with {@link #DEFAULT_CONCURRENCY}
*/
public ParallelGenerator() {
this(DEFAULT_CONCURRENCY);
}
/**
* Create a generator with the given concurrency
*
* @param concurrency
* anywhere above zero
*/
public ParallelGenerator(int concurrency) {
if (concurrency <= 0) {
throw new IllegalArgumentException();
}
pool_ = new Generator[concurrency];
concurrency_ = concurrency;
Set<Long> nodes = new HashSet<Long>();
for (int p = 0; p < concurrency; p++) {
try {
pool_[p] = new DefaultGenerator();
if (!nodes.add(pool_[p].next().node())) {
throw new Exception("Duplicate node error in "
+ getClass().getSimpleName());
}
} catch (Exception e) {
throw new Error(e);
}
}
}
/*
* (non-Javadoc)
*
* @see eu.msmit.uuid.v1.UUIDv1Gen#next()
*/
@Override
public UUID next() {
int cur;
synchronized (this) {
cur = pointer_++;
if (pointer_ >= concurrency_) {
pointer_ = 0;
}
}
return pool_[cur].next();
}
}
| apache-2.0 |
knizhnik/scalan-sql | spark/NativeTest.scala | 4754 | import org.apache.spark._
import org.apache.spark.rdd._
import org.apache.spark.sql._
import org.apache.spark.sql.catalyst.expressions.Row
import scala.reflect.ClassTag
import scala.collection.mutable.ArrayBuffer
import org.apache.spark.executor.TaskMetrics
import org.apache.spark.unsafe.memory.TaskMemoryManager
import org.apache.spark.util.{TaskCompletionListener, TaskCompletionListenerException}
class ExternalRDD(sc: SparkContext, input: RDD[Row], push: Boolean) extends RDD[Int](sc, input.dependencies) {
def compute(split: Partition, context: TaskContext): Iterator[Int] = {
val i = input.compute(split, context)
System.err.println(s"context.partitionId=${context.partitionId}")
val sum = scalaSum(i)
// val sum = nativeSumPull(i)
Seq(sum).iterator
}
def scalaSum(i: Iterator[Row]):Int = {
var sum = 0
while (i.hasNext) {
val row = i.next
for (col <- 0 until row.size) {
sum += row(col).hashCode()
}
}
sum
}
protected def getPartitions: Array[Partition] = input.partitions
@native def nativeSumPush(arr: Array[Row]):Int
@native def nativeSumPushArr(arr: Array[Int]):Int
@native def nativeSumPull(iter: Iterator[Row]):Int
}
class CombineRDD[T: ClassTag](prev: RDD[T], maxPartitions: Int) extends RDD[T](prev)
{
val inputPartitions = prev.partitions
class CombineIterator(partitions: Array[Partition], index: Int, context: TaskContext) extends Iterator[T]
{
var iter : Iterator[T] = null
var i = index
def hasNext() : Boolean = {
while ((iter == null || !iter.hasNext) && i < partitions.length) {
val ctx = new CombineTaskContext(context.stageId, context.partitionId, context.taskAttemptId, context.attemptNumber, null/*context.taskMemoryManager*/, context.isRunningLocally, context.taskMetrics)
iter = firstParent[T].compute(partitions(i), ctx)
//ctx.complete()
partitions(i) = null
i = i + maxPartitions
}
iter != null && iter.hasNext
}
def next() = { iter.next }
}
class CombineTaskContext(val stageId: Int,
val partitionId: Int,
override val taskAttemptId: Long,
override val attemptNumber: Int,
override val taskMemoryManager: TaskMemoryManager,
val runningLocally: Boolean = true,
val taskMetrics: TaskMetrics = null) extends TaskContext
{
@transient private val onCompleteCallbacks = new ArrayBuffer[TaskCompletionListener]
override def attemptId(): Long = taskAttemptId
override def addTaskCompletionListener(listener: TaskCompletionListener): this.type = {
onCompleteCallbacks += listener
this
}
def complete(): Unit = {
// Process complete callbacks in the reverse order of registration
onCompleteCallbacks.reverse.foreach { listener =>
listener.onTaskCompletion(this)
}
}
override def addTaskCompletionListener(f: TaskContext => Unit): this.type = {
onCompleteCallbacks += new TaskCompletionListener {
override def onTaskCompletion(context: TaskContext): Unit = f(context)
}
this
}
override def addOnCompleteCallback(f: () => Unit) {
onCompleteCallbacks += new TaskCompletionListener {
override def onTaskCompletion(context: TaskContext): Unit = f()
}
}
override def isCompleted(): Boolean = false
override def isRunningLocally(): Boolean = true
override def isInterrupted(): Boolean = false
}
case class CombinePartition(index : Int) extends Partition
protected def getPartitions: Array[Partition] = Array.tabulate(maxPartitions){i => CombinePartition(i)}
override def compute(partition: Partition, context: TaskContext): Iterator[T] = {
new CombineIterator(inputPartitions, partition.index, context)
}
}
object NativeTest
{
def now: Long = java.lang.System.currentTimeMillis()
def exec(rdd: ExternalRDD) = {
val start = now
val result = rdd.fold(0)((x:Int,y:Int) => x+y)
System.err.println(s"Result ${result} produced in ${now - start} second")
}
def main(args: Array[String]) = {
val conf = new SparkConf().setAppName("Spark intergration with native code")
val sc = new SparkContext(conf)
val sqlContext = new SQLContext(sc)
val data_dir = "/mnt/tpch/"
val lineitem = new CombineRDD[Row](sqlContext.parquetFile(data_dir + "lineitem.parquet").rdd, 16)
//System.loadLibrary("nativerdd")
exec(new ExternalRDD(sc, lineitem, false))
}
}
| apache-2.0 |
rfellows/pentaho-kettle | engine/src/org/pentaho/di/trans/steps/loadfileinput/LoadFileInputMeta.java | 35352 | /*! ******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2013 by Pentaho : http://www.pentaho.com
*
*******************************************************************************
*
* 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.pentaho.di.trans.steps.loadfileinput;
import java.util.List;
import java.util.Map;
import org.apache.commons.vfs.FileObject;
import org.pentaho.di.core.CheckResult;
import org.pentaho.di.core.CheckResultInterface;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleStepException;
import org.pentaho.di.core.exception.KettleXMLException;
import org.pentaho.di.core.fileinput.FileInputList;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.core.row.ValueMeta;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.core.row.value.ValueMetaFactory;
import org.pentaho.di.core.variables.VariableSpace;
import org.pentaho.di.core.vfs.KettleVFS;
import org.pentaho.di.core.xml.XMLHandler;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.repository.ObjectId;
import org.pentaho.di.repository.Repository;
import org.pentaho.di.resource.ResourceDefinition;
import org.pentaho.di.resource.ResourceNamingInterface;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.BaseStepMeta;
import org.pentaho.di.trans.step.StepDataInterface;
import org.pentaho.di.trans.step.StepInterface;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.step.StepMetaInterface;
import org.pentaho.metastore.api.IMetaStore;
import org.w3c.dom.Node;
public class LoadFileInputMeta extends BaseStepMeta implements StepMetaInterface {
private static Class<?> PKG = LoadFileInputMeta.class; // for i18n purposes, needed by Translator2!!
public static final String[] RequiredFilesDesc = new String[] {
BaseMessages.getString( PKG, "System.Combo.No" ), BaseMessages.getString( PKG, "System.Combo.Yes" ) };
public static final String[] RequiredFilesCode = new String[] { "N", "Y" };
private static final String NO = "N";
private static final String YES = "Y";
/** Array of filenames */
private String[] fileName;
/** Wildcard or filemask (regular expression) */
private String[] fileMask;
/** Wildcard or filemask to exclude (regular expression) */
private String[] excludeFileMask;
/** Flag indicating that we should include the filename in the output */
private boolean includeFilename;
/** The name of the field in the output containing the filename */
private String filenameField;
/** Flag indicating that a row number field should be included in the output */
private boolean includeRowNumber;
/** The name of the field in the output containing the row number */
private String rowNumberField;
/** The maximum number or lines to read */
private long rowLimit;
/** The fields to import... */
private LoadFileInputField[] inputFields;
/** The encoding to use for reading: null or empty string means system default encoding */
private String encoding;
/** Dynamic FilenameField */
private String DynamicFilenameField;
/** Is In fields */
private boolean fileinfield;
/** Flag: add result filename **/
private boolean addresultfile;
/** Array of boolean values as string, indicating if a file is required. */
private String[] fileRequired;
/** Flag : do we ignore empty file? */
private boolean IsIgnoreEmptyFile;
/** Array of boolean values as string, indicating if we need to fetch sub folders. */
private String[] includeSubFolders;
/** Additional fields **/
private String shortFileFieldName;
private String pathFieldName;
private String hiddenFieldName;
private String lastModificationTimeFieldName;
private String uriNameFieldName;
private String rootUriNameFieldName;
private String extensionFieldName;
public LoadFileInputMeta() {
super(); // allocate BaseStepMeta
}
/**
* @return Returns the shortFileFieldName.
*/
public String getShortFileNameField() {
return shortFileFieldName;
}
/**
* @param field
* The shortFileFieldName to set.
*/
public void setShortFileNameField( String field ) {
shortFileFieldName = field;
}
/**
* @return Returns the pathFieldName.
*/
public String getPathField() {
return pathFieldName;
}
/**
* @param field
* The pathFieldName to set.
*/
public void setPathField( String field ) {
this.pathFieldName = field;
}
/**
* @return Returns the hiddenFieldName.
*/
public String isHiddenField() {
return hiddenFieldName;
}
/**
* @param field
* The hiddenFieldName to set.
*/
public void setIsHiddenField( String field ) {
hiddenFieldName = field;
}
/**
* @return Returns the lastModificationTimeFieldName.
*/
public String getLastModificationDateField() {
return lastModificationTimeFieldName;
}
/**
* @param field
* The lastModificationTimeFieldName to set.
*/
public void setLastModificationDateField( String field ) {
lastModificationTimeFieldName = field;
}
/**
* @return Returns the uriNameFieldName.
*/
public String getUriField() {
return uriNameFieldName;
}
/**
* @param field
* The uriNameFieldName to set.
*/
public void setUriField( String field ) {
uriNameFieldName = field;
}
/**
* @return Returns the uriNameFieldName.
*/
public String getRootUriField() {
return rootUriNameFieldName;
}
/**
* @param field
* The rootUriNameFieldName to set.
*/
public void setRootUriField( String field ) {
rootUriNameFieldName = field;
}
/**
* @return Returns the extensionFieldName.
*/
public String getExtensionField() {
return extensionFieldName;
}
/**
* @param field
* The extensionFieldName to set.
*/
public void setExtensionField( String field ) {
extensionFieldName = field;
}
public String[] getFileRequired() {
return fileRequired;
}
public void setFileRequired( String[] fileRequired ) {
this.fileRequired = fileRequired;
}
/**
* @return Returns the excludeFileMask.
*/
public String[] getExludeFileMask() {
return excludeFileMask;
}
/**
* @param excludeFileMask
* The excludeFileMask to set.
*/
public void setExcludeFileMask( String[] excludeFileMask ) {
this.excludeFileMask = excludeFileMask;
}
/**
* @return the add result filesname flag
*/
public boolean addResultFile() {
return addresultfile;
}
/**
* @return the IsIgnoreEmptyFile flag
*/
public boolean isIgnoreEmptyFile() {
return IsIgnoreEmptyFile;
}
/**
* @param the
* IsIgnoreEmptyFile to set
*/
public void setIgnoreEmptyFile( boolean IsIgnoreEmptyFile ) {
this.IsIgnoreEmptyFile = IsIgnoreEmptyFile;
}
public void setAddResultFile( boolean addresultfile ) {
this.addresultfile = addresultfile;
}
/**
* @return Returns the input fields.
*/
public LoadFileInputField[] getInputFields() {
return inputFields;
}
/**
* @param inputFields
* The input fields to set.
*/
public void setInputFields( LoadFileInputField[] inputFields ) {
this.inputFields = inputFields;
}
/************************************
* get and set FilenameField
*************************************/
/** */
public String getDynamicFilenameField() {
return DynamicFilenameField;
}
/** */
public void setDynamicFilenameField( String DynamicFilenameField ) {
this.DynamicFilenameField = DynamicFilenameField;
}
/************************************
* get et set IsInFields
*************************************/
/** */
public boolean getIsInFields() {
return fileinfield;
}
/** */
public void setIsInFields( boolean IsInFields ) {
this.fileinfield = IsInFields;
}
/**
* @return Returns the fileMask.
*/
public String[] getFileMask() {
return fileMask;
}
/**
* @param fileMask
* The fileMask to set.
*/
public void setFileMask( String[] fileMask ) {
this.fileMask = fileMask;
}
/**
* @return Returns the fileName.
*/
public String[] getFileName() {
return fileName;
}
public String[] getIncludeSubFolders() {
return includeSubFolders;
}
public void setIncludeSubFolders( String[] includeSubFoldersin ) {
for ( int i = 0; i < includeSubFoldersin.length; i++ ) {
this.includeSubFolders[i] = getRequiredFilesCode( includeSubFoldersin[i] );
}
}
public String getRequiredFilesCode( String tt ) {
if ( tt == null ) {
return RequiredFilesCode[0];
}
if ( tt.equals( RequiredFilesDesc[1] ) ) {
return RequiredFilesCode[1];
} else {
return RequiredFilesCode[0];
}
}
public String getRequiredFilesDesc( String tt ) {
if ( tt == null ) {
return RequiredFilesDesc[0];
}
if ( tt.equals( RequiredFilesCode[1] ) ) {
return RequiredFilesDesc[1];
} else {
return RequiredFilesDesc[0];
}
}
/**
* @param fileName
* The fileName to set.
*/
public void setFileName( String[] fileName ) {
this.fileName = fileName;
}
/**
* @return Returns the filenameField.
*/
public String getFilenameField() {
return filenameField;
}
/**
* @param filenameField
* The filenameField to set.
*/
public void setFilenameField( String filenameField ) {
this.filenameField = filenameField;
}
/**
* @return Returns the includeFilename.
*/
public boolean includeFilename() {
return includeFilename;
}
/**
* @param includeFilename
* The includeFilename to set.
*/
public void setIncludeFilename( boolean includeFilename ) {
this.includeFilename = includeFilename;
}
/**
* @return Returns the includeRowNumber.
*/
public boolean includeRowNumber() {
return includeRowNumber;
}
/**
* @param includeRowNumber
* The includeRowNumber to set.
*/
public void setIncludeRowNumber( boolean includeRowNumber ) {
this.includeRowNumber = includeRowNumber;
}
/**
* @return Returns the rowLimit.
*/
public long getRowLimit() {
return rowLimit;
}
/**
* @param rowLimit
* The rowLimit to set.
*/
public void setRowLimit( long rowLimit ) {
this.rowLimit = rowLimit;
}
/**
* @return Returns the rowNumberField.
*/
public String getRowNumberField() {
return rowNumberField;
}
/**
* @param rowNumberField
* The rowNumberField to set.
*/
public void setRowNumberField( String rowNumberField ) {
this.rowNumberField = rowNumberField;
}
/**
* @return the encoding
*/
public String getEncoding() {
return encoding;
}
/**
* @param encoding
* the encoding to set
*/
public void setEncoding( String encoding ) {
this.encoding = encoding;
}
public void loadXML( Node stepnode, List<DatabaseMeta> databases, IMetaStore metaStore )
throws KettleXMLException {
readData( stepnode );
}
public Object clone() {
LoadFileInputMeta retval = (LoadFileInputMeta) super.clone();
int nrFiles = fileName.length;
int nrFields = inputFields.length;
retval.allocate( nrFiles, nrFields );
for ( int i = 0; i < nrFiles; i++ ) {
retval.fileName[i] = fileName[i];
retval.fileMask[i] = fileMask[i];
retval.excludeFileMask[i] = excludeFileMask[i];
retval.fileRequired[i] = fileRequired[i];
retval.includeSubFolders[i] = includeSubFolders[i];
}
for ( int i = 0; i < nrFields; i++ ) {
if ( inputFields[i] != null ) {
retval.inputFields[i] = (LoadFileInputField) inputFields[i].clone();
}
}
return retval;
}
public String getXML() {
StringBuffer retval = new StringBuffer();
retval.append( " " + XMLHandler.addTagValue( "include", includeFilename ) );
retval.append( " " + XMLHandler.addTagValue( "include_field", filenameField ) );
retval.append( " " + XMLHandler.addTagValue( "rownum", includeRowNumber ) );
retval.append( " " + XMLHandler.addTagValue( "addresultfile", addresultfile ) );
retval.append( " " + XMLHandler.addTagValue( "IsIgnoreEmptyFile", IsIgnoreEmptyFile ) );
retval.append( " " + XMLHandler.addTagValue( "rownum_field", rowNumberField ) );
retval.append( " " + XMLHandler.addTagValue( "encoding", encoding ) );
retval.append( " <file>" + Const.CR );
for ( int i = 0; i < fileName.length; i++ ) {
retval.append( " " + XMLHandler.addTagValue( "name", fileName[i] ) );
retval.append( " " + XMLHandler.addTagValue( "filemask", fileMask[i] ) );
retval.append( " " ).append( XMLHandler.addTagValue( "exclude_filemask", excludeFileMask[i] ) );
retval.append( " " ).append( XMLHandler.addTagValue( "file_required", fileRequired[i] ) );
retval.append( " " + XMLHandler.addTagValue( "include_subfolders", includeSubFolders[i] ) );
}
retval.append( " </file>" + Const.CR );
retval.append( " <fields>" + Const.CR );
for ( int i = 0; i < inputFields.length; i++ ) {
LoadFileInputField field = inputFields[i];
retval.append( field.getXML() );
}
retval.append( " </fields>" + Const.CR );
retval.append( " " + XMLHandler.addTagValue( "limit", rowLimit ) );
retval.append( " " + XMLHandler.addTagValue( "IsInFields", fileinfield ) );
retval.append( " " + XMLHandler.addTagValue( "DynamicFilenameField", DynamicFilenameField ) );
retval.append( " " ).append( XMLHandler.addTagValue( "shortFileFieldName", shortFileFieldName ) );
retval.append( " " ).append( XMLHandler.addTagValue( "pathFieldName", pathFieldName ) );
retval.append( " " ).append( XMLHandler.addTagValue( "hiddenFieldName", hiddenFieldName ) );
retval.append( " " ).append(
XMLHandler.addTagValue( "lastModificationTimeFieldName", lastModificationTimeFieldName ) );
retval.append( " " ).append( XMLHandler.addTagValue( "uriNameFieldName", uriNameFieldName ) );
retval.append( " " ).append( XMLHandler.addTagValue( "rootUriNameFieldName", rootUriNameFieldName ) );
retval.append( " " ).append( XMLHandler.addTagValue( "extensionFieldName", extensionFieldName ) );
return retval.toString();
}
private void readData( Node stepnode ) throws KettleXMLException {
try {
includeFilename = "Y".equalsIgnoreCase( XMLHandler.getTagValue( stepnode, "include" ) );
filenameField = XMLHandler.getTagValue( stepnode, "include_field" );
addresultfile = "Y".equalsIgnoreCase( XMLHandler.getTagValue( stepnode, "addresultfile" ) );
IsIgnoreEmptyFile = "Y".equalsIgnoreCase( XMLHandler.getTagValue( stepnode, "IsIgnoreEmptyFile" ) );
includeRowNumber = "Y".equalsIgnoreCase( XMLHandler.getTagValue( stepnode, "rownum" ) );
rowNumberField = XMLHandler.getTagValue( stepnode, "rownum_field" );
encoding = XMLHandler.getTagValue( stepnode, "encoding" );
Node filenode = XMLHandler.getSubNode( stepnode, "file" );
Node fields = XMLHandler.getSubNode( stepnode, "fields" );
int nrFiles = XMLHandler.countNodes( filenode, "name" );
int nrFields = XMLHandler.countNodes( fields, "field" );
allocate( nrFiles, nrFields );
for ( int i = 0; i < nrFiles; i++ ) {
Node filenamenode = XMLHandler.getSubNodeByNr( filenode, "name", i );
Node filemasknode = XMLHandler.getSubNodeByNr( filenode, "filemask", i );
Node excludefilemasknode = XMLHandler.getSubNodeByNr( filenode, "exclude_filemask", i );
Node fileRequirednode = XMLHandler.getSubNodeByNr( filenode, "file_required", i );
Node includeSubFoldersnode = XMLHandler.getSubNodeByNr( filenode, "include_subfolders", i );
fileName[i] = XMLHandler.getNodeValue( filenamenode );
fileMask[i] = XMLHandler.getNodeValue( filemasknode );
excludeFileMask[i] = XMLHandler.getNodeValue( excludefilemasknode );
fileRequired[i] = XMLHandler.getNodeValue( fileRequirednode );
includeSubFolders[i] = XMLHandler.getNodeValue( includeSubFoldersnode );
}
for ( int i = 0; i < nrFields; i++ ) {
Node fnode = XMLHandler.getSubNodeByNr( fields, "field", i );
LoadFileInputField field = new LoadFileInputField( fnode );
inputFields[i] = field;
}
// Is there a limit on the number of rows we process?
rowLimit = Const.toLong( XMLHandler.getTagValue( stepnode, "limit" ), 0L );
fileinfield = "Y".equalsIgnoreCase( XMLHandler.getTagValue( stepnode, "IsInFields" ) );
DynamicFilenameField = XMLHandler.getTagValue( stepnode, "DynamicFilenameField" );
shortFileFieldName = XMLHandler.getTagValue( stepnode, "shortFileFieldName" );
pathFieldName = XMLHandler.getTagValue( stepnode, "pathFieldName" );
hiddenFieldName = XMLHandler.getTagValue( stepnode, "hiddenFieldName" );
lastModificationTimeFieldName = XMLHandler.getTagValue( stepnode, "lastModificationTimeFieldName" );
uriNameFieldName = XMLHandler.getTagValue( stepnode, "uriNameFieldName" );
rootUriNameFieldName = XMLHandler.getTagValue( stepnode, "rootUriNameFieldName" );
extensionFieldName = XMLHandler.getTagValue( stepnode, "extensionFieldName" );
} catch ( Exception e ) {
throw new KettleXMLException( BaseMessages.getString( PKG, "LoadFileInputMeta.Exception.ErrorLoadingXML", e
.toString() ) );
}
}
public void allocate( int nrfiles, int nrfields ) {
fileName = new String[nrfiles];
fileMask = new String[nrfiles];
excludeFileMask = new String[nrfiles];
fileRequired = new String[nrfiles];
includeSubFolders = new String[nrfiles];
inputFields = new LoadFileInputField[nrfields];
}
public void setDefault() {
shortFileFieldName = null;
pathFieldName = null;
hiddenFieldName = null;
lastModificationTimeFieldName = null;
uriNameFieldName = null;
rootUriNameFieldName = null;
extensionFieldName = null;
encoding = "";
IsIgnoreEmptyFile = false;
includeFilename = false;
filenameField = "";
includeRowNumber = false;
rowNumberField = "";
addresultfile = true;
int nrFiles = 0;
int nrFields = 0;
allocate( nrFiles, nrFields );
for ( int i = 0; i < nrFiles; i++ ) {
fileName[i] = "filename" + ( i + 1 );
fileMask[i] = "";
excludeFileMask[i] = "";
fileRequired[i] = RequiredFilesCode[0];
includeSubFolders[i] = RequiredFilesCode[0];
}
for ( int i = 0; i < nrFields; i++ ) {
inputFields[i] = new LoadFileInputField( "field" + ( i + 1 ) );
}
rowLimit = 0;
fileinfield = false;
DynamicFilenameField = null;
}
public void getFields( RowMetaInterface r, String name, RowMetaInterface[] info, StepMeta nextStep,
VariableSpace space, Repository repository, IMetaStore metaStore ) throws KettleStepException {
if ( !getIsInFields() ) {
r.clear();
}
int i;
for ( i = 0; i < inputFields.length; i++ ) {
LoadFileInputField field = inputFields[i];
int type = field.getType();
switch ( field.getElementType() ) {
case LoadFileInputField.ELEMENT_TYPE_FILECONTENT:
if ( type == ValueMeta.TYPE_NONE ) {
type = ValueMeta.TYPE_STRING;
}
break;
case LoadFileInputField.ELEMENT_TYPE_FILESIZE:
if ( type == ValueMeta.TYPE_NONE ) {
type = ValueMeta.TYPE_INTEGER;
}
break;
default:
break;
}
try {
ValueMetaInterface v =
ValueMetaFactory.createValueMeta( space.environmentSubstitute( field.getName() ), type );
v.setLength( field.getLength() );
v.setPrecision( field.getPrecision() );
v.setConversionMask( field.getFormat() );
v.setCurrencySymbol( field.getCurrencySymbol() );
v.setDecimalSymbol( field.getDecimalSymbol() );
v.setGroupingSymbol( field.getGroupSymbol() );
v.setTrimType( field.getTrimType() );
v.setOrigin( name );
r.addValueMeta( v );
} catch ( Exception e ) {
throw new KettleStepException( e );
}
}
if ( includeFilename ) {
ValueMetaInterface v = new ValueMeta( space.environmentSubstitute( filenameField ), ValueMeta.TYPE_STRING );
v.setLength( 250 );
v.setPrecision( -1 );
v.setOrigin( name );
r.addValueMeta( v );
}
if ( includeRowNumber ) {
ValueMetaInterface v = new ValueMeta( space.environmentSubstitute( rowNumberField ), ValueMeta.TYPE_INTEGER );
v.setLength( ValueMetaInterface.DEFAULT_INTEGER_LENGTH, 0 );
v.setOrigin( name );
r.addValueMeta( v );
}
// Add additional fields
if ( getShortFileNameField() != null && getShortFileNameField().length() > 0 ) {
ValueMetaInterface v =
new ValueMeta( space.environmentSubstitute( getShortFileNameField() ), ValueMeta.TYPE_STRING );
v.setLength( 100, -1 );
v.setOrigin( name );
r.addValueMeta( v );
}
if ( getExtensionField() != null && getExtensionField().length() > 0 ) {
ValueMetaInterface v =
new ValueMeta( space.environmentSubstitute( getExtensionField() ), ValueMeta.TYPE_STRING );
v.setLength( 100, -1 );
v.setOrigin( name );
r.addValueMeta( v );
}
if ( getPathField() != null && getPathField().length() > 0 ) {
ValueMetaInterface v = new ValueMeta( space.environmentSubstitute( getPathField() ), ValueMeta.TYPE_STRING );
v.setLength( 100, -1 );
v.setOrigin( name );
r.addValueMeta( v );
}
if ( isHiddenField() != null && isHiddenField().length() > 0 ) {
ValueMetaInterface v =
new ValueMeta( space.environmentSubstitute( isHiddenField() ), ValueMeta.TYPE_BOOLEAN );
v.setOrigin( name );
r.addValueMeta( v );
}
if ( getLastModificationDateField() != null && getLastModificationDateField().length() > 0 ) {
ValueMetaInterface v =
new ValueMeta( space.environmentSubstitute( getLastModificationDateField() ), ValueMeta.TYPE_DATE );
v.setOrigin( name );
r.addValueMeta( v );
}
if ( getUriField() != null && getUriField().length() > 0 ) {
ValueMetaInterface v = new ValueMeta( space.environmentSubstitute( getUriField() ), ValueMeta.TYPE_STRING );
v.setLength( 100, -1 );
v.setOrigin( name );
r.addValueMeta( v );
}
if ( getRootUriField() != null && getRootUriField().length() > 0 ) {
ValueMetaInterface v =
new ValueMeta( space.environmentSubstitute( getRootUriField() ), ValueMeta.TYPE_STRING );
v.setLength( 100, -1 );
v.setOrigin( name );
r.addValueMeta( v );
}
}
public void readRep( Repository rep, IMetaStore metaStore, ObjectId id_step, List<DatabaseMeta> databases )
throws KettleException {
try {
includeFilename = rep.getStepAttributeBoolean( id_step, "include" );
filenameField = rep.getStepAttributeString( id_step, "include_field" );
addresultfile = rep.getStepAttributeBoolean( id_step, "addresultfile" );
IsIgnoreEmptyFile = rep.getStepAttributeBoolean( id_step, "IsIgnoreEmptyFile" );
includeRowNumber = rep.getStepAttributeBoolean( id_step, "rownum" );
rowNumberField = rep.getStepAttributeString( id_step, "rownum_field" );
rowLimit = rep.getStepAttributeInteger( id_step, "limit" );
encoding = rep.getStepAttributeString( id_step, "encoding" );
int nrFiles = rep.countNrStepAttributes( id_step, "file_name" );
int nrFields = rep.countNrStepAttributes( id_step, "field_name" );
allocate( nrFiles, nrFields );
for ( int i = 0; i < nrFiles; i++ ) {
fileName[i] = rep.getStepAttributeString( id_step, i, "file_name" );
fileMask[i] = rep.getStepAttributeString( id_step, i, "file_mask" );
excludeFileMask[i] = rep.getStepAttributeString( id_step, i, "exclude_file_mask" );
fileRequired[i] = rep.getStepAttributeString( id_step, i, "file_required" );
if ( !YES.equalsIgnoreCase( fileRequired[i] ) ) {
fileRequired[i] = NO;
}
includeSubFolders[i] = rep.getStepAttributeString( id_step, i, "include_subfolders" );
if ( !YES.equalsIgnoreCase( includeSubFolders[i] ) ) {
includeSubFolders[i] = NO;
}
}
for ( int i = 0; i < nrFields; i++ ) {
LoadFileInputField field = new LoadFileInputField();
field.setName( rep.getStepAttributeString( id_step, i, "field_name" ) );
field.setElementType( LoadFileInputField.getElementTypeByCode( rep.getStepAttributeString(
id_step, i, "element_type" ) ) );
field.setType( ValueMeta.getType( rep.getStepAttributeString( id_step, i, "field_type" ) ) );
field.setFormat( rep.getStepAttributeString( id_step, i, "field_format" ) );
field.setCurrencySymbol( rep.getStepAttributeString( id_step, i, "field_currency" ) );
field.setDecimalSymbol( rep.getStepAttributeString( id_step, i, "field_decimal" ) );
field.setGroupSymbol( rep.getStepAttributeString( id_step, i, "field_group" ) );
field.setLength( (int) rep.getStepAttributeInteger( id_step, i, "field_length" ) );
field.setPrecision( (int) rep.getStepAttributeInteger( id_step, i, "field_precision" ) );
field.setTrimType( LoadFileInputField.getTrimTypeByCode( rep.getStepAttributeString(
id_step, i, "field_trim_type" ) ) );
field.setRepeated( rep.getStepAttributeBoolean( id_step, i, "field_repeat" ) );
inputFields[i] = field;
}
fileinfield = rep.getStepAttributeBoolean( id_step, "IsInFields" );
DynamicFilenameField = rep.getStepAttributeString( id_step, "DynamicFilenameField" );
DynamicFilenameField = rep.getStepAttributeString( id_step, "DynamicFilenameField" );
shortFileFieldName = rep.getStepAttributeString( id_step, "shortFileFieldName" );
pathFieldName = rep.getStepAttributeString( id_step, "pathFieldName" );
hiddenFieldName = rep.getStepAttributeString( id_step, "hiddenFieldName" );
lastModificationTimeFieldName = rep.getStepAttributeString( id_step, "lastModificationTimeFieldName" );
rootUriNameFieldName = rep.getStepAttributeString( id_step, "rootUriNameFieldName" );
extensionFieldName = rep.getStepAttributeString( id_step, "extensionFieldName" );
} catch ( Exception e ) {
throw new KettleException( BaseMessages
.getString( PKG, "LoadFileInputMeta.Exception.ErrorReadingRepository" ), e );
}
}
public void saveRep( Repository rep, IMetaStore metaStore, ObjectId id_transformation, ObjectId id_step )
throws KettleException {
try {
rep.saveStepAttribute( id_transformation, id_step, "include", includeFilename );
rep.saveStepAttribute( id_transformation, id_step, "include_field", filenameField );
rep.saveStepAttribute( id_transformation, id_step, "addresultfile", addresultfile );
rep.saveStepAttribute( id_transformation, id_step, "IsIgnoreEmptyFile", IsIgnoreEmptyFile );
rep.saveStepAttribute( id_transformation, id_step, "rownum", includeRowNumber );
rep.saveStepAttribute( id_transformation, id_step, "rownum_field", rowNumberField );
rep.saveStepAttribute( id_transformation, id_step, "limit", rowLimit );
rep.saveStepAttribute( id_transformation, id_step, "encoding", encoding );
for ( int i = 0; i < fileName.length; i++ ) {
rep.saveStepAttribute( id_transformation, id_step, i, "file_name", fileName[i] );
rep.saveStepAttribute( id_transformation, id_step, i, "file_mask", fileMask[i] );
rep.saveStepAttribute( id_transformation, id_step, i, "excludefile_mask", excludeFileMask[i] );
rep.saveStepAttribute( id_transformation, id_step, i, "file_required", fileRequired[i] );
rep.saveStepAttribute( id_transformation, id_step, i, "include_subfolders", includeSubFolders[i] );
}
for ( int i = 0; i < inputFields.length; i++ ) {
LoadFileInputField field = inputFields[i];
rep.saveStepAttribute( id_transformation, id_step, i, "field_name", field.getName() );
rep.saveStepAttribute( id_transformation, id_step, i, "element_type", field.getElementTypeCode() );
rep.saveStepAttribute( id_transformation, id_step, i, "field_type", field.getTypeDesc() );
rep.saveStepAttribute( id_transformation, id_step, i, "field_format", field.getFormat() );
rep.saveStepAttribute( id_transformation, id_step, i, "field_currency", field.getCurrencySymbol() );
rep.saveStepAttribute( id_transformation, id_step, i, "field_decimal", field.getDecimalSymbol() );
rep.saveStepAttribute( id_transformation, id_step, i, "field_group", field.getGroupSymbol() );
rep.saveStepAttribute( id_transformation, id_step, i, "field_length", field.getLength() );
rep.saveStepAttribute( id_transformation, id_step, i, "field_precision", field.getPrecision() );
rep.saveStepAttribute( id_transformation, id_step, i, "field_trim_type", field.getTrimTypeCode() );
rep.saveStepAttribute( id_transformation, id_step, i, "field_repeat", field.isRepeated() );
}
rep.saveStepAttribute( id_transformation, id_step, "IsInFields", fileinfield );
rep.saveStepAttribute( id_transformation, id_step, "DynamicFilenameField", DynamicFilenameField );
rep.saveStepAttribute( id_transformation, id_step, "shortFileFieldName", shortFileFieldName );
rep.saveStepAttribute( id_transformation, id_step, "pathFieldName", pathFieldName );
rep.saveStepAttribute( id_transformation, id_step, "hiddenFieldName", hiddenFieldName );
rep.saveStepAttribute(
id_transformation, id_step, "lastModificationTimeFieldName", lastModificationTimeFieldName );
rep.saveStepAttribute( id_transformation, id_step, "uriNameFieldName", uriNameFieldName );
rep.saveStepAttribute( id_transformation, id_step, "rootUriNameFieldName", rootUriNameFieldName );
rep.saveStepAttribute( id_transformation, id_step, "extensionFieldName", extensionFieldName );
} catch ( Exception e ) {
throw new KettleException( BaseMessages.getString(
PKG, "LoadFileInputMeta.Exception.ErrorSavingToRepository", "" + id_step ), e );
}
}
public FileInputList getFiles( VariableSpace space ) {
return FileInputList.createFileList(
space, fileName, fileMask, excludeFileMask, fileRequired, includeSubFolderBoolean() );
}
private boolean[] includeSubFolderBoolean() {
int len = fileName.length;
boolean[] includeSubFolderBoolean = new boolean[len];
for ( int i = 0; i < len; i++ ) {
includeSubFolderBoolean[i] = YES.equalsIgnoreCase( includeSubFolders[i] );
}
return includeSubFolderBoolean;
}
public void check( List<CheckResultInterface> remarks, TransMeta transMeta, StepMeta stepMeta,
RowMetaInterface prev, String[] input, String[] output, RowMetaInterface info, VariableSpace space,
Repository repository, IMetaStore metaStore ) {
CheckResult cr;
// See if we get input...
if ( input.length <= 0 ) {
cr =
new CheckResult( CheckResult.TYPE_RESULT_ERROR, BaseMessages.getString(
PKG, "LoadFileInputMeta.CheckResult.NoInputExpected" ), stepMeta );
remarks.add( cr );
} else {
cr =
new CheckResult( CheckResult.TYPE_RESULT_OK, BaseMessages.getString(
PKG, "LoadFileInputMeta.CheckResult.NoInput" ), stepMeta );
remarks.add( cr );
}
if ( getIsInFields() ) {
if ( Const.isEmpty( getDynamicFilenameField() ) ) {
cr =
new CheckResult( CheckResult.TYPE_RESULT_ERROR, BaseMessages.getString(
PKG, "LoadFileInputMeta.CheckResult.NoField" ), stepMeta );
remarks.add( cr );
} else {
cr =
new CheckResult( CheckResult.TYPE_RESULT_OK, BaseMessages.getString(
PKG, "LoadFileInputMeta.CheckResult.FieldOk" ), stepMeta );
remarks.add( cr );
}
} else {
FileInputList fileInputList = getFiles( transMeta );
if ( fileInputList == null || fileInputList.getFiles().size() == 0 ) {
cr =
new CheckResult( CheckResult.TYPE_RESULT_ERROR, BaseMessages.getString(
PKG, "LoadFileInputMeta.CheckResult.NoFiles" ), stepMeta );
remarks.add( cr );
} else {
cr =
new CheckResult( CheckResult.TYPE_RESULT_OK, BaseMessages.getString(
PKG, "LoadFileInputMeta.CheckResult.FilesOk", "" + fileInputList.getFiles().size() ), stepMeta );
remarks.add( cr );
}
}
}
/**
* @param space
* the variable space to use
* @param definitions
* @param resourceNamingInterface
* @param repository
* The repository to optionally load other resources from (to be converted to XML)
* @param metaStore
* the metaStore in which non-kettle metadata could reside.
*
* @return the filename of the exported resource
*/
public String exportResources( VariableSpace space, Map<String, ResourceDefinition> definitions,
ResourceNamingInterface resourceNamingInterface, Repository repository, IMetaStore metaStore )
throws KettleException {
try {
// The object that we're modifying here is a copy of the original!
// So let's change the filename from relative to absolute by grabbing the file object...
//
if ( !fileinfield ) {
for ( int i = 0; i < fileName.length; i++ ) {
FileObject fileObject = KettleVFS.getFileObject( space.environmentSubstitute( fileName[i] ), space );
fileName[i] = resourceNamingInterface.nameResource( fileObject, space, Const.isEmpty( fileMask[i] ) );
}
}
return null;
} catch ( Exception e ) {
throw new KettleException( e );
}
}
public StepInterface getStep( StepMeta stepMeta, StepDataInterface stepDataInterface, int cnr,
TransMeta transMeta, Trans trans ) {
return new LoadFileInput( stepMeta, stepDataInterface, cnr, transMeta, trans );
}
public StepDataInterface getStepData() {
return new LoadFileInputData();
}
public boolean supportsErrorHandling() {
return true;
}
}
| apache-2.0 |
graham22/Classic | j2modlite/src/main/java/ca/farrelltonsolar/j2modlite/procimg/InputRegister.java | 2592 | //License
/***
* Java Modbus Library (jamod)
* Copyright (c) 2002-2004, jamod development team
* 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 the author 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 HOLDER 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.
***/
package ca.farrelltonsolar.j2modlite.procimg;
/**
* Interface defining an input register.
* <p>
* This register is read only from the slave side.
*
* @author Dieter Wimberger
* @version 1.2rc1 (09/11/2004)
*/
public interface InputRegister {
/**
* Returns the value of this <tt>InputRegister</tt>. The value is stored as
* <tt>int</tt> but should be treated like a 16-bit word.
*
* @return the value as <tt>int</tt>.
*/
public int getValue();
/**
* Returns the content of this <tt>Register</tt> as unsigned 16-bit value
* (unsigned short).
*
* @return the content as unsigned short (<tt>int</tt>).
*/
public int toUnsignedShort();
/**
* Returns the content of this <tt>Register</tt> as signed 16-bit value
* (short).
*
* @return the content as <tt>short</tt>.
*/
public short toShort();
/**
* Returns the content of this <tt>Register</tt> as bytes.
*
* @return a <tt>byte[]</tt> with length 2.
*/
public byte[] toBytes();
} | apache-2.0 |
kendarorg/ECQRSFramrework | ECQRSFramrework/Samples/UsersManager/UserManager.Web/Api/Locals/OrganizationUsersController.cs | 4753 | // ===========================================================
// Copyright (c) 2014-2015, Enrico Da Ros/kendar.org
// 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.
//
// 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 HOLDER 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.
// ===========================================================
using System.Net;
using System.Web;
using ECQRS.Commons.Commands;
using ECQRS.Commons.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using UserManager.Core.Organizations.Commands;
using UserManager.Core.Organizations.ReadModel;
using UserManager.Model.Organizations;
using UserManager.Core.Users.ReadModel;
using UserManager.Core.Users.Commands;
using UserManager.Core.Applications.ReadModel;
using UserManager.Commons.ReadModel;
namespace UserManager.Api
{
[Authorize]
public class OrganizationUsersController : ApiController
{
private readonly IRepository<OrganizationGroupItem> _groups;
private readonly IRepository<OrganizationGroupRoleItem> _groupsRoles;
private readonly IRepository<OrganizationRoleItem> _roles;
private readonly IRepository<UserListItem> _users;
private readonly ICommandSender _bus;
private IRepository<OrganizationUserItem> _orgUsers;
public OrganizationUsersController(
IRepository<OrganizationGroupItem> list,
IRepository<OrganizationGroupRoleItem> groupsRoles,
IRepository<OrganizationRoleItem> roles,
IRepository<UserListItem> users,
IRepository<OrganizationUserItem> orgUsers,
ICommandSender bus)
{
_groups = list;
_bus = bus;
_groupsRoles = groupsRoles;
_roles = roles;
_users = users;
_orgUsers = orgUsers;
}
// GET: api/Organizations
[Route("api/OrganizationUsers/list/{organizationId}")]
public IEnumerable<UserListItem> GetList(Guid? organizationId, string range = null, string filter = null)
{
if (organizationId == null) throw new HttpException(400, "Invalid organization Id");
var parsedRange = AngularApiUtils.ParseRange(range);
var parsedFilters = AngularApiUtils.ParseFilter(filter);
var where = _users.Where(a=> a.Deleted == false);
if (parsedFilters.ContainsKey("EMail")) where = where.Where(a => a.EMail.Contains(parsedFilters["EMail"].ToString()));
if (parsedFilters.ContainsKey("UserName")) where = where.Where(a => a.UserName.Contains(parsedFilters["UserName"].ToString()));
var organizationUsers = _orgUsers.Where(u => u.OrganizationId == organizationId.Value && u.Deleted == false).ToList().Select(u => u.UserId).ToList();
if (organizationUsers.Count == 0) return new List<UserListItem>();
return where
.Where(u => organizationUsers.Contains(u.Id))
.DoSkip(parsedRange.From).DoTake(parsedRange.Count)
.ToList();
}
// DELETE: api/Organizations/5
[Route("api/OrganizationUsers/{organizationId}/{userId}")]
public void Delete(Guid organizationId, Guid userId)
{
var item = _orgUsers.Where(u => u.OrganizationId == organizationId && u.UserId == userId).ToList().FirstOrDefault();
_bus.SendSync(new UserOrganizationDeassociate
{
UserId = userId,
OrganizationId = organizationId
});
}
}
}
| apache-2.0 |
tolstenko/mobagen | engine/Shader.cpp | 6351 | #include "Shader.hpp"
#include "Logger.hpp"
#include "components/DirectionalLight.hpp"
#include "components/PointLight.hpp"
#include "components/SpotLight.hpp"
namespace mobagen {
Shader::Shader(void) {
g_shProg = glCreateProgram();
}
Shader::Shader(std::string shaderAssetName) {
g_shProg = glCreateProgram();
#if defined(GLES2) || defined(GLES3) || defined(EMSCRIPTEN)
addVertex(Asset(shaderAssetName + "-gles.vs").read());
addFragment(Asset(shaderAssetName + "-gles.fs").read());
#else
addVertex(Asset(shaderAssetName + ".vs").read());
addFragment(Asset(shaderAssetName + ".fs").read());
#endif
}
Shader::Shader(const char *vert_src, const char *frag_src) {
g_shProg = glCreateProgram();
addVertex(vert_src);
addFragment(frag_src);
}
Shader::~Shader(void) {
glDetachShader(g_shProg, g_shVert);
glDeleteShader(g_shVert);
glDetachShader(g_shProg, g_shFrag);
glDeleteShader(g_shFrag);
glDeleteProgram(g_shProg);
}
void Shader::addVertex(const char *vert_src) {
char shErr[1024];
int errlen;
GLint res;
// Generate some IDs for our shader programs
g_shVert = glCreateShader(GL_VERTEX_SHADER);
// Assign our above shader source code to these IDs
glShaderSource(g_shVert, 1, &vert_src, nullptr);
// Attempt to compile the source code
glCompileShader(g_shVert);
// check if compilation was successful
glGetShaderiv(g_shVert, GL_COMPILE_STATUS, &res);
if (GL_FALSE == res) {
glGetShaderInfoLog(g_shVert, 1024, &errlen, shErr);
log_err("Failed to compile vertex shader: %s", shErr);
return;
}
// Attach these shaders to the shader program
glAttachShader(g_shProg, g_shVert);
// flag the shaders to be deleted when the shader program is deleted
glDeleteShader(g_shVert);
}
void Shader::addFragment(const char *frag_src) {
char shErr[1024];
int errlen;
GLint res;
// Generate some IDs for our shader programs
g_shFrag = glCreateShader(GL_FRAGMENT_SHADER);
// Assign our above shader source code to these IDs
glShaderSource(g_shFrag, 1, &frag_src, nullptr);
// Attempt to compile the source code
glCompileShader(g_shFrag);
// check if compilation was successful
glGetShaderiv(g_shFrag, GL_COMPILE_STATUS, &res);
if (GL_FALSE == res) {
glGetShaderInfoLog(g_shFrag, 1024, &errlen, shErr);
log_err("Failed to compile fragment shader: %s", shErr);
return;
}
// Attach these shaders to the shader program
glAttachShader(g_shProg, g_shFrag);
// flag the shaders to be deleted when the shader program is deleted
glDeleteShader(g_shFrag);
}
void Shader::link(void) {
char shErr[1024];
int errlen;
GLint res;
// Link the shaders
glLinkProgram(g_shProg);
glGetProgramiv(g_shProg, GL_LINK_STATUS, &res);
if (GL_FALSE == res)
log_err("Failed to link shader program");
glValidateProgram(g_shProg);
glGetProgramiv(g_shProg, GL_VALIDATE_STATUS, &res);
if (GL_FALSE == res) {
glGetProgramInfoLog(g_shProg, 1024, &errlen, shErr);
log_err("Error validating shader: %s", shErr);
}
}
GLuint Shader::getProgram(void) {
return g_shProg;
}
void Shader::createUniform(const std::string &uniformName) {
uniformLocation[uniformName] = glGetUniformLocation(g_shProg, uniformName.c_str());
}
GLuint Shader::getUniformLocation(const std::string &uniformName) {
return uniformLocation[uniformName];
}
void Shader::setAttribLocation(const char *name, int i) {
glBindAttribLocation(g_shProg, i, name);
}
void Shader::bind(void) const {
glUseProgram(g_shProg);
}
void Shader::updateUniformDirectionalLight(const std::string &uniformName, DirectionalLight *directionalLight) {
bind();
setUniformVec3f(uniformName + ".base.color", directionalLight->getColor());
setUniform1f(uniformName + ".base.intensity", directionalLight->getIntensity());
setUniformVec3f(uniformName + ".direction", directionalLight->getParent()->getDirection().xyz());
}
void Shader::updateUniformPointLight(const std::string &uniformName, PointLight *pointLight) {
bind();
setUniformVec3f(uniformName + ".base.color", pointLight->getColor());
setUniform1f(uniformName + ".base.intensity", pointLight->getIntensity());
setUniformAttenuation(uniformName + ".attenuation", pointLight->getAttenuation());
setUniformVec3f(uniformName + ".position", pointLight->getParent()->getPosition());
setUniform1f(uniformName + ".range", pointLight->getRange());
}
void Shader::updateUniformSpotLight(const std::string &uniformName, SpotLight *spotLight) {
bind();
setUniformVec3f(uniformName + ".pointLight.base.color", spotLight->getColor());
setUniform1f(uniformName + ".pointLight.base.intensity", spotLight->getIntensity());
setUniformAttenuation(uniformName + ".pointLight.attenuation", spotLight->getAttenuation());
setUniformVec3f(uniformName + ".pointLight.position", spotLight->getParent()->getPosition());
setUniform1f(uniformName + ".pointLight.range", spotLight->getRange());
setUniformVec3f(uniformName + ".direction", spotLight->getParent()->getDirection().xyz());
setUniform1f(uniformName + ".cutoff", spotLight->getCutoff());
}
void Shader::setUniformAttenuation(const std::string &uniformName, std::shared_ptr<Attenuation> attenuation) {
setUniform1f(uniformName + ".constant", attenuation->getConstant());
setUniform1f(uniformName + ".linear", attenuation->getLinear());
setUniform1f(uniformName + ".exponent", attenuation->getExponent());
}
void Shader::setUniform1i(const std::string &uniformName, int value) {
bind();
glUniform1i(getUniformLocation(uniformName), value);
}
void Shader::setUniform1f(const std::string &uniformName, float value) {
bind();
glUniform1f(getUniformLocation(uniformName), value);
}
void Shader::setUniformVec3f(const std::string &uniformName, glm::vec3 vector) {
bind();
glUniform3f(getUniformLocation(uniformName), vector.x, vector.y, vector.z);
}
void Shader::setUniformMatrix4f(const std::string &uniformName, const glm::mat4 &matrix) {
bind();
glUniformMatrix4fv(getUniformLocation(uniformName), 1, GL_FALSE, &(matrix)[0][0]);
}
} | apache-2.0 |
osnote/LinkPHP | bin/provider/ConsoleProvider.php | 453 | <?php
namespace bin\provider;
use linkphp\event\EventDefinition;
use linkphp\event\EventServerProvider;
class ConsoleProvider implements EventServerProvider
{
public function update(EventDefinition $definition)
{
app()->make(\linkphp\console\Console::class)
->import(
require LOAD_PATH . 'command.php'
)->init();
return $definition;
// TODO: Implement update() method.
}
}
| apache-2.0 |
square/dagger | core/src/test/java/dagger/internal/KeysTest.java | 5914 | /**
* Copyright (C) 2012 Square, 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 dagger.internal;
import dagger.Lazy;
import dagger.MembersInjector;
import dagger.Provides;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
import javax.inject.Named;
import javax.inject.Provider;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import static com.google.common.truth.Truth.assertThat;
import static dagger.Provides.Type.SET;
@RunWith(JUnit4.class)
public final class KeysTest {
int primitive;
@Test public void lonePrimitiveGetsBoxed() throws NoSuchFieldException {
assertThat(fieldKey("primitive"))
.isEqualTo("java.lang.Integer");
}
Map<String, List<Integer>> mapStringListInteger;
@Test public void parameterizedTypes() throws NoSuchFieldException {
assertThat(fieldKey("mapStringListInteger"))
.isEqualTo("java.util.Map<java.lang.String, java.util.List<java.lang.Integer>>");
}
Map<String, int[]> mapStringArrayInt;
@Test public void parameterizedTypeOfPrimitiveArray() throws NoSuchFieldException {
assertThat(fieldKey("mapStringArrayInt"))
.isEqualTo("java.util.Map<java.lang.String, int[]>");
}
@Named("foo") String annotatedType;
@Test public void annotatedType() throws NoSuchFieldException {
assertThat(fieldKey("annotatedType"))
.isEqualTo("@javax.inject.Named(value=foo)/java.lang.String");
}
String className;
@Test public void testGetClassName() throws NoSuchFieldException {
assertThat(Keys.getClassName(fieldKey("className")))
.isEqualTo("java.lang.String");
}
@Named("foo") String classNameWithAnnotation;
@Test public void testGetClassNameWithoutAnnotation() throws NoSuchFieldException {
assertThat(Keys.getClassName(fieldKey("classNameWithAnnotation")))
.isEqualTo("java.lang.String");
}
String[] classNameArray;
@Test public void testGetClassNameArray() throws NoSuchFieldException {
assertThat(Keys.getClassName(fieldKey("classNameArray"))).isNull();
}
List<String> classNameParameterized;
@Test public void testGetClassParameterized() throws NoSuchFieldException {
assertThat(Keys.getClassName(fieldKey("classNameParameterized"))).isNull();
}
@Named("foo") String annotated;
@Test public void testAnnotated() throws NoSuchFieldException {
assertThat(fieldKey("annotated")).isEqualTo("@javax.inject.Named(value=foo)/java.lang.String");
assertThat(Keys.isAnnotated(fieldKey("annotated"))).isTrue();
}
String notAnnotated;
@Test public void testIsAnnotatedFalse() throws NoSuchFieldException {
assertThat(Keys.isAnnotated(fieldKey("notAnnotated"))).isFalse();
}
Provider<String> providerOfType;
String providedType;
@Test public void testGetDelegateKey() throws NoSuchFieldException {
assertThat(Keys.getBuiltInBindingsKey(fieldKey("providerOfType")))
.isEqualTo(fieldKey("providedType"));
}
@Named("/@") Provider<String> providerOfTypeAnnotated;
@Named("/@") String providedTypeAnnotated;
@Test public void testGetDelegateKeyWithAnnotation() throws NoSuchFieldException {
assertThat(Keys.getBuiltInBindingsKey(fieldKey("providerOfTypeAnnotated")))
.isEqualTo(fieldKey("providedTypeAnnotated"));
}
@Named("/@") MembersInjector<String> membersInjectorOfType;
@Named("/@") String injectedType;
@Test public void testGetDelegateKeyWithMembersInjector() throws NoSuchFieldException {
assertThat(Keys.getBuiltInBindingsKey(fieldKey("membersInjectorOfType")))
.isEqualTo("members/java.lang.String");
}
@Named("/@") Lazy<String> lazyAnnotatedString;
@Named("/@") String eagerAnnotatedString;
@Test public void testAnnotatedGetLazyKey() throws NoSuchFieldException {
assertThat(Keys.getLazyKey(fieldKey("lazyAnnotatedString")))
.isEqualTo(fieldKey("eagerAnnotatedString"));
}
Lazy<String> lazyString;
String eagerString;
@Test public void testGetLazyKey() throws NoSuchFieldException {
assertThat(Keys.getLazyKey(fieldKey("lazyString"))).isEqualTo(fieldKey("eagerString"));
}
@Test public void testGetLazyKey_WrongKeyType() throws NoSuchFieldException {
assertThat(Keys.getLazyKey(fieldKey("providerOfTypeAnnotated"))).isNull();
}
@Provides(type=SET) String elementProvides() { return "foo"; }
@Test public void testGetElementKey_NoQualifier() throws NoSuchMethodException {
Method method = KeysTest.class.getDeclaredMethod("elementProvides", new Class<?>[]{});
assertThat(Keys.getSetKey(method.getGenericReturnType(), method.getAnnotations(), method))
.isEqualTo("java.util.Set<java.lang.String>");
}
@Named("foo")
@Provides(type=SET) String qualifiedElementProvides() { return "foo"; }
@Test public void testGetElementKey_WithQualifier() throws NoSuchMethodException {
Method method = KeysTest.class.getDeclaredMethod("qualifiedElementProvides", new Class<?>[]{});
assertThat(Keys.getSetKey(method.getGenericReturnType(), method.getAnnotations(), method))
.isEqualTo("@javax.inject.Named(value=foo)/java.util.Set<java.lang.String>");
}
private String fieldKey(String fieldName) throws NoSuchFieldException {
Field field = KeysTest.class.getDeclaredField(fieldName);
return Keys.get(field.getGenericType(), field.getAnnotations(), field);
}
}
| apache-2.0 |
flychensc/orange | stock/__init__.py | 781 | """
stock API
"""
from stock.website import get_balance_sheet, get_profit_statement
from stock.fundamental import get_annual_report, get_quarterly_results
from stock.fundamental import get_stock_basics, get_basic_info
from stock.fundamental import get_level0_report, get_level1_report
from stock.fundamental import classifier_level_report, pct_change
from stock.fundamental import (get_report_data, get_profit_data,
get_operation_data, get_growth_data,
get_debtpaying_data, get_cashflow_data)
from stock.fundamental import get_bdi, get_shibor
from stock.technical import get_sh_margin_details, get_sz_margin_details
from stock.technical import get_tick_data, get_k_data, get_szzs
from stock.news import get_notices
| apache-2.0 |
Julien-Cohen/pullupgen | tests/testPullUpGen/test2/test/A.java | 134 | package testPullUpGen.test2.test;
/**
* Test : pull up m
*/
public class A extends S {
Integer m(){
return 1;
}
}
| apache-2.0 |
codesoftware/NSIGEMCO | src/main/java/co/com/codesoftware/servicio/producto/ObtenerExistenciasProducto.java | 1217 |
package co.com.codesoftware.servicio.producto;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Clase Java para obtenerExistenciasProducto complex type.
*
* <p>El siguiente fragmento de esquema especifica el contenido que se espera que haya en esta clase.
*
* <pre>
* <complexType name="obtenerExistenciasProducto">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="idDska" type="{http://www.w3.org/2001/XMLSchema}int"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "obtenerExistenciasProducto", propOrder = {
"idDska"
})
public class ObtenerExistenciasProducto {
protected int idDska;
/**
* Obtiene el valor de la propiedad idDska.
*
*/
public int getIdDska() {
return idDska;
}
/**
* Define el valor de la propiedad idDska.
*
*/
public void setIdDska(int value) {
this.idDska = value;
}
}
| apache-2.0 |
LeeHounshell/Capstone-Project | mobile/src/main/java/com/harlie/radiotheater/radiomysterytheater/model/MutableMediaMetadata.java | 1714 | /*
* Copyright (C) 2014 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.
*/
//
// THIS CODE IS REPURPOSED FROM THE GOOGLE UNIVERSAL-MEDIA-PLAYER SAMPLE
//
package com.harlie.radiotheater.radiomysterytheater.model;
import android.support.v4.media.MediaMetadataCompat;
import android.text.TextUtils;
/**
* Holder class that encapsulates a MediaMetadata and allows the actual metadata to be modified
* without requiring to rebuild the collections the metadata is in.
*/
public class MutableMediaMetadata {
public MediaMetadataCompat metadata;
public final String trackId;
public MutableMediaMetadata(String trackId, MediaMetadataCompat metadata) {
this.metadata = metadata;
this.trackId = trackId;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || o.getClass() != MutableMediaMetadata.class) {
return false;
}
MutableMediaMetadata that = (MutableMediaMetadata) o;
return TextUtils.equals(trackId, that.trackId);
}
@Override
public int hashCode() {
return trackId.hashCode();
}
}
| apache-2.0 |
ptphp/PyLib | src/webpy1/src/manage/changeHosts.py | 2045 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os, sys
class changeHosts():
systemRoot = "C:\\Windows\\System32\\drivers\\etc\\hosts"
content_local = """
222.73.17.25 www.10086.com
222.73.17.25 www.myproject.com
127.0.0.1 www.mysql.org
127.0.0.1 jjr360.com
127.0.0.1 www.jjr360.com
127.0.0.1 shop.jjr360.com
127.0.0.1 site.jjr360.com
127.0.0.1 www.rrr.jjr360.com
127.0.0.1 tt.jjr360.com
127.0.0.1 upload.jjr360.com
127.0.0.1 my.jjr360.com #å京
127.0.0.1 static.jjr360.com #䏿µ·
127.0.0.1 post.jjr360.com #æå±±
127.0.0.1 suzhou.jjr360.com #å京
127.0.0.1 bj.jjr360.com #å京
127.0.0.1 sh.jjr360.com #䏿µ·
127.0.0.1 ks.jjr360.com #æå±±
127.0.0.1 gz.jjr360.com #广å·
127.0.0.1 sz.jjr360.com #æ·±å³
127.0.0.1 hz.jjr360.com #æå·
127.0.0.1 nj.jjr360.com #å京
127.0.0.1 cz.jjr360.com #常å·
127.0.0.1 wx.jjr360.com #æ é¡
127.0.0.1 nb.jjr360.com #宿³¢
127.0.0.1 zz.jjr360.com #éå·
127.0.0.1 wz.jjr360.com #温å·
127.0.0.1 tc.jjr360.com #太ä»
127.0.0.1 zjg.jjr360.com #å¼ å®¶æ¸?
127.0.0.1 cd.jjr360.com #æé½
127.0.0.1 cq.jjr360.com #éåº
127.0.0.1 tj.jjr360.com #天津
127.0.0.1 wh.jjr360.com #æ¦æ±
127.0.0.1 dg.jjr360.com #ä¸è
127.0.0.1 www.name.jjr360.com
127.0.0.1 sy.jjr360.com #æ²é³
127.0.0.1 dl.jjr360.com #大è¿
127.0.0.1 jn.jjr360.com #æµå
127.0.0.1 hn.jjr360.com #æµ·å
127.0.0.1 sanya.jjr360.com #ä¸äº
127.0.0.1 hf.jjr360.com #åè¥
"""
content_pro = """
222.73.17.25 www.10086.com
222.73.17.25 www.myproject.com
127.0.0.1 www.mysql.org
127.0.0.1 ks.jjr360.com
127.0.0.1 suzhou.jjr360.com
127.0.0.1 my.jjr360.com
127.0.0.1 static.jjr360.com
"""
def do(self, flag):
if flag == 1:
data = self.content_local
s = "content_local"
else:
data = self.content_pro
s = "content_pro"
open(self.systemRoot, 'w').write(data)
print s + "åå
¥æå"
def main():
flag = input('enter:')
obj = changeHosts()
obj.do(flag)
if __name__ == "__main__":
main()
| apache-2.0 |
QTek/QRadio | tramatego/src/tramatego/transforms/common/launchers.py | 760 | import subprocess
def get_qradio_data(command, result_column = 0 ):
python_path = 'C:\Python27\python.exe'
qradio_path = 'C:\MaltegoTransforms\QRadio\cli_qradio.py'
error = "lol"
output = []
command_final = python_path + ' ' + qradio_path + ' ' + command
p = subprocess.Popen(command_final, stdout=subprocess.PIPE, shell=True)
out, err = p.communicate()
try:
result = out.split('\n')
del result[0]
except:
error = "yay..."
for lin in result:
try:
final_out = lin.split(',')[result_column].strip("\n").strip("\r")
if final_out != "" and final_out != " ":
output.append(final_out)
except:
error = 'oh no...'
return output
| apache-2.0 |
rpudil/midpoint | model/workflow-impl/src/main/java/com/evolveum/midpoint/wf/impl/activiti/users/MidPointUserManager.java | 1772 | /*
* Copyright (c) 2010-2013 Evolveum
*
* 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.evolveum.midpoint.wf.impl.activiti.users;
import org.activiti.engine.identity.User;
import org.activiti.engine.impl.Page;
import org.activiti.engine.impl.persistence.entity.UserEntity;
import org.activiti.engine.impl.persistence.entity.UserEntityManager;
import java.util.List;
public class MidPointUserManager extends UserEntityManager {
@Override
public User createNewUser(String userId) {
throw new UnsupportedOperationException("MidPoint user manager doesn't support creating a new user");
}
@Override
public void insertUser(User user) {
throw new UnsupportedOperationException("MidPoint user manager doesn't support inserting a new user");
}
@Override
public UserEntity findUserById(String userId) {
throw new UnsupportedOperationException("MidPoint user manager doesn't support finding a user by id");
}
@Override
public void deleteUser(String userId) {
throw new UnsupportedOperationException("MidPoint user manager doesn't support deleting a user");
}
@Override
public Boolean checkPassword(String userId, String password) {
return true;
}
}
| apache-2.0 |
leoleegit/jetty-8.0.4.v20111024 | jetty-server/src/test/java/org/eclipse/jetty/server/ssl/SslSocketTimeoutTest.java | 2624 | // ========================================================================
// Copyright (c) 2010 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
package org.eclipse.jetty.server.ssl;
import java.io.FileInputStream;
import java.net.Socket;
import java.security.KeyStore;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManagerFactory;
import org.eclipse.jetty.http.ssl.SslContextFactory;
import org.eclipse.jetty.server.ConnectorTimeoutTest;
import org.junit.BeforeClass;
public class SslSocketTimeoutTest extends ConnectorTimeoutTest
{
static SSLContext __sslContext;
@Override
protected Socket newSocket(String host, int port) throws Exception
{
SSLSocket socket = (SSLSocket)__sslContext.getSocketFactory().createSocket(host,port);
socket.setEnabledProtocols(new String[] {"TLSv1"});
return socket;
}
@BeforeClass
public static void init() throws Exception
{
SslSocketConnector connector = new SslSocketConnector();
connector.setMaxIdleTime(MAX_IDLE_TIME); //250 msec max idle
String keystorePath = System.getProperty("basedir",".") + "/src/test/resources/keystore";
SslContextFactory cf = connector.getSslContextFactory();
cf.setKeyStorePath(keystorePath);
cf.setKeyStorePassword("storepwd");
cf.setKeyManagerPassword("keypwd");
cf.setTrustStore(keystorePath);
cf.setTrustStorePassword("storepwd");
startServer(connector);
KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
keystore.load(new FileInputStream(connector.getKeystore()), "storepwd".toCharArray());
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keystore);
__sslContext = SSLContext.getInstance("TLSv1");
__sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
}
}
| apache-2.0 |
oehme/analysing-gradle-performance | commons/src/main/java/org/gradle/test/performance/mediummonolithicjavaproject/p4/Production86.java | 1887 | package org.gradle.test.performance.mediummonolithicjavaproject.p4;
public class Production86 {
private String property0;
public String getProperty0() {
return property0;
}
public void setProperty0(String value) {
property0 = value;
}
private String property1;
public String getProperty1() {
return property1;
}
public void setProperty1(String value) {
property1 = value;
}
private String property2;
public String getProperty2() {
return property2;
}
public void setProperty2(String value) {
property2 = value;
}
private String property3;
public String getProperty3() {
return property3;
}
public void setProperty3(String value) {
property3 = value;
}
private String property4;
public String getProperty4() {
return property4;
}
public void setProperty4(String value) {
property4 = value;
}
private String property5;
public String getProperty5() {
return property5;
}
public void setProperty5(String value) {
property5 = value;
}
private String property6;
public String getProperty6() {
return property6;
}
public void setProperty6(String value) {
property6 = value;
}
private String property7;
public String getProperty7() {
return property7;
}
public void setProperty7(String value) {
property7 = value;
}
private String property8;
public String getProperty8() {
return property8;
}
public void setProperty8(String value) {
property8 = value;
}
private String property9;
public String getProperty9() {
return property9;
}
public void setProperty9(String value) {
property9 = value;
}
} | apache-2.0 |
couchbase/couchbase-lite-java-core | src/main/java/com/couchbase/lite/storage/SQLiteNativeLibrary.java | 3532 | /**
* Created by Pasin Suriyentrakorn.
*
* Copyright (c) 2015 Couchbase, Inc. 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 com.couchbase.lite.storage;
import com.couchbase.lite.util.Log;
import com.couchbase.lite.util.NativeLibraryUtils;
public class SQLiteNativeLibrary {
private static final String TAG = Log.TAG_DATABASE;
// JNI Native libraries:
public static final String JNI_SQLITE_CUSTOM_LIBRARY = "cbljavasqlitecustom";
public static final String JNI_SQLCIPHER_LIBRARY = "cbljavasqlcipher";
public static final String[] NATIVE_LIBRARY_OPTIONS =
{JNI_SQLCIPHER_LIBRARY, JNI_SQLITE_CUSTOM_LIBRARY};
// Use this to override auto loading native libraries:
public static String TEST_NATIVE_LIBRARY_NAME = null;
// JNI Key Derivation Native library:
private static final String JNI_KEY_LIBRARY = "cbljavakey";
// SQLite library:
private static final String SHARED_ANDROID_SQLITE_LIBRARY = "sqlite";
private static final String SHARED_SQLITE_LIBRARY = "sqlite3";
// SQLCipher library:
private static final String SHARED_SQLCIPHER_LIBRARY = "sqlcipher";
public static void load() {
String[] libraryOption;
if (TEST_NATIVE_LIBRARY_NAME != null) {
libraryOption = new String[1];
libraryOption[0] = TEST_NATIVE_LIBRARY_NAME;
} else {
libraryOption = NATIVE_LIBRARY_OPTIONS;
}
String loadedLibrary = null;
boolean success = false;
for (String libName : libraryOption) {
if (JNI_SQLCIPHER_LIBRARY.equals(libName)) {
if (load(SHARED_SQLCIPHER_LIBRARY)) {
if (load(JNI_KEY_LIBRARY))
success = load(libName);
}
} else if (JNI_SQLITE_CUSTOM_LIBRARY.equals(libName)) {
if (load(SHARED_SQLITE_LIBRARY))
success = load(libName);
} else
Log.e(TAG, "Unknown native library name : " + libName);
if (success) {
loadedLibrary = libName;
break;
}
}
if (success)
Log.v(TAG, "Successfully load native library: " + loadedLibrary);
else
Log.e(TAG, "Cannot load native library");
}
private static boolean load(String libName) {
try {
if (isAndriod()) {
return loadSystemLibrary(libName);
} else {
return NativeLibraryUtils.loadLibrary(libName);
}
} catch (UnsatisfiedLinkError e) {
return false;
}
}
private static boolean loadSystemLibrary(String libName) {
try {
System.loadLibrary(libName);
} catch (UnsatisfiedLinkError e) {
return false;
}
return true;
}
private static boolean isAndriod() {
return (System.getProperty("java.vm.name").equalsIgnoreCase("Dalvik"));
}
}
| apache-2.0 |
Valakias/AndroidWearProject | app/src/main/java/com/example/android/sunshine/app/DetailFragment.java | 12874 | /*
* Copyright (C) 2015 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.example.android.sunshine.app;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.CardView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.example.android.sunshine.app.data.WeatherContract;
import com.example.android.sunshine.app.data.WeatherContract.WeatherEntry;
/**
* A placeholder fragment containing a simple view.
*/
public class DetailFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {
// These indices are tied to DETAIL_COLUMNS. If DETAIL_COLUMNS changes, these
// must change.
public static final int COL_WEATHER_ID = 0;
public static final int COL_WEATHER_DATE = 1;
public static final int COL_WEATHER_DESC = 2;
public static final int COL_WEATHER_MAX_TEMP = 3;
public static final int COL_WEATHER_MIN_TEMP = 4;
public static final int COL_WEATHER_HUMIDITY = 5;
public static final int COL_WEATHER_PRESSURE = 6;
public static final int COL_WEATHER_WIND_SPEED = 7;
public static final int COL_WEATHER_DEGREES = 8;
public static final int COL_WEATHER_CONDITION_ID = 9;
static final String DETAIL_URI = "URI";
static final String DETAIL_TRANSITION_ANIMATION = "DTA";
private static final String LOG_TAG = DetailFragment.class.getSimpleName();
private static final String FORECAST_SHARE_HASHTAG = " #SunshineApp";
private static final int DETAIL_LOADER = 0;
private static final String[] DETAIL_COLUMNS = {
WeatherEntry.TABLE_NAME + "." + WeatherEntry._ID,
WeatherEntry.COLUMN_DATE,
WeatherEntry.COLUMN_SHORT_DESC,
WeatherEntry.COLUMN_MAX_TEMP,
WeatherEntry.COLUMN_MIN_TEMP,
WeatherEntry.COLUMN_HUMIDITY,
WeatherEntry.COLUMN_PRESSURE,
WeatherEntry.COLUMN_WIND_SPEED,
WeatherEntry.COLUMN_DEGREES,
WeatherEntry.COLUMN_WEATHER_ID,
// This works because the WeatherProvider returns location data joined with
// weather data, even though they're stored in two different tables.
WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING
};
private String mForecast;
private Uri mUri;
private boolean mTransitionAnimation;
private ImageView mIconView;
private TextView mDateView;
private TextView mDescriptionView;
private TextView mHighTempView;
private TextView mLowTempView;
private TextView mHumidityView;
private TextView mHumidityLabelView;
private TextView mWindView;
private TextView mWindLabelView;
private TextView mPressureView;
private TextView mPressureLabelView;
public DetailFragment() {
setHasOptionsMenu(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Bundle arguments = getArguments();
if (arguments != null) {
mUri = arguments.getParcelable(DetailFragment.DETAIL_URI);
mTransitionAnimation = arguments.getBoolean(DetailFragment.DETAIL_TRANSITION_ANIMATION, false);
}
View rootView = inflater.inflate(R.layout.fragment_detail_start, container, false);
mIconView = (ImageView) rootView.findViewById(R.id.detail_icon);
mDateView = (TextView) rootView.findViewById(R.id.detail_date_textview);
mDescriptionView = (TextView) rootView.findViewById(R.id.detail_forecast_textview);
mHighTempView = (TextView) rootView.findViewById(R.id.detail_high_textview);
mLowTempView = (TextView) rootView.findViewById(R.id.detail_low_textview);
mHumidityView = (TextView) rootView.findViewById(R.id.detail_humidity_textview);
mHumidityLabelView = (TextView) rootView.findViewById(R.id.detail_humidity_label_textview);
mWindView = (TextView) rootView.findViewById(R.id.detail_wind_textview);
mWindLabelView = (TextView) rootView.findViewById(R.id.detail_wind_label_textview);
mPressureView = (TextView) rootView.findViewById(R.id.detail_pressure_textview);
mPressureLabelView = (TextView) rootView.findViewById(R.id.detail_pressure_label_textview);
return rootView;
}
private void finishCreatingMenu(Menu menu) {
// Retrieve the share menu item
MenuItem menuItem = menu.findItem(R.id.action_share);
menuItem.setIntent(createShareForecastIntent());
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
if ( getActivity() instanceof DetailActivity ){
// Inflate the menu; this adds items to the action bar if it is present.
inflater.inflate(R.menu.detailfragment, menu);
finishCreatingMenu(menu);
}
}
private Intent createShareForecastIntent() {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, mForecast + FORECAST_SHARE_HASHTAG);
return shareIntent;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
getLoaderManager().initLoader(DETAIL_LOADER, null, this);
super.onActivityCreated(savedInstanceState);
}
void onLocationChanged( String newLocation ) {
// replace the uri, since the location has changed
Uri uri = mUri;
if (null != uri) {
long date = WeatherContract.WeatherEntry.getDateFromUri(uri);
Uri updatedUri = WeatherContract.WeatherEntry.buildWeatherLocationWithDate(newLocation, date);
mUri = updatedUri;
getLoaderManager().restartLoader(DETAIL_LOADER, null, this);
}
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
if ( null != mUri ) {
// Now create and return a CursorLoader that will take care of
// creating a Cursor for the data being displayed.
return new CursorLoader(
getActivity(),
mUri,
DETAIL_COLUMNS,
null,
null,
null
);
}
ViewParent vp = getView().getParent();
if ( vp instanceof CardView ) {
((View)vp).setVisibility(View.INVISIBLE);
}
return null;
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
if (data != null && data.moveToFirst()) {
ViewParent vp = getView().getParent();
if ( vp instanceof CardView ) {
((View)vp).setVisibility(View.VISIBLE);
}
// Read weather condition ID from cursor
int weatherId = data.getInt(COL_WEATHER_CONDITION_ID);
if ( Utility.usingLocalGraphics(getActivity()) ) {
mIconView.setImageResource(Utility.getArtResourceForWeatherCondition(weatherId));
} else {
// Use weather art image
Glide.with(this)
.load(Utility.getArtUrlForWeatherCondition(getActivity(), weatherId))
.error(Utility.getArtResourceForWeatherCondition(weatherId))
.crossFade()
.into(mIconView);
}
// Read date from cursor and update views for day of week and date
long date = data.getLong(COL_WEATHER_DATE);
String dateText = Utility.getFullFriendlyDayString(getActivity(),date);
mDateView.setText(dateText);
// Get description from weather condition ID
String description = Utility.getStringForWeatherCondition(getActivity(), weatherId);
mDescriptionView.setText(description);
mDescriptionView.setContentDescription(getString(R.string.a11y_forecast, description));
// For accessibility, add a content description to the icon field. Because the ImageView
// is independently focusable, it's better to have a description of the image. Using
// null is appropriate when the image is purely decorative or when the image already
// has text describing it in the same UI component.
mIconView.setContentDescription(getString(R.string.a11y_forecast_icon, description));
// Read high temperature from cursor and update view
boolean isMetric = Utility.isMetric(getActivity());
double high = data.getDouble(COL_WEATHER_MAX_TEMP);
String highString = Utility.formatTemperature(getActivity(), high);
mHighTempView.setText(highString);
mHighTempView.setContentDescription(getString(R.string.a11y_high_temp, highString));
// Read low temperature from cursor and update view
double low = data.getDouble(COL_WEATHER_MIN_TEMP);
String lowString = Utility.formatTemperature(getActivity(), low);
mLowTempView.setText(lowString);
mLowTempView.setContentDescription(getString(R.string.a11y_low_temp, lowString));
// Read humidity from cursor and update view
float humidity = data.getFloat(COL_WEATHER_HUMIDITY);
mHumidityView.setText(getActivity().getString(R.string.format_humidity, humidity));
mHumidityView.setContentDescription(getString(R.string.a11y_humidity, mHumidityView.getText()));
mHumidityLabelView.setContentDescription(mHumidityView.getContentDescription());
// Read wind speed and direction from cursor and update view
float windSpeedStr = data.getFloat(COL_WEATHER_WIND_SPEED);
float windDirStr = data.getFloat(COL_WEATHER_DEGREES);
mWindView.setText(Utility.getFormattedWind(getActivity(), windSpeedStr, windDirStr));
mWindView.setContentDescription(getString(R.string.a11y_wind, mWindView.getText()));
mWindLabelView.setContentDescription(mWindView.getContentDescription());
// Read pressure from cursor and update view
float pressure = data.getFloat(COL_WEATHER_PRESSURE);
mPressureView.setText(getString(R.string.format_pressure, pressure));
mPressureView.setContentDescription(getString(R.string.a11y_pressure, mPressureView.getText()));
mPressureLabelView.setContentDescription(mPressureView.getContentDescription());
// We still need this for the share intent
mForecast = String.format("%s - %s - %s/%s", dateText, description, high, low);
}
AppCompatActivity activity = (AppCompatActivity)getActivity();
Toolbar toolbarView = (Toolbar) getView().findViewById(R.id.toolbar);
// We need to start the enter transition after the data has loaded
if ( mTransitionAnimation ) {
activity.supportStartPostponedEnterTransition();
if ( null != toolbarView ) {
activity.setSupportActionBar(toolbarView);
activity.getSupportActionBar().setDisplayShowTitleEnabled(false);
activity.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
} else {
if ( null != toolbarView ) {
Menu menu = toolbarView.getMenu();
if ( null != menu ) menu.clear();
toolbarView.inflateMenu(R.menu.detailfragment);
finishCreatingMenu(toolbarView.getMenu());
}
}
}
@Override
public void onLoaderReset(Loader<Cursor> loader) { }
} | apache-2.0 |
armstrong/armstrong.core.arm_sections | armstrong/core/arm_sections/south_migrations/0002_auto__chg_field_section_slug__add_unique_section_full_slug.py | 2009 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Changing field 'Section.slug'
db.alter_column('arm_sections_section', 'slug', self.gf('django.db.models.fields.SlugField')(max_length=200))
# Adding unique constraint on 'Section', fields ['full_slug']
db.create_unique('arm_sections_section', ['full_slug'])
def backwards(self, orm):
# Removing unique constraint on 'Section', fields ['full_slug']
db.delete_unique('arm_sections_section', ['full_slug'])
# Changing field 'Section.slug'
db.alter_column('arm_sections_section', 'slug', self.gf('django.db.models.fields.SlugField')(max_length=50))
models = {
'arm_sections.section': {
'Meta': {'object_name': 'Section'},
'full_slug': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
u'level': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
u'lft': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
'parent': ('mptt.fields.TreeForeignKey', [], {'to': "orm['arm_sections.Section']", 'null': 'True', 'blank': 'True'}),
u'rght': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
'slug': ('django.db.models.fields.SlugField', [], {'max_length': '200'}),
'summary': ('django.db.models.fields.TextField', [], {'default': "''", 'blank': 'True'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
u'tree_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'})
}
}
complete_apps = ['arm_sections'] | apache-2.0 |
sql-machine-learning/sqlflow | go/workflow/response/response_test.go | 921 | // Copyright 2020 The SQLFlow 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 response
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestHTMLCode(t *testing.T) {
a := assert.New(t)
code := `<div align='center'> mock code </div>`
invalidHTMLCode := `<div align='center' invalid HTML code`
a.True(isHTMLCode(code))
a.False(isHTMLCode(invalidHTMLCode))
}
| apache-2.0 |
LSL-Git/ImageLabelerApp | photo-selector/src/main/java/com/sleepyzzz/photo_selector/http/okhttp/OkHttpUtils.java | 8910 | package com.sleepyzzz.photo_selector.http.okhttp;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import com.sleepyzzz.photo_selector.http.okhttp.builder.GetBuilder;
import com.sleepyzzz.photo_selector.http.okhttp.builder.HeadBuilder;
import com.sleepyzzz.photo_selector.http.okhttp.builder.OtherRequestBuilder;
import com.sleepyzzz.photo_selector.http.okhttp.builder.PostFileBuilder;
import com.sleepyzzz.photo_selector.http.okhttp.builder.PostFormBuilder;
import com.sleepyzzz.photo_selector.http.okhttp.builder.PostStringBuilder;
import com.sleepyzzz.photo_selector.http.okhttp.callback.Callback;
import com.sleepyzzz.photo_selector.http.okhttp.cookie.SimpleCookieJar;
import com.sleepyzzz.photo_selector.http.okhttp.https.HttpsUtils;
import com.sleepyzzz.photo_selector.http.okhttp.log.LoggerInterceptor;
import com.sleepyzzz.photo_selector.http.okhttp.request.RequestCall;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Response;
/**
* Created by zhy on 15/8/17.
*/
public class OkHttpUtils
{
public static final long DEFAULT_MILLISECONDS = 10000;
private static OkHttpUtils mInstance;
private OkHttpClient mOkHttpClient;
private Handler mDelivery;
public OkHttpUtils(OkHttpClient okHttpClient)
{
if (okHttpClient == null)
{
OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder();
//cookie enabled
okHttpClientBuilder.cookieJar(new SimpleCookieJar());
mDelivery = new Handler(Looper.getMainLooper());
okHttpClientBuilder.hostnameVerifier(new HostnameVerifier()
{
@Override
public boolean verify(String hostname, SSLSession session)
{
return true;
}
});
mOkHttpClient = okHttpClientBuilder.build();
} else
{
mOkHttpClient = okHttpClient;
}
}
public OkHttpUtils debug(String tag)
{
mOkHttpClient = getOkHttpClient().newBuilder().addInterceptor(new LoggerInterceptor(tag, false)).build();
return this;
}
/**
* showResponse may cause error, but you can try .
*
* @param tag
* @param showResponse
* @return
*/
public OkHttpUtils debug(String tag, boolean showResponse)
{
mOkHttpClient = getOkHttpClient().newBuilder().addInterceptor(new LoggerInterceptor(tag, showResponse)).build();
return this;
}
public static OkHttpUtils getInstance(OkHttpClient okHttpClient)
{
if (mInstance == null)
{
synchronized (OkHttpUtils.class)
{
if (mInstance == null)
{
mInstance = new OkHttpUtils(okHttpClient);
}
}
}
return mInstance;
}
public static OkHttpUtils getInstance()
{
if (mInstance == null)
{
synchronized (OkHttpUtils.class)
{
if (mInstance == null)
{
mInstance = new OkHttpUtils(null);
}
}
}
return mInstance;
}
public Handler getDelivery()
{
return mDelivery;
}
public OkHttpClient getOkHttpClient()
{
return mOkHttpClient;
}
public static GetBuilder get()
{
return new GetBuilder();
}
public static PostStringBuilder postString()
{
return new PostStringBuilder();
}
public static PostFileBuilder postFile()
{
return new PostFileBuilder();
}
public static PostFormBuilder post()
{
return new PostFormBuilder();
}
public static OtherRequestBuilder put()
{
return new OtherRequestBuilder(METHOD.PUT);
}
public static HeadBuilder head()
{
return new HeadBuilder();
}
public static OtherRequestBuilder delete()
{
return new OtherRequestBuilder(METHOD.DELETE);
}
public static OtherRequestBuilder patch()
{
return new OtherRequestBuilder(METHOD.PATCH);
}
public void execute(final RequestCall requestCall, Callback callback)
{
if (callback == null)
callback = Callback.CALLBACK_DEFAULT;
final Callback finalCallback = callback;
requestCall.getCall().enqueue(new okhttp3.Callback()
{
@Override
public void onFailure(Call call, final IOException e)
{
sendFailResultCallback(call, e, finalCallback);
}
@Override
public void onResponse(final Call call, final Response response)
{
if (response.code() >= 400 && response.code() <= 599)
{
try
{
sendFailResultCallback(call, new RuntimeException(response.body().string()), finalCallback);
} catch (IOException e)
{
e.printStackTrace();
}
return;
}
try
{
Object o = finalCallback.parseNetworkResponse(response);
sendSuccessResultCallback(o, finalCallback);
} catch (Exception e)
{
sendFailResultCallback(call, e, finalCallback);
}
}
});
}
public void sendFailResultCallback(final Call call, final Exception e, final Callback callback)
{
if (callback == null) return;
mDelivery.post(new Runnable()
{
@Override
public void run()
{
callback.onError(call, e);
callback.onAfter();
}
});
}
public void sendSuccessResultCallback(final Object object, final Callback callback)
{
if (callback == null) return;
mDelivery.post(new Runnable()
{
@Override
public void run()
{
callback.onResponse(object);
callback.onAfter();
}
});
}
public void cancelTag(Object tag)
{
for (Call call : mOkHttpClient.dispatcher().queuedCalls())
{
if (tag.equals(call.request().tag()))
{
call.cancel();
}
}
for (Call call : mOkHttpClient.dispatcher().runningCalls())
{
if (tag.equals(call.request().tag()))
{
call.cancel();
}
}
}
/**
* for https-way authentication
*
* @param certificates
*/
public void setCertificates(InputStream... certificates)
{
SSLSocketFactory sslSocketFactory = HttpsUtils.getSslSocketFactory(certificates, null, null);
Log.e("TAG", sslSocketFactory + "");
OkHttpClient.Builder builder = getOkHttpClient().newBuilder();
builder = builder.sslSocketFactory(sslSocketFactory);
mOkHttpClient = builder.build();
}
/**
* for https mutual authentication
*
* @param certificates
* @param bksFile
* @param password
*/
public void setCertificates(InputStream[] certificates, InputStream bksFile, String password)
{
mOkHttpClient = getOkHttpClient().newBuilder()
.sslSocketFactory(HttpsUtils.getSslSocketFactory(certificates, bksFile, password))
.build();
}
public void setHostNameVerifier(HostnameVerifier hostNameVerifier)
{
mOkHttpClient = getOkHttpClient().newBuilder()
.hostnameVerifier(hostNameVerifier)
.build();
}
public void setConnectTimeout(int timeout, TimeUnit units)
{
mOkHttpClient = getOkHttpClient().newBuilder()
.connectTimeout(timeout, units)
.build();
}
public void setReadTimeout(int timeout, TimeUnit units)
{
mOkHttpClient = getOkHttpClient().newBuilder()
.readTimeout(timeout, units)
.build();
}
public void setWriteTimeout(int timeout, TimeUnit units)
{
mOkHttpClient = getOkHttpClient().newBuilder()
.writeTimeout(timeout, units)
.build();
}
public static class METHOD
{
public static final String HEAD = "HEAD";
public static final String DELETE = "DELETE";
public static final String PUT = "PUT";
public static final String PATCH = "PATCH";
}
}
| apache-2.0 |
LBEVAN/capone | database/seeds/CategoryTableSeeder.php | 802 | <?php
use Illuminate\Database\Seeder;
class CategoryTableSeeder extends Seeder {
/**
* Run the database seeds.
*
* @return void
*/
public function run() {
DB::table('category')->insert([
'description' => 'Hoodie',
'code' => 'HOOD',
]);
DB::table('category')->insert([
'description' => 'T-Shirt',
'code' => 'TSHR',
]);
DB::table('category')->insert([
'description' => 'Joggers',
'code' => 'JOGG',
]);
DB::table('category')->insert([
'description' => 'Vests',
'code' => 'VEST',
]);
DB::table('category')->insert([
'description' => 'Hats',
'code' => 'HATS',
]);
}
}
| apache-2.0 |
spring-cloud-incubator/spring-cloud-vault-config | spring-cloud-vault-config/src/test/java/org/springframework/cloud/vault/config/VaultConfigKubernetesTests.java | 4223 | /*
* Copyright 2017-2018 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
*
* https://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.springframework.cloud.vault.config;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.assertj.core.util.Files;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.vault.util.VaultRule;
import org.springframework.cloud.vault.util.Version;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.util.StringUtils;
import org.springframework.vault.core.VaultOperations;
import org.springframework.vault.support.Policy;
import org.springframework.vault.support.Policy.BuiltinCapabilities;
import org.springframework.vault.support.Policy.Rule;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assume.assumeTrue;
import static org.springframework.cloud.vault.util.Settings.findWorkDir;
/**
* Integration test using config infrastructure with Kubernetes authentication.
*
* @author Michal Budzyn
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = VaultConfigKubernetesTests.TestApplication.class, properties = {
"spring.cloud.vault.authentication=kubernetes",
"spring.cloud.vault.kubernetes.role=my-role",
"spring.cloud.vault.kubernetes.service-account-token-file=../work/minikube/hello-minikube-token",
"spring.cloud.vault.application-name=VaultConfigKubernetesTests" })
public class VaultConfigKubernetesTests {
@Value("${vault.value}")
String configValue;
@BeforeClass
public static void beforeClass() {
VaultRule vaultRule = new VaultRule();
vaultRule.before();
String minikubeIp = System.getProperty("MINIKUBE_IP");
assumeTrue(StringUtils.hasText(minikubeIp) && vaultRule.prepare().getVersion()
.isGreaterThanOrEqualTo(Version.parse("0.8.3")));
if (!vaultRule.prepare().hasAuth("kubernetes")) {
vaultRule.prepare().mountAuth("kubernetes");
}
VaultOperations vaultOperations = vaultRule.prepare().getVaultOperations();
Policy policy = Policy.of(
Rule.builder().path("*").capabilities(BuiltinCapabilities.READ).build());
vaultOperations.opsForSys().createOrUpdatePolicy("testpolicy", policy);
vaultOperations.write(
"secret/" + VaultConfigKubernetesTests.class.getSimpleName(),
Collections.singletonMap("vault.value", "foo"));
File workDir = findWorkDir();
String certificate = Files.contentOf(new File(workDir, "minikube/ca.crt"),
StandardCharsets.US_ASCII);
String host = String.format("https://%s:8443", minikubeIp);
Map<String, String> kubeConfig = new HashMap<>();
kubeConfig.put("kubernetes_ca_cert", certificate);
kubeConfig.put("kubernetes_host", host);
vaultOperations.write("auth/kubernetes/config", kubeConfig);
Map<String, String> roleData = new HashMap<>();
roleData.put("bound_service_account_names", "default");
roleData.put("bound_service_account_namespaces", "default");
roleData.put("policies", "testpolicy");
roleData.put("ttl", "1h");
vaultOperations.write("auth/kubernetes/role/my-role", roleData);
}
@Test
public void contextLoads() {
assertThat(this.configValue).isEqualTo("foo");
}
@SpringBootApplication
public static class TestApplication {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}
}
| apache-2.0 |
RabbitStewDio/ivy-project-converter | src/main/scala/com/rabbitstewdio/build/ivyconverter/ProjectExclusion.scala | 308 | package com.rabbitstewdio.build.ivyconverter
import org.apache.maven.model.Exclusion
case class ProjectExclusion(org:Option[String], name: Option[String]) {
def toMavenExclusion = {
val me = new Exclusion
me.setArtifactId(name.getOrElse("*"))
me.setGroupId(org.getOrElse("*"))
me
}
}
| apache-2.0 |
concourse/concourse | atc/api/jobserver/rerun_build.go | 1631 | package jobserver
import (
"encoding/json"
"errors"
"net/http"
"github.com/concourse/concourse/atc/api/accessor"
"github.com/concourse/concourse/atc/api/present"
"github.com/concourse/concourse/atc/db"
)
func (s *Server) RerunJobBuild(pipeline db.Pipeline) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
logger := s.logger.Session("rerun-build")
jobName := r.FormValue(":job_name")
buildName := r.FormValue(":build_name")
job, found, err := pipeline.Job(jobName)
if err != nil {
logger.Error("failed-to-get-job", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
if !found {
w.WriteHeader(http.StatusNotFound)
return
}
buildToRerun, found, err := job.Build(buildName)
if err != nil {
logger.Error("failed-to-get-build-to-rerun", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
if !found {
w.WriteHeader(http.StatusNotFound)
return
}
if !buildToRerun.InputsReady() {
logger.Error("build-to-rerun-has-no-inputs", errors.New("build has no inputs"))
w.WriteHeader(http.StatusInternalServerError)
return
}
acc := accessor.GetAccessor(r)
build, err := job.RerunBuild(buildToRerun, acc.UserInfo().DisplayUserId)
if err != nil {
logger.Error("failed-to-retrigger-build", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
err = json.NewEncoder(w).Encode(present.Build(build, nil, nil))
if err != nil {
logger.Error("failed-to-encode-build", err)
w.WriteHeader(http.StatusInternalServerError)
}
})
}
| apache-2.0 |
oehf/ipf | commons/ihe/xacml20/impl/src/main/java/org/openehealth/ipf/commons/ihe/xacml20/stub/saml20/assertion/package-info.java | 844 | /*
* Copyright 2018 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.
*/
@javax.xml.bind.annotation.XmlSchema(namespace = "urn:oasis:names:tc:SAML:2.0:assertion", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package org.openehealth.ipf.commons.ihe.xacml20.stub.saml20.assertion;
| apache-2.0 |
ParTech/Expand-Descendants-Command | Source/ParTech.Commands.ExpandDescendants/ExpandDescendants.cs | 1284 | namespace ParTech.Commands
{
using System.Linq;
using Sitecore;
using Sitecore.Data.Items;
using Sitecore.Shell.Framework.Commands;
/// <summary>
/// Command that expands all the descendants of the selected item in the Content Editor tree
/// </summary>
public class ExpandDescendants : Command
{
/// <summary>
/// Executes the command in the specified context.
/// </summary>
/// <param name="context">The context.</param>
public override void Execute(CommandContext context)
{
Item parent = context.Items.FirstOrDefault();
this.RefreshChildren(parent);
}
/// <summary>
/// Refresh the parent node in the content tree.
/// </summary>
/// <param name="parent">The parent.</param>
private void RefreshChildren(Item parent)
{
if (parent != null)
{
Context.ClientPage.SendMessage(this, string.Format("item:refreshchildren(id={0})", parent.ID));
var children = parent.GetChildren();
foreach (Item child in children)
{
this.RefreshChildren(child);
}
}
}
}
} | apache-2.0 |
newcommerce/jsforms | scripts/validate.php | 697 | <?php
// validate.php
require_once("../../php_incs/tasty_error.inc.php");
require_once("../../php_incs/db.inc.php");
$table = $_GET['table'];
$field = $_GET['field'];
$value = $_GET['value'];
$function = $_GET['function'];
$modelId = $_GET['modelId'];
$result = $function($table, $field, $value, $modelId);
$data = array();
$data['result'] = $result ? "true" : "false";
outputResultJSON($data);
function string_not_exists_exact($table, $field, $value, $modelId)
{
$value = esc($value);
$query = <<< QUERY
SELECT * FROM `$table` WHERE `$field` LIKE '$value' AND `id` <> '$modelId'
QUERY;
$result = runQuery($query, "");
$totalRows = mysql_num_rows($result);
return $totalRows == 0;
}
?> | apache-2.0 |
huyanoperation/magicpet | magicpet/Classes/loader/CBaseDataAnimation.cpp | 391 | //
// CBaseDataAnimation.cpp
// magicpet
//
// Created by jia huyan on 12-1-9.
// Copyright (c) 2012年 道锋互动(北京)科技有限责任公司. All rights reserved.
//
#include <iostream>
#include "CBaseDataAnimation.h"
CBaseDataAnimation::CBaseDataAnimation()
{
}
//----------------------------------------------
//
//
CBaseDataAnimation::~CBaseDataAnimation()
{
} | apache-2.0 |
TheRingbearer/HAWKS | ode/bpel-compiler/src/main/java/org/apache/ode/bpel/compiler/wsdl/WSDLReaderImpl.java | 1540 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF 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.apache.ode.bpel.compiler.wsdl;
import javax.wsdl.WSDLException;
import javax.wsdl.factory.WSDLFactory;
/**
* Little hack to solve the disfunctional WSDL4J extension mechanism. Without
* this, WSDL4J will attempt to do Class.forName to get the WSDLFactory, which
* will break if WSDL4J is loaded from a parent class-loader (as it often is,
* e.g. in ServiceMix).
*
* @author Maciej Szefler - m s z e f l e r @ g m a i l . c o m
*
*/
class WSDLReaderImpl extends com.ibm.wsdl.xml.WSDLReaderImpl {
private WSDLFactory _localFactory;
WSDLReaderImpl(WSDLFactory factory) {
_localFactory = factory;
}
@Override
protected WSDLFactory getWSDLFactory() throws WSDLException {
return _localFactory;
}
}
| apache-2.0 |
nafae/developer | modules/adwords_appengine/src/main/java/com/google/api/ads/adwords/jaxws/v201406/cm/ExperimentReturnValue.java | 1971 |
package com.google.api.ads.adwords.jaxws.v201406.cm;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
/**
*
* A container for return values from the ExperimentService.
*
*
* <p>Java class for ExperimentReturnValue complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="ExperimentReturnValue">
* <complexContent>
* <extension base="{https://adwords.google.com/api/adwords/cm/v201406}ListReturnValue">
* <sequence>
* <element name="value" type="{https://adwords.google.com/api/adwords/cm/v201406}Experiment" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ExperimentReturnValue", propOrder = {
"value"
})
public class ExperimentReturnValue
extends ListReturnValue
{
protected List<Experiment> value;
/**
* Gets the value of the value property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the value property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getValue().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link Experiment }
*
*
*/
public List<Experiment> getValue() {
if (value == null) {
value = new ArrayList<Experiment>();
}
return this.value;
}
}
| apache-2.0 |
bryamrr/wit-webapp | app/assets/javascripts/shared/public.js | 292 | $(document).on('turbolinks:load', function () {
$("#shopping-cart").click(function () {
console.log("shopping-cart");
});
$("#team-list").click(function () {
console.log("team-list");
});
$("#settings").click(function () {
$(".aside-menu").toggleClass("open");
});
}); | apache-2.0 |
annict/annict | app/components/activities/record_activity_component.rb | 2417 | # frozen_string_literal: true
module Activities
class RecordActivityComponent < ApplicationV6Component
def initialize(view_context, activity_group:)
super view_context
@activity_group = activity_group
@user = activity_group.user.decorate
end
def render
build_html do |h|
h.tag :div, class: "card u-card-flat" do
h.tag :div, class: "card-body" do
h.tag :div, class: "mb-3" do
h.tag :a, href: view_context.profile_path(@user.username) do
h.html Pictures::AvatarPictureComponent.new(view_context,
user: @user,
width: 32).render
end
h.tag :span, class: "c-timeline__user-name ms-3" do
h.tag :a, href: view_context.profile_path(@user.username), class: "text-body fw-bold" do
h.text @user.name
end
end
h.tag :small, class: "ms-1" do
h.text t("messages._components.activities.episode_record.created")
end
h.html RelativeTimeComponent.new(
view_context,
time: @activity_group.created_at.iso8601,
class_name: "ms-1 small text-muted"
).render
end
if @activity_group.single?
record = @activity_group.first_item
h.html Contents::RecordContentComponent.new(view_context, record: record).render
else
h.tag :turbo_frame, id: view_context.dom_id(@activity_group) do
record = @activity_group.first_item
h.html Contents::RecordContentComponent.new(view_context, record: record).render
if @activity_group.activities_count > 1
h.tag :div, class: "text-center" do
h.tag :a, {
class: "py-1 small",
href: view_context.fragment_activity_item_list_path(@activity_group, page_category: page_category)
} do
h.tag :i, class: "fal fa-chevron-double-down me-1"
h.text t("messages._components.activities.episode_record.more", n: @activity_group.activities_count - 1)
end
end
end
end
end
end
end
end
end
end
end
| apache-2.0 |