language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Markdown
UTF-8
2,623
2.859375
3
[ "BSD-3-Clause", "CC-BY-3.0" ]
permissive
--- title: Free Flutter course from the App Brewery title: 来自 App Brewery 提供的免费 Flutter 教程 description: Link for registering for the free App Brewery course. description: 链接到 App Brewery 提供的免费 Flutter 教程。 tags: 课程 keywords: Flutter系列课程, Flutter视频教程, App Brewery --- <h1>This course is closed for enrollment.</h1> However, for $10 you can purchase a more in-depth version of this course, [The Complete Flutter Bootcamp with Dart][]. [The Complete Flutter Bootcamp with Dart]: https://www.appbrewery.co/p/flutter-development-bootcamp-with-dart {% comment %} <section class="landing-page__cta card text-center"> <div class="card-body"> <h2 class="landing-page__cta__headline">Sign up today</h2> <p class="landing-page__cta__body">It’s free</p> <a class="landing-page__cta__button btn btn-primary btn-cta" href="https://www.google.com/url?q=https://www.appbrewery.co/p/intro-to-flutter?utm_source%3Dgoogle%26utm_medium%3Dfreecoursebutton%26utm_campaign%3Dapp_brewery&sa=D&source=hangouts&ust=1587844936675000&usg=AFQjCNHxUa-OrkH1HkbRLZXxeG60opZI_w">Register</a> </div> </section> <br> <section class="landing-page__cta card text-center"> Sign up for the **Introduction to Flutter Development with Dart** course, created by the App Brewery in collaboration with the Google Flutter team. The course contains the first 10 hours of the Complete Flutter Development Bootcamp and will teach you all the fundamentals of Flutter development to get you started. The curriculum, developed over months with the Flutter team, teaches you Flutter **from scratch**. This Flutter development course teaches you how to code using **Dart** to build beautiful, fast, native-quality iOS and Android apps, even if you have **ZERO** programming experience. It takes you **step-by-step** through engaging and fun video tutorials and teaches you everything you need to know to get started as a Flutter developer. The course includes **10+** hours of HD video tutorials and builds your programming knowledge while making **real world apps**, including a quiz, a choose-your-own-adventure game, and even a musical instrument! By the end of this course, you will be programming in **Dart** and be ready to start building apps with **Flutter**. You'll also have a portfolio of over 8 apps that will give you a taste of what it's like to work with Flutter and Dart. Sign up today, and look forward to: * Over 10 hours of HD 1080p video content. * Building over 8 fully-fledged apps. * Comprehensive course materials and curriculum. {% endcomment %}
Java
UTF-8
1,420
3.390625
3
[]
no_license
import java.util.Arrays; import java.util.Comparator; public class LargestNumber { public Comparator<String> comparater = new Comparator<String>() { @Override public int compare(String s1, String s2) { if (s1.length()==0) return s2.length(); if (s2.length()==0) return s1.length(); int i=0,j=0; while (i<s1.length()&&j<s2.length()&&s1.charAt(i)==s2.charAt(j)){ i++; j++; } if (i==s1.length()&&j==s2.length()) return 0; if (i==s1.length()||j==s2.length()){ String n_str1 = s1.concat(s2); String n_str2 = s2.concat(s1); return compare(n_str1, n_str2); } return s1.charAt(i)-s2.charAt(j); } }; public String largestNumber(int[] nums) { String[] strs = new String[nums.length]; for (int i = 0; i < nums.length; i++) strs[i] = String.valueOf(nums[i]); Arrays.sort(strs,comparater); StringBuilder res = new StringBuilder(); if (strs[strs.length - 1].equals("0")) return "0"; for (int i = strs.length - 1; i >= 0; i--) res.append(strs[i]); return res.toString(); } public static void main(String[] args) { int[] nums = new int[]{3, 30,31, 34, 5, 9}; System.out.println(new LargestNumber().largestNumber(nums)); } }
C++
UTF-8
4,286
2.984375
3
[ "MIT" ]
permissive
#pragma once #include "Traits.h" #include "EnumNameMapping.h" namespace Lux::Json { class json_value { private: winrt::Windows::Data::Json::IJsonValue _value; public: template <typename T> static winrt::Windows::Data::Json::IJsonValue to_json(const T& value) { using namespace winrt::Windows::Data::Json; if constexpr (std::is_same<T, winrt::Windows::Data::Json::JsonValue>::value) { return value; } else if constexpr (std::is_same<T, bool>::value) { return JsonValue::CreateBooleanValue(value); } else if constexpr (std::is_enum<T>::value) { return JsonValue::CreateStringValue(Text::enum_value_name_mapping<T>::name(value)); } else if constexpr (std::is_arithmetic<T>::value) { return JsonValue::CreateNumberValue(double(value)); } else if constexpr (std::is_convertible<T, std::wstring_view>::value) { return JsonValue::CreateStringValue(winrt::hstring(value)); } else if constexpr (Traits::is_instantiation_of<std::vector, T>::value) { JsonArray jsonArray{}; for (auto& item : value) { jsonArray.Append(to_json(item)); } return jsonArray; } else if constexpr (std::is_convertible<T, json_value>::value) { return (json_value)value; } else { static_assert(false, "Cannot serialize this type to json automatically"); } } template <typename T> static T from_json(const winrt::Windows::Data::Json::IJsonValue& value) { using namespace winrt::Windows::Data::Json; if constexpr (std::is_same<T, bool>::value) { return value.GetBoolean(); } else if constexpr (std::is_enum<T>::value) { return Text::enum_value_name_mapping<T>::value(std::wstring(value.GetString())); } else if constexpr (std::is_arithmetic<T>::value) { return T(value.GetNumber()); } else if constexpr (std::is_convertible<T, std::wstring_view>::value) { return T(value.GetString()); } else if constexpr (Traits::is_instantiation_of<std::vector, T>::value) { auto jsonArray = value.GetArray(); T result; for (const auto& item : jsonArray) { result.push_back(from_json<typename T::value_type>(item)); } return result; } else if constexpr (std::is_convertible<json_value, T>::value) { return T(json_value(value)); } else { static_assert(false, "Cannot deserialize this type from json automatically"); } } json_value() : _value(winrt::Windows::Data::Json::JsonValue::CreateNullValue()) { } json_value(const winrt::Windows::Data::Json::IJsonValue& value) : _value(value) { } template <typename T> json_value(const T& value) : _value(to_json(value)) { } template <typename T> operator T() const { return from_json<T>(_value); } operator winrt::Windows::Data::Json::IJsonValue& () { return _value; } operator const winrt::Windows::Data::Json::IJsonValue& () const { return _value; } }; class json_object { private: winrt::Windows::Data::Json::JsonObject _value; public: json_object() = default; json_object(const json_value& value) : _value(winrt::Windows::Data::Json::IJsonValue(value).GetObject()) { } template <typename T> void write(const wchar_t* name, const T& value) { _value.SetNamedValue(std::wstring(name), json_value(value)); } template <typename T> void read(const wchar_t* name, T& value, const T& fallback = T{}) { auto jsonValue = _value.TryLookup(name); if (jsonValue) { value = json_value::from_json<T>(jsonValue); } else { value = fallback; } } template <typename T> T read_or(const wchar_t* name, const T& fallback = T{}) { T result; read(name, result, fallback); return result; } operator winrt::Windows::Data::Json::IJsonValue() const { return _value; } }; }
C#
UTF-8
6,858
2.5625
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using System.Text.RegularExpressions; using MEFEditor.Analyzing; using MEFEditor.Analyzing.Execution; using MEFEditor.TypeSystem; using MEFEditor.TypeSystem.Runtime; namespace MEFEditor.TypeSystem.Dialogs { /// <summary> /// Dialog provider for variable name selection. /// </summary> public partial class VariableName : Window { /// <summary> /// Name of variable that has been selected by user. Name is validated according /// to basic naming rules, context duplicity is checked. /// If no name is selected null is present. /// </summary> /// <value>The name of the result.</value> public string ResultName { get; private set; } /// <summary> /// Context of call, where new variable name will be used. Is used for /// duplicity checking. /// </summary> private readonly CallContext _context; /// <summary> /// Validator for variable form. /// </summary> static readonly Regex _variableValidator = new Regex(@"^[a-zA-Z]\w*$", RegexOptions.Compiled); /// <summary> /// Keywords that cannot be used as variable names. /// </summary> static readonly HashSet<string> _keywords = new HashSet<string>(){ "while", "do", "this", "self", "until", "base", "class", "interface", "public", "protected", }; /// <summary> /// Create dialog for selecting. /// </summary> /// <param name="initialName">Initial hint that will be offered to user.</param> /// <param name="context">Context of call, where new variable name will be used. Is used for duplicity checking.</param> private VariableName(string initialName, CallContext context) { InitializeComponent(); _context = context; Input.Text = initialName; Input.TextChanged += (e, s) => hasError(); hasError(); } /// <summary> /// Provide variable name dialog for creation edit of given definition. /// </summary> /// <param name="definition">Definition which creation edit is active.</param> /// <param name="creationContext">Context of call, where new variable name will be used. Is used for duplicity checking.</param> /// <returns>Name of variable that has been selected by user. Name is validated according /// to basic naming rules, context duplicity is checked. /// If no name is selected null is returned.</returns> public static string GetName(RuntimeTypeDefinition definition, CallContext creationContext) { return GetName(definition.TypeInfo, creationContext); } /// <summary> /// Provide variable name dialog for creation edit of given type. /// </summary> /// <param name="type">The created type.</param> /// <param name="creationContext">Context of call, where new variable name will be used. Is used for duplicity checking.</param> /// <returns>Name of variable that has been selected by user. Name is validated according /// to basic naming rules, context duplicity is checked. /// If no name is selected null is returned.</returns> public static string GetName(InstanceInfo type, CallContext creationContext) { var defaultName = getDefaultName(type, creationContext); var dialog = new VariableName(defaultName, creationContext); dialog.ShowDialog(); return dialog.ResultName; } /// <summary> /// Create default name hint for given type. /// </summary> /// <param name="type">Definition which name is created.</param> /// <param name="context">Context used for uniqueness guaranty.</param> /// <returns>Created name.</returns> private static string getDefaultName(InstanceInfo type, CallContext context) { var basename = Naming.SplitGenericPath(type.TypeName).Last(); basename = char.ToLowerInvariant(basename[0]) + basename.Substring(1); var name = basename; var variableNumber = 0; while (context.IsVariableDefined(name)) { ++variableNumber; name = basename + variableNumber; } return name; } /// <summary> /// Determine that current name has validation error. /// </summary> /// <returns>True if there is validation error in variable name.</returns> private bool hasError() { //error that will be displayed string error = null; var name = Input.Text; if (name == null || name == "") { error = "Name cannot be blank"; } else if (_keywords.Contains(name)) { error = "Name is same as keyword"; } else if (!_variableValidator.IsMatch(name)) { error = "Name has incorrect format"; } else if (_context.IsVariableDefined(name)) { error = "There already exists variable with same name"; } var hasError = error != null; Error.Text = error; Error.Visibility = hasError ? Visibility.Visible : Visibility.Hidden; OK.IsEnabled = !hasError; return hasError; } /// <summary> /// Handles the Click event of the OK control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="RoutedEventArgs"/> instance containing the event data.</param> private void OK_Click(object sender, RoutedEventArgs e) { if (!hasError()) { ResultName = Input.Text; DialogResult = true; } } /// <summary> /// Handles the Click event of the Storno control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="RoutedEventArgs"/> instance containing the event data.</param> private void Storno_Click(object sender, RoutedEventArgs e) { ResultName = null; DialogResult = true; } } }
SQL
UTF-8
424
3.015625
3
[]
no_license
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Admin_Parking_List]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[Admin_Parking_List] GO CREATE Procedure dbo.Admin_Parking_List As SET NOCOUNT ON SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED SELECT ParkingID AS ParkingID ,Parking as Value FROM ParkingVW GO GRANT EXECUTE ON [Admin_Parking_List] TO ExecuteOnlyRole GO
C++
UTF-8
18,087
3.21875
3
[ "MIT" ]
permissive
// // Created by cworrell on 7/21/2017. // #include <random> #include <ctime> #include <iostream> #include <cfloat> #include "GeneticAlgorithim.h" GeneticAlgorithim::GeneticAlgorithim(std::mt19937 &rng){ bool validNumber = false; while(!validNumber) { this->contents.clear(); for (int i = 0; i < 30; i++) { if (i == 0 || i == 3 || i == 6 || i == 9 || i == 11 || i == 14 || i == 17 || i == 21 || i == 25 || i == 28) { this->contents.push_back(GeneticAlgorithim::generateRandSign(rng)); } else if (i == 1 || i == 4 || i == 7 || i == 10 || i == 12 || i == 15 || i == 18 || i == 22 || i == 26 || i == 29) { this->contents.push_back(GeneticAlgorithim::generateRandInt(rng)); } else if (i == 2 || i == 8 || i == 16 || i == 27) { this->contents.push_back(GeneticAlgorithim::generateRandVariable(rng)); } else if (i == 5 || i == 13 || i == 19 || i == 23) { this->contents.push_back(GeneticAlgorithim::generateRandOperator(rng)); } else if (i == 24) { this->contents.push_back(GeneticAlgorithim::generateRandTrig(rng)); } else if (i == 20) { this->contents.push_back('e'); } } if(this->evaluate() != DBL_MAX && this->evaluate() != DBL_MIN && this->evaluate() != 1.762575757){ validNumber = true; } } }; GeneticAlgorithim::GeneticAlgorithim(std::vector<char> values) { for(int i = 0; i < 30; i++){ this->contents.push_back(values[i]); } } char GeneticAlgorithim::generateRandSign(std::mt19937 &engine) { std::uniform_int_distribution<int> gen(0, 1); switch (gen(engine)){ case 0: return 'p'; break; case 1: return 'n'; break; } } char GeneticAlgorithim::generateRandTrig(std::mt19937 &engine) { std::uniform_int_distribution<int> gen(0, 2); switch (gen(engine)){ case 0: return 'S'; break; case 1: return 'C'; break; case 2: return 'T'; break; } } char GeneticAlgorithim::generateRandVariable(std::mt19937 &engine) { std::uniform_int_distribution<int> gen(0, 2); switch (gen(engine)){ case 0: return 'X'; break; case 1: return 'Y'; break; case 2: return 'Z'; break; } } char GeneticAlgorithim::generateRandInt(std::mt19937 &engine) { std::uniform_int_distribution<int> gen(0, 9); switch (gen(engine)){ case 0: return '0'; break; case 1: return '1'; break; case 2: return '2'; break; case 3: return '3'; break; case 4: return '4'; break; case 5: return '5'; break; case 6: return '6'; break; case 7: return '7'; break; case 8: return '8'; break; case 9: return '9'; break; } } char GeneticAlgorithim::generateRandOperator(std::mt19937 &engine) { std::uniform_int_distribution<int> gen(0, 3); switch (gen(engine)) { case 0: return '+'; break; case 1: return '-'; break; case 2: return '*'; break; case 3: return '/'; break; } } double GeneticAlgorithim::evaluate() { double var1, var2, var3, var4, var5; double exp1, exp2, exp3, exp4, exp5, expParen; bool nan = false; //set var 1 (0-4) var1 = this->contents.at(1) - '0'; var1 *= this->returnVariableValue(this->contents.at(2)); if (this->contents.at(0) == 'n') { var1 *= -1; } exp1 = this->contents.at(4) - '0'; if (this->contents.at(3) == 'n') { exp1 *= -1; } if (var1 != 0) { var1 = pow(var1, exp1); } //set var 2 (6-10) var2 = this->contents.at(7) - '0'; var2 *= this->returnVariableValue(this->contents.at(8)); if (this->contents.at(6) == 'n') { var2 *= -1; } exp2 = this->contents.at(10) - '0'; if (this->contents.at(9) == 'n') { exp2 *= -1; } if (var2 != 0) { var2 = pow(var2, exp2); } //set var 3 (14-18) var3 = this->contents.at(15) - '0'; var3 *= this->returnVariableValue(this->contents.at(16)); if (this->contents.at(14) == 'n') { var3 *= -1; } exp3 = this->contents.at(18) - '0'; if (this->contents.at(17) == 'n') { exp3 *= -1; } if (var3 != 0) { var3 = pow(var3, exp3); } //set var 4 (20-22) exp4 = this->contents.at(22); if(this->contents.at(21) == 'n'){ exp4 *= -1; } var4 = pow(euler, exp3); var5 = this->contents.at(26) - '0'; if(this->contents.at(25) == 'n'){ var5 *= -1; } exp5 = this->contents.at(29) - '0'; if(this->contents.at(28) == 'n'){ exp5 *= -1; } if(var5 != 0) { var5 = pow(var5, exp5); } if(this->contents.at(24) == 'S'){ var5 = sin(var5); } else if(this->contents.at(24) == 'C'){ var5 = cos(var5); } else if(this->contents.at(24) == 'T'){ var5 = tan(var5); } //std::cout << " Var 1 = " << var1 << " Var 2 = " << var2 << " Var 3 = " << var3 << " Var 4 = " << var4 << " Var 5 = " << var5 << " " << std::endl; double var1and2; if(this->contents.at(5) == '*'){ var1and2 = var1 * var2; } else if(this->contents.at(5) == '/'){ if(var2 == 0){ nan = true; } else { var1and2 = var1 / var2; } } else if(this->contents.at(5) == '+'){ var1and2 = var1 + var2; } else if(this->contents.at(5) == '-'){ var1and2 = var1 - var2; } expParen = this->contents.at(12); if(this->contents.at(11) == 'n'){ expParen *= -1; } var1and2 = pow(var1and2, expParen); // + + + double result = 0; double resultaux = 0; if(!nan) { if (((contents.at(13) == '+') || (contents.at(13) == '-')) && ((contents.at(19) == '+') || (contents.at(19) == '-')) && ((contents.at(23) == '+') || (contents.at(23) == '-'))) { if(contents.at(13) == '+'){ result = var1and2 + var3; } else if(contents.at(13) == '-'){ result = var1and2 - var3; } if(contents.at(19) == '+'){ result += var4; } else if(contents.at(19) == '-'){ result -= var4; } if(contents.at(23) == '+'){ result += var5; } else if(contents.at(23) == '-'){ result -= var5; } } // * + + if (((contents.at(13) == '*') || (contents.at(13) == '/')) && ((contents.at(19) == '+') || (contents.at(19) == '-')) && ((contents.at(23) == '+') || (contents.at(23) == '-'))) { if(contents.at(13) == '*'){ result = var1and2 * var3; } else if(contents.at(13) == '/'){ if(var3 == 0){ nan = true; } else { result = var1and2 / var3; } } if(contents.at(19) == '+'){ result += var4; } else if(contents.at(19) == '-'){ result -= var4; } if(contents.at(23) == '+'){ result += var5; } else if(contents.at(23) == '-'){ result -= var5; } } // + * + if (((contents.at(13) == '+') || (contents.at(13) == '-')) && ((contents.at(19) == '*') || (contents.at(19) == '/')) && ((contents.at(23) == '+') || (contents.at(23) == '-'))) { if(contents.at(19) == '*'){ result = var3 * var4; } else if(contents.at(19) == '/'){ if(var4 == 0){ nan = true; } else{ result = var3 / var4; } } if(contents.at(13) == '+'){ result += var1and2; } else if(contents.at(13) == '-'){ result = var1and2 - result; } if(contents.at(23) == '+'){ result += var5; } else if(contents.at(23) == '-'){ result -= var5; } } // + + * if (((contents.at(13) == '+') || (contents.at(13) == '-')) && ((contents.at(19) == '+') || (contents.at(19) == '-')) && ((contents.at(23) == '*') || (contents.at(23) == '/'))) { if(contents.at(23) == '*'){ result = var4 * var5; } else if(contents.at(23) == '/'){ if(var5 == 0){ nan = true; } else{ result = var4 / var5; } } if(contents.at(13) == '+'){ resultaux = var1and2 + var3; } else if(contents.at(13) == '-'){ resultaux = var1and2 - var3; } if(contents.at(13) == '+'){ result = resultaux + result; } if(contents.at(13) == '-'){ result = resultaux - result; } } // * * + if (((contents.at(13) == '*') || (contents.at(13) == '/')) && ((contents.at(19) == '*') || (contents.at(19) == '/')) && ((contents.at(23) == '+') || (contents.at(23) == '-'))) { if(contents.at(13) == '*'){ result = var1and2 * var3; } else if(contents.at(13) == '/'){ if(var3 == 0){ nan = true; } else{ result = var1and2 / var3; } } if(contents.at(19) == '*'){ result *= var4; } else if(contents.at(19) == '/'){ if(var4 == 0){ nan = true; } else{ result /= var4; } } if(contents.at(23) == '+'){ result += var5; } else if(contents.at(23) == '-'){ result -= var5; } } // * + * if (((contents.at(13) == '*') || (contents.at(13) == '/')) && ((contents.at(19) == '+') || (contents.at(19) == '-')) && ((contents.at(23) == '*') || (contents.at(23) == '/'))) { if(contents.at(13) == '*'){ result = var1and2 * var3; } else if(contents.at(13) == '/'){ if(var3 == 0){ nan = true; } else{ result = var1and2 / var3; } } if(contents.at(23) == '*'){ resultaux = var4 * var5; } else if(contents.at(23) == '/'){ if(var5 == 0){ nan = true; } else{ resultaux = var4 / var5; } } if(contents.at(19) == '+'){ result += resultaux; } else if(contents.at(19) == '-'){ result -= resultaux; } } // + * * if (((contents.at(13) == '+') || (contents.at(13) == '-')) && ((contents.at(19) == '*') || (contents.at(19) == '/')) && ((contents.at(23) == '*') || (contents.at(23) == '/'))) { if(contents.at(19) == '*'){ result = var3 * var4; } else if(contents.at(19) == '/'){ if(var4 == 0){ nan = true; } else{ result = var3 / var4; } } if(contents.at(23) == '*'){ result *= var5; } else if(contents.at(23) == '/'){ if(var5 == 0){ nan = true; } else{ result /= var5; } } if(contents.at(13) == '+'){ result += var1and2; } else if(contents.at(13) == '-'){ result = var1and2 - result; } } // * * * if (((contents.at(13) == '*') || (contents.at(13) == '/')) && ((contents.at(19) == '*') || (contents.at(19) == '/')) && ((contents.at(23) == '*') || (contents.at(23) == '/'))) { if(contents.at(13) == '*'){ result = var1and2 * var3; } else if(contents.at(13) == '/'){ if(var3 == 0){ nan = true; } else{ result = var1and2 / var3; } } if(contents.at(19) == '*'){ result *= var4; } else if(contents.at(19) == '/'){ if(var4 == 0){ nan = true; } else{ result /= var4; } } if(contents.at(23) == '*'){ result *= var5; } else if(contents.at(23) == '/'){ if(var5 == 0){ nan = true; } else{ result /= var5; } } } } if(nan){ return 1.762575757; } else if(std::isinf(result)){ //std::cout << " Max " << std::endl; return DBL_MAX; } else{ return result; } } void GeneticAlgorithim::sort(std::vector<GeneticAlgorithim *> &list) { std::vector<double> values; for(int i = 0; i < list.size(); i++){ values.push_back(list[i]->evaluate()); } double swap; GeneticAlgorithim* swapPnt; for(int i = 0; i < values.size(); i++){ for(int j = 0; j < values.size() - 1; j++){ if(values[j] > values[j + 1]){ swap = values[j]; swapPnt = list[j]; values[j] = values[j + 1]; list[j] = list[j + 1]; values[j + 1] = swap; list[j + 1] = swapPnt; } } } std::cout << "List 5: " << list[5]->evaluate() << std::endl; } void GeneticAlgorithim::record(std::vector<GeneticAlgorithim *> &list, DataTracker &tracker) { double average = 0; for(int i = 0; i < list.size(); i++){ average += list[i]->evaluate(); } average /= list.size(); tracker.addAverage(average); //std::cout<< list[5]->evaluate() <<std::endl; if(list[5]->evaluate() > tracker.getBest()){ tracker.setBest(list[5]->getContents(), list[5]->evaluate()); } } std::vector<char> GeneticAlgorithim::getContents() { return this->contents; } GeneticAlgorithim* GeneticAlgorithim::crossover(std::vector<GeneticAlgorithim*> container, std::mt19937 &rnd) { std::uniform_int_distribution<int> gen(3, 5); std::uniform_int_distribution<int> dist(1, 29); std::vector<char> sequence; int rand1, rand2; rand1 = gen(rnd); rand2 = gen(rnd); int splitPoint; splitPoint = dist(rnd); for(int i = 0; i < splitPoint; i++){ sequence.push_back(container[rand1]->getCharAt(i)); } for(int i = splitPoint; i < 30; i++){ sequence.push_back(container[rand2]->getCharAt(i)); } GeneticAlgorithim* newString = new GeneticAlgorithim(sequence); return newString; } void GeneticAlgorithim::mutate(std::mt19937 &rnd) { std::uniform_int_distribution<int> dice(1, 20); for(int i = 0; i < 30; i++){ if(dice(rnd) == 1){ if (i == 0 || i == 3 || i == 6 || i == 9 || i == 11 || i == 14 || i == 17 || i == 21 || i == 25 || i == 28) { this->contents[i] = GeneticAlgorithim::generateRandSign(rnd); } else if (i == 1 || i == 4 || i == 7 || i == 10 || i == 12 || i == 15 || i == 18 || i == 22 || i == 26 || i == 29) { this->contents[i] = GeneticAlgorithim::generateRandInt(rnd); } else if (i == 2 || i == 8 || i == 16 || i == 27) { this->contents[i] = GeneticAlgorithim::generateRandVariable(rnd); } else if (i == 5 || i == 13 || i == 19 || i == 23) { this->contents[i] = GeneticAlgorithim::generateRandOperator(rnd); } else if (i == 24) { this->contents[i] = GeneticAlgorithim::generateRandTrig(rnd); } else if (i == 20) { this->contents[i] = 'e'; } } } }
TypeScript
UTF-8
648
2.9375
3
[ "MIT" ]
permissive
import { get } from "lodash-es"; import { normalizeDataLocationToDotNotation } from "./location"; /** * The target is in an array */ export function isInArray(data: unknown, dataLocation: string): boolean { const dataLocationAsDotNotation: string = normalizeDataLocationToDotNotation( dataLocation ); const dataLocationSegments: string[] = dataLocationAsDotNotation.split("."); const parentDataLocation: string = dataLocationSegments.slice(0, -1).join("."); return ( !isNaN(parseInt(dataLocationSegments[dataLocationSegments.length - 1], 10)) && Array.isArray(get(data, parentDataLocation)) ); }
Markdown
UTF-8
1,643
2.796875
3
[]
no_license
--- layout: page type: text title: No Balls categories: - picture --- It's fair to say I've been more frustrated than a teenage boy (no understatement) with the looooooong halt on my photography. Which is why I made a decision to try to [get back into drawing](http://www.flickr.com/photos/i-5-m/5505513095/in/photostream), so I was at least doing something creative (I want - and feel it is important - to have both creative and technical interests, even if I don't achieve it). I had hoped by making a (somewhat) public statement of my intentions it would coerce me to follow through. But it seems [I have no balls](http://www.43folders.com/2008/12/01/courageous-sucking). It's weird because I have no problems being crap at programming. It doesn't bother me that I'm late to the game, unlikely to ever catch peers up or am totally outclassed by those younger than me. I'm think I'm happy with my abilities because I can satisfy myself: I can have a problem, no idea how to programme it, but be confident that I'll be able to figure it out eventually. Even if I don't do the best way. With drawing it's different, but I'm not exactly sure why though. Probably a combination of having regressed so much from what I was capable of years ago (I was never ace at it as a kid, but as per what I've said for programming, I was able to satisfy myself) and so I find my current abilities hugely frustrating; And having two daugthers who can out draw me (and one's not even at primary school yet) which makes me feel embarrassed when I attempt anything. So, until I grow a pair, back to the waiting game it is for me.
Java
UTF-8
40,530
2
2
[]
no_license
package com.mi.game.module.pet; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import com.mi.core.dao.KeyGeneratorDAO; import com.mi.core.engine.IOMessage; import com.mi.core.engine.ModuleManager; import com.mi.core.engine.TemplateManager; import com.mi.core.engine.annotation.Module; import com.mi.core.pojo.KeyGenerator; import com.mi.game.defines.ErrorIds; import com.mi.game.defines.KindIDs; import com.mi.game.defines.ModuleNames; import com.mi.game.defines.PetSkillLearnCode; import com.mi.game.defines.SysConstants; import com.mi.game.module.analyse.AnalyseModule; import com.mi.game.module.bag.data.BagData; import com.mi.game.module.base.BaseModule; import com.mi.game.module.pet.dao.PetDAO; import com.mi.game.module.pet.data.PetData; import com.mi.game.module.pet.data.PetLevelupData; import com.mi.game.module.pet.data.PetLockSkillData; import com.mi.game.module.pet.data.PetRankupData; import com.mi.game.module.pet.data.PetShardData; import com.mi.game.module.pet.data.PetSkillData; import com.mi.game.module.pet.data.PetSpecialSkillData; import com.mi.game.module.pet.data.PetTalentData; import com.mi.game.module.pet.pojo.Pet; import com.mi.game.module.pet.pojo.PetEntity; import com.mi.game.module.pet.pojo.PetShard; import com.mi.game.module.pet.pojo.PetSkill; import com.mi.game.module.pet.protocol.PetInfoProtocol; import com.mi.game.module.reward.RewardModule; import com.mi.game.module.reward.data.GoodsBean; import com.mi.game.util.Utilities; /** * @author 宋雷 宠物模块 2015年3月27日 下午4:46:07 */ @Module(name = ModuleNames.PetModule, clazz = PetModule.class) public class PetModule extends BaseModule { private PetDAO petDAO = PetDAO.getInstance(); private KeyGeneratorDAO keyGeneratorDAO = KeyGeneratorDAO.getInstance(); private final Map<Integer, Integer> expListData = new HashMap<Integer, Integer>(); private final Map<Integer, PetRankupData> rankupListData = new HashMap<Integer, PetRankupData>(); private final Map<Integer, Map<Integer, Integer>> petLockSkillData = new HashMap<Integer, Map<Integer, Integer>>(); @Override public void init() { initPetID(); initExpData(); initRankupData(); initPetLockSkillData(); } private void initExpData() { List<PetLevelupData> expList = TemplateManager.getTemplateList(PetLevelupData.class); for (PetLevelupData data : expList) { int exp = data.getExp(); int level = data.getLevel(); expListData.put(level, exp); } } private void initRankupData() { List<PetRankupData> expList = TemplateManager.getTemplateList(PetRankupData.class); for (PetRankupData data : expList) { int level = data.getLevel(); rankupListData.put(level, data); } } private void initPetLockSkillData(){ List<PetLockSkillData> petLockSkillList = TemplateManager.getTemplateList(PetLockSkillData.class); for (PetLockSkillData data : petLockSkillList) { int lock = data.getLocks(); Map<Integer, Integer> priceMap = data.getPrice(); petLockSkillData.put(lock, priceMap); } } /** * 保存宠物实体 * */ public void saveEntity(PetEntity petEntity) { this.petDAO.save(petEntity); } /** * 获取宠物实体 * */ public PetEntity getEntity(String playerID) { PetEntity petEntity = this.petDAO.getEntity(playerID); if (petEntity == null) { petEntity = this.initEntity(playerID); this.saveEntity(petEntity); } return petEntity; } public PetEntity getEntity(String playerID,IOMessage ioMessage) { PetEntity petEntity = null; if(ioMessage != null){ String key = PetEntity.class.getName(); petEntity = (PetEntity) ioMessage.getInputParse().get(key); if(petEntity == null){ petEntity = this.getEntity(playerID); ioMessage.getInputParse().put(key, petEntity); } }else{ petEntity = this.getEntity(playerID); } return petEntity; } /** * 初始化宠物ID * */ private void initPetID() { String clsName = SysConstants.petIDEntity; KeyGenerator keyGenerator = keyGeneratorDAO.getEntity(clsName); if (keyGenerator == null) { keyGenerator = new KeyGenerator(); keyGenerator.setKey(clsName); keyGenerator.setNextId(SysConstants.petStatID); keyGeneratorDAO.save(keyGenerator); } } /** * 获取宠物唯一ID * */ private long getPetID() { String clsName = SysConstants.petIDEntity; long petID = keyGeneratorDAO.updateInc(clsName); return petID; } /** * 初始化宠物实体 * */ public PetEntity initEntity(String playerID) { Map<Long, Pet> petMap = new HashMap<Long, Pet>(); Map<Integer, PetShard> shardMap = this.initPetShard(); PetEntity petEntity = new PetEntity(); petEntity.setPetMap(petMap); petEntity.setShardMap(shardMap); petEntity.setKey(playerID); return petEntity; } /** * 初始化宠物碎片 * */ private Map<Integer, PetShard> initPetShard() { List<PetShardData> shardDataList = TemplateManager.getTemplateList(PetShardData.class); Map<Integer, PetShard> shardList = new HashMap<Integer, PetShard>(); for (PetShardData data : shardDataList) { PetShard shard = new PetShard(); shard.setShardID(data.getPid()); shard.setNum(0); shardList.put(data.getPid(), shard); } return shardList; } /** * 初始化宠物 * */ private Pet initPet(PetData petData) { Pet pet = new Pet(); int skillSlots = petData.getSkillSlots(); int pid = petData.getPid(); List<PetSkill> skillList = this.initSkillList(skillSlots); int skillPoint = petData.getInitialPrint(); int specialSkillID = petData.getPetSpecialSkillID(); pet.setSkillList(skillList); pet.setSkillPoint(skillPoint); pet.setSpecialSkillID(specialSkillID); pet.setTemplateID(pid); pet.setPetID(this.getPetID()); pet.setResetPoint(skillPoint); return pet; } /** * 初始化宠物技能列表 * */ private List<PetSkill> initSkillList(int skillLimit) { List<PetSkill> skillList = new ArrayList<PetSkill>(); for (int i = 1; i <= skillLimit; i++) { PetSkill petSkill = new PetSkill(); petSkill.setPostion(i); petSkill.setSellLock(true); skillList.add(petSkill); } return skillList; } /** * 保存宠物碎片 * @param playerID * @param pid * @param num * @param isSave * @param ioMessage * @return */ public void addPetShard(String playerID,List<PetShard> petShardList, int pid, int num, boolean isSave, IOMessage ioMessage) { PetEntity entity = this.getEntity(playerID, ioMessage); Map<Integer, PetShard> list = entity.getShardMap(); PetShard shard = list.get(pid); if (shard == null) { shard = new PetShard(); shard.setShardID(pid); shard.setNum(num); list.put(pid, shard); } else { shard.setNum(shard.getNum() + num); } if (isSave) { this.saveEntity(entity); } boolean flag=false; for(PetShard petShard:petShardList){ if(petShard.getShardID()==pid){ petShard.setNum(petShard.getNum()+num); flag=true; } } if(!flag){ petShardList.add(shard); } } /** * 宠物进阶 * */ public void petAdvanced(String playerID, long petID,int shardID, PetInfoProtocol protocol) { PetEntity petEntity = this.getEntity(playerID); Map<Integer, PetShard> shardMap = petEntity.getShardMap(); PetShard petShard = shardMap.get(shardID); if (petShard == null) { logger.error("碎片不存在"); protocol.setCode(ErrorIds.PetShardNotFound); return; } PetShardData data = TemplateManager.getTemplateData(shardID, PetShardData.class); Map<Long, Pet> petMap = petEntity.getPetMap(); Pet pet = petMap.get(petID);//需要进阶的宠物 int targetID = data.getTargetID(); if (targetID!=pet.getTemplateID()) { logger.error("进阶宠物与宠物碎片不是同一种"); protocol.setCode(ErrorIds.PET_IS_SHARD); return; } if(pet.getRank()==rankupListData.size()){ logger.error("已达到最高阶"); protocol.setCode(ErrorIds.PET_IS_MAXADV); return; } PetRankupData petRankupData=rankupListData.get(pet.getRank()+1); int composeNum=petRankupData.getExp(); int nowNum = petShard.getNum() - composeNum; if (nowNum < 0) { logger.error("碎片不足"); protocol.setCode(ErrorIds.PetSHardNotEnough); return; } petShard.setNum(nowNum); pet.setSkillPoint(pet.getSkillPoint()+petRankupData.getEarnSkill()); pet.setResetPoint(pet.getResetPoint()+petRankupData.getEarnSkill()); pet.setRank(pet.getRank()+1); openPetTalent(pet);//开启宠物天赋技能 protocol.setPet(pet); protocol.setPetShard(petShard); this.saveEntity(petEntity); } /** * 宠物进阶、采用递归、只要碎片足够,可多次进阶 * @param pet * @param petShard */ // private void petAdvanced(Pet pet,PetShard petShard){ // int composeNum=rankupListData.get(pet.getRank()+1); // int nowNum = petShard.getNum() - composeNum; // if(nowNum>=0){ // petShard.setNum(nowNum); // pet.setRank(pet.getRank()+1); // openPetTalent(pet);//开启宠物天赋技能 // petAdvanced(pet,petShard); // } // } /** * 宠物碎片兑换 * */ public void compoundPet(String playerID, int shardID, IOMessage ioMessage, PetInfoProtocol protocol) { PetEntity petEntity = this.getEntity(playerID); Map<Integer, PetShard> shardMap = petEntity.getShardMap(); PetShard petShard = shardMap.get(shardID); if (petShard == null) { logger.error("碎片不存在"); protocol.setCode(ErrorIds.PetShardNotFound); return; } PetShardData data = TemplateManager.getTemplateData(shardID, PetShardData.class); int composeNum = data.getComposeNum(); Map<Long, Pet> petMap = petEntity.getPetMap(); int nowNum = petShard.getNum() - composeNum; if (nowNum < 0) { logger.error("碎片不足"); protocol.setCode(ErrorIds.PetSHardNotEnough); return; } int targetID = data.getTargetID(); for (Entry<Long, Pet> entry : petMap.entrySet()) { Pet tempPet = entry.getValue(); if (targetID==tempPet.getTemplateID()) { logger.error("宠物已存在"); protocol.setCode(ErrorIds.PETEXIST); return; } } petShard.setNum(nowNum); PetData petData = TemplateManager.getTemplateData(targetID, PetData.class); Pet pet = this.initPet(petData); long petID = pet.getPetID(); petMap.put(petID, pet); protocol.setPet(pet); protocol.setPetShard(petShard); this.saveEntity(petEntity); } /** * 宠物出战 * */ public void petWork(String playerID, long petID, PetInfoProtocol protocol) { PetEntity petEntity = this.getEntity(playerID); Map<Long, Pet> petMap = petEntity.getPetMap(); Pet pet = petMap.get(petID); if (pet == null) { logger.error("宠物未找到"); protocol.setCode(ErrorIds.PetNotFound); return; } if (pet.isWorked()) { logger.error("宠物已出战"); protocol.setCode(ErrorIds.PetWorked); return; } long nowTime = System.currentTimeMillis(); for (Entry<Long, Pet> entry : petMap.entrySet()) { Pet tempPet = entry.getValue(); if (tempPet.isWorked()) { tempPet.setWorked(false); protocol.setUnWorkPet(tempPet.getPetID()); } } if(pet.getSpecialSkillTime()==0){ pet.setSpecialSkillTime(nowTime); } pet.setWorked(true); this.saveEntity(petEntity); protocol.setSpecialSkillTime(pet.getSpecialSkillTime()); protocol.setWorkPet(pet.getPetID()); } /*** * 出战的宠物的定时经验计算、每10秒获得一次经验 */ public Pet petTimeExp(String playerID) { PetEntity petEntity=this.getEntity(playerID); Map<Long, Pet> petMap = petEntity.getPetMap(); for (Entry<Long, Pet> entry : petMap.entrySet()) { Pet tempPet = entry.getValue(); if (tempPet.isWorked()) { if(!petIsMaxExp(tempPet)){ long expTime=tempPet.getExpTime(); if(expTime==0){ addPetExp(tempPet,1); tempPet.setExpTime(System.currentTimeMillis()/1000); }else{ if((System.currentTimeMillis()/1000-expTime)>=10){ int exp=(int) ((System.currentTimeMillis()/1000-expTime)/10); addPetExp(tempPet,exp); tempPet.setExpTime(System.currentTimeMillis()/1000); }else{ return null; } } this.saveEntity(petEntity); return tempPet; } } } return null; } /** * 宠物喂养 * @param playerID * @param useType * @param petID * @param goodsList * @param protocol * @param ioMessage */ public void feedPet(String playerID,int useType,long petID,List<GoodsBean> goodsList,PetInfoProtocol protocol,IOMessage ioMessage){ PetEntity petEntity = this.getEntity(playerID); Map<Long, Pet> petMap = petEntity.getPetMap(); Pet pet = petMap.get(petID); if (pet == null) { logger.error("宠物未找到"); protocol.setCode(ErrorIds.PetNotFound); return; } if(petIsMaxExp(pet)){ logger.error("宠物已满级"); protocol.setCode(ErrorIds.PET_EXP_EMP); return; } Map<String,GoodsBean> showMap = new HashMap<>(); Map<String, Object> itemMap = new HashMap<String, Object>(); RewardModule rewardModule = ModuleManager.getModule(ModuleNames.RewardModule,RewardModule.class); int exp=0; if(useType==0){ rewardModule.useGoods(playerID, goodsList, 0, true, showMap, itemMap, ioMessage); for(GoodsBean goodsBean:goodsList){ BagData bagData = (BagData) TemplateManager.getTemplateData(goodsBean.getPid()); Map<Integer, Integer> useFunc = bagData.getUseFunc(); for (Entry<Integer, Integer> entry : useFunc.entrySet()) { int value = entry.getValue(); exp+=value*goodsBean.getNum(); } } }else{ //如果宠物没有满级,判断满级需要的经验 long needExp=petNeedExpMax(pet); for(GoodsBean goodsBean:goodsList){ int maxExp=0; BagData bagData = (BagData) TemplateManager.getTemplateData(goodsBean.getPid()); Map<Integer, Integer> useFunc = bagData.getUseFunc(); int value=0; for (Entry<Integer, Integer> entry : useFunc.entrySet()) { value = entry.getValue(); maxExp+=value*goodsBean.getNum(); } List<GoodsBean> newGoodsList=new ArrayList<GoodsBean>(); if(maxExp>=needExp){ int needNum=0; if((needExp%value)==0){ needNum=(int) (needExp/value);//需要的数量 }else{ needNum=(int) (needExp/value+1);//需要的数量 } GoodsBean needGoodsBean=new GoodsBean(goodsBean.getPid(),needNum); newGoodsList.add(needGoodsBean); rewardModule.useGoods(playerID, newGoodsList, 0, true, showMap, itemMap, ioMessage); exp+=needNum*value; break; }else{ newGoodsList.add(goodsBean); rewardModule.useGoods(playerID, newGoodsList, 0, true, showMap, itemMap, ioMessage); needExp-=maxExp; exp+=maxExp; } } } this.addPetExp(pet, exp); this.saveEntity(petEntity); protocol.setItemMap(itemMap); protocol.setPet(pet); } public boolean isPetMaxExp(String playerID,long petID,PetInfoProtocol protocol){ PetEntity petEntity = this.getEntity(playerID); Map<Long, Pet> petMap = petEntity.getPetMap(); Pet pet = petMap.get(petID); if (pet == null) { logger.error("宠物未找到"); protocol.setCode(ErrorIds.PetNotFound); throw new IllegalArgumentException(ErrorIds.PetNotFound + ""); } if(petIsMaxExp(pet)){ protocol.setCode(ErrorIds.PET_EXP_EMP); return true; } return false; } /** * 宠物满级需要的经验 * @param pet * @return */ private long petNeedExpMax(Pet pet){ long exp=0; long nowExp = pet.getExp(); int allExp=exp(pet); long needExp=allExp-nowExp;//升级到下一级需要用到的经验 int max=expListData.size();//最大级数 exp+=needExp; for(int i=pet.getLevel()+1;i<=max;i++){ exp+=expListData.get(i); } return exp; } /** * 增加宠物经验 * * */ private int addPetExp(Pet pet, long exp){ long nowExp = pet.getExp(); int allExp=exp(pet); long needExp=allExp-nowExp;//升级到下一级需要用到的经验 int max=expListData.size();//最大级数 if(exp>=needExp){ if(pet.getLevel()<max){ pet.setLevel(pet.getLevel()+1); pet.setExp(allExp); pet.setSkillPoint(pet.getSkillPoint()+1); pet.setResetPoint(pet.getResetPoint()+1); addPetExp(pet,exp-needExp); }else{ pet.setExp(allExp); return 0; } }else{ pet.setExp(nowExp+exp); } return allExp; } /** * 计算宠物从一级到现在级数的所有经验值 * @param pet * @return */ private int exp(Pet pet){ int exp=0; for(int i=1;i<=pet.getLevel();i++){ int needExp=expListData.get(i);//升级到下一级需要用到的经验 exp+=needExp; } return exp; } /** * 开启宠物的天赋属性,领悟技能时调用该方法 * @param pet */ private void openPetTalentToSkill(Pet pet,PetSkill petSkill,List<PetSkill> petSkillList){ PetData petData = TemplateManager.getTemplateData(pet.getTemplateID(), PetData.class); Map<Integer,Integer> map=petData.getPetTalent(); boolean flag=false; for (Entry<Integer, Integer> entry : map.entrySet()) { PetTalentData petTalentData = TemplateManager.getTemplateData(entry.getKey(), PetTalentData.class); if(petTalentData.getSkillReq()==petSkill.getSkillID()){//判断该技能是否是开启该宠物天赋技能的普通技能 int index=map.get(entry.getKey());//开启宠物的天赋属性需要的阶数 if(pet.getRank()>=index){//判断是否到开启天赋技能的级数 List<PetSkill> skillList=pet.getSkillList(); pet.setTalentNum(pet.getTalentNum()+petTalentData.getAddition()); flag=true; for(PetSkill skill:skillList){ if(skill.getSkillID()!=0 && skill.getSkillID() != petSkill.getSkillID()){ PetSkillData petSkillData = TemplateManager.getTemplateData(skill.getSkillID(), PetSkillData.class); Map<Integer,Integer> petSkillDataMap=petSkillData.getIntensify(); skill.setLevel(skill.getLevel()+petTalentData.getAddition());//技能等级+1 skill.setLevelNum(skill.getLevelNum()+petTalentData.getAddition()); addPrototype(skill,petSkillDataMap);//技能属性增加 petSkillList.add(skill); }else if(skill.getSkillID()!=0 && skill.getSkillID() == petSkill.getSkillID()){ PetSkillData petSkillData = TemplateManager.getTemplateData(skill.getSkillID(), PetSkillData.class); Map<Integer,Integer> petSkillDataMap=petSkillData.getIntensify(); for(int i=1;i<=pet.getTalentNum();i++){ skill.setLevel(skill.getLevel()+1);//技能等级+1 skill.setLevelNum(skill.getLevelNum()+1); addPrototype(skill,petSkillDataMap);//技能属性增加 } petSkillList.add(skill); } } } } } if(!flag){//如果不是开启该宠物天赋技能的普通技能,那么将该技能升级到已经开启了天赋技能的次数 if(pet.getTalentNum() > 0){ PetSkillData petSkillData = TemplateManager.getTemplateData(petSkill.getSkillID(), PetSkillData.class); Map<Integer,Integer> petSkillDataMap=petSkillData.getIntensify(); for(int i=1;i<=pet.getTalentNum();i++){ petSkill.setLevel(petSkill.getLevel()+1);//技能等级+1 petSkill.setLevelNum(petSkill.getLevelNum()+1); addPrototype(petSkill,petSkillDataMap);//技能属性增加 } petSkillList.add(petSkill); } } } /** * 开启宠物的天赋属性,宠物进阶时调用该方法 * @param pet */ private void openPetTalent(Pet pet){ PetData petData = TemplateManager.getTemplateData(pet.getTemplateID(), PetData.class); Map<Integer,Integer> map=petData.getPetTalent();//获取宠物的所有天赋技能 for (Entry<Integer, Integer> entry : map.entrySet()) { if(pet.getRank()==entry.getValue()){//判断是否达到开启天赋技能的阶段 PetTalentData petTalentData = TemplateManager.getTemplateData(entry.getKey(), PetTalentData.class); for(PetSkill skill:pet.getSkillList()){ if(skill.getSkillID()!=0&&skill.getSkillID()==petTalentData.getSkillReq()){ pet.setTalentNum(pet.getTalentNum()+petTalentData.getAddition()); for(PetSkill skill1:pet.getSkillList()){ if(skill1.getSkillID()!=0){ PetSkillData petSkillData = TemplateManager.getTemplateData(skill1.getSkillID(), PetSkillData.class); Map<Integer,Integer> petSkillDataMap=petSkillData.getIntensify(); skill1.setLevel(skill1.getLevel()+petTalentData.getAddition());//技能等级+1 addPrototype(skill1,petSkillDataMap);//技能属性增加 } } } } } } } /** * 传承 * */ public void eatPet(String playerID, long petID, long eatID, PetInfoProtocol protocol) { PetEntity petEntity = this.getEntity(playerID); Map<Long, Pet> petMap = petEntity.getPetMap(); if (petID == eatID) { logger.error("不可吞噬自身"); protocol.setCode(ErrorIds.NoEatSelf); return; } Pet pet = petMap.get(petID); if (pet == null) { logger.error("宠物未找到"); protocol.setCode(ErrorIds.PetNotFound); return; } Pet eatPet = petMap.get(eatID); if (eatPet == null) { logger.error("宠物未找到"); protocol.setCode(ErrorIds.PetNotFound); return; } if(pet.getLevel()>eatPet.getLevel()){ logger.error("被传承宠物不能比传承宠物等级高"); protocol.setCode(ErrorIds.PET_EAT_EMP); return; } if(petIsMaxExp(pet)){ logger.error("宠物已满级"); protocol.setCode(ErrorIds.PET_EXP_EMP); return; } Map<String, Object> itemMap = new HashMap<String, Object>(); RewardModule rewardModule = ModuleManager.getModule(ModuleNames.RewardModule, RewardModule.class); int gold=eatPet.getLevel()*5; int code=rewardModule.useGoods(playerID, KindIDs.GOLDTYPE, gold, 0, true, null, itemMap, null); if(code!=0){ protocol.setCode(code); return; } // //// // // 元宝消耗记录 // /// AnalyseModule analyseModule = ModuleManager.getModule(ModuleNames.AnalyseModule, AnalyseModule.class); analyseModule.goldCostLog(playerID, gold, 1, gold, "eatPet", "pet"); PetData petData= TemplateManager.getTemplateData(eatPet.getTemplateID(),PetData.class); long eatExp = eatPet.getExp(); this.addPetExp(pet, eatExp); Pet initPet=this.initPet(petData); initPet.setPetID(eatID); initPet.setWorked(eatPet.isWorked()); petMap.put(eatID, initPet);//将吞吃的宠物初始化状态 this.saveEntity(petEntity); Map<String,Pet> petHashMap=new HashMap<String,Pet>(); petHashMap.put(String.valueOf(petID), petMap.get(petID)); petHashMap.put(String.valueOf(eatID), petMap.get(eatID)); protocol.setItemMap(itemMap); protocol.setPetMap(petHashMap); } private boolean petIsMaxExp(Pet pet){ //1.判断宠物是否满级 int max=expListData.size();//最大级数 if(pet.getLevel()==max){ int allExp=exp(pet); //2.判断宠物经验是否满 if(pet.getExp()==allExp){ return true; } } return false; } /** * 获取可激活的技能 * @param pet * @return */ private List<PetSkillData> canLearnPetSkill(Pet pet){ List<PetSkillData> skillDataList = TemplateManager.getTemplateList(PetSkillData.class); List<PetSkillData> canLearnSkillDataList=new ArrayList<PetSkillData>(); List<PetSkill> skillList=pet.getSkillList(); if(skillDataList!=null&&skillDataList.size()>0){ for(int i=0;i<skillDataList.size();i++){ PetSkillData petSkillData=skillDataList.get(i); boolean flag=false; PetData petData=TemplateManager.getTemplateData(pet.getTemplateID(), PetData.class); if(petSkillData.getQuality()<=petData.getSkillQuality()){ if(skillList!=null){ for(int j=0;j<skillList.size();j++){ PetSkill petSkill=skillList.get(j); if(petSkillData.getPid()==petSkill.getSkillID()){ flag=true; break; } } } if(!flag){ canLearnSkillDataList.add(petSkillData); } } } } return canLearnSkillDataList; } public int getRandomList(List<Integer> list) { int random = Utilities.getRandomInt(list.size()); int index=list.get(random);//随机获取技能 return index; } /** * 领悟技能 * @param playerID * @param petID * @param protocol */ public void learnSkill(String playerID, long petID, PetInfoProtocol protocol) { PetEntity petEntity = this.getEntity(playerID); Map<Long, Pet> petMap = petEntity.getPetMap(); Pet pet = petMap.get(petID); if (pet == null) { logger.error("宠物未找到"); protocol.setCode(ErrorIds.PetNotFound); return; } int skillPoint = pet.getSkillPoint(); if (skillPoint < 1) { logger.error("技能点数不够"); protocol.setCode(ErrorIds.PetSkillPointNotEnough); return; } int templateID = pet.getTemplateID(); PetData petData = TemplateManager.getTemplateData(templateID, PetData.class); int skillLevelLimit = petData.getSkillLimit()+pet.getTalentNum();//技能最大等级 List<PetSkill> skillList = pet.getSkillList();//技能集合 int state = PetSkillLearnCode.failed; int isLock=isLockPetSkill(skillList);//判断解锁几个技能栏 int isLearnSkill=isLearnSkill(skillList);//判断学了几个技能 int isCanlevelUp=countMaxSkillLev(skillList,skillLevelLimit);//可升级的个数 //1:解锁技能栏 //2:学习技能 int random=0; List<PetSkillData> PetSkillDataList=canLearnPetSkill(pet); List<Integer> list=new ArrayList<Integer>(); if(isLock>0){//技能栏已经解锁 //判断是否已经学习了技能 if(isLearnSkill>0){ //3:技能栏满之后不用解锁 if(isLock>=skillList.size()){//技能栏全部解锁 if(isLearnSkill>=skillList.size()){//技能学满不用学习 //判断技能是否全部满级 if(isCanlevelUp==0){ protocol.setCode(ErrorIds.PET_KILL_EMP); return; }else{ list.add(2); list.add(3); } }else{ //判断学到的技能是否已经学满 if(isCanlevelUp!=0){ list.add(2); } list.add(1); list.add(3); } random=getRandomList(list); }else{ if(isLock>isLearnSkill){//技能栏有空余 if(isCanlevelUp==0){ list.add(0); list.add(1); list.add(3); random=getRandomList(list); }else{ random = Utilities.getRandomInt(4); } }else{ if(isCanlevelUp!=0){ list.add(2); } list.add(0); list.add(3); random=getRandomList(list); } } }else{ random = 1; } } switch (random) { case 0://解锁技能栏 state=unlockPetSkill(skillList,protocol); break; case 1://学习新的技能 if(PetSkillDataList!=null&&PetSkillDataList.size()>0){ for (PetSkill tempSkill : skillList) { if (tempSkill.getSkillID() == 0 && !tempSkill.isSellLock()) { int random1 = Utilities.getRandomInt(PetSkillDataList.size()); PetSkillData petSkillData=PetSkillDataList.get(random1);//随机获取技能 Map<Integer,Integer> petSkillDataMap=petSkillData.getProperty(); addPrototype(tempSkill,petSkillDataMap);//学习新的技能时,将新学到的技能的血、攻、防等属性值保存到数据库 tempSkill.setSkillID(petSkillData.getPid()); List<PetSkill> petSkillList=new ArrayList<PetSkill>(); openPetTalentToSkill(pet,tempSkill,petSkillList);//开启天赋技能 if(petSkillList.isEmpty()){ petSkillList.add(tempSkill); } protocol.setPetSkillList(petSkillList); state = PetSkillLearnCode.newSkill; break; } } } break; case 2://技能升级 List<PetSkill> petSkillList=new ArrayList<PetSkill>(); for (PetSkill tempSkill : skillList) { if (tempSkill.getSkillID() != 0 && !tempSkill.isSellLock()&&tempSkill.getLevel()<skillLevelLimit) { petSkillList.add(tempSkill);//哪些技能可以升级 } } if(petSkillList.size()>0){ int random2 = Utilities.getRandomInt(petSkillList.size());//随机获取技能 PetSkill petSkill=petSkillList.get(random2);//得到可升级的技能 petSkill.setLevel(petSkill.getLevel() + 1); state = PetSkillLearnCode.levelUp; /*技能升级时,攻、血、防等属性等重新赋值*/ PetSkillData petSkillData = TemplateManager.getTemplateData(petSkill.getSkillID(), PetSkillData.class); Map<Integer,Integer> petSkillDataMap=petSkillData.getIntensify(); addPrototype(petSkill,petSkillDataMap); //结束 List<PetSkill> newSkillList=new ArrayList<PetSkill>(); newSkillList.add(petSkill); protocol.setPetSkillList(newSkillList); break; } break; } protocol.setState(state); skillPoint -= 1; pet.setSkillPoint(skillPoint); protocol.setSkillPoint(skillPoint); protocol.setPetID(petID); this.saveEntity(petEntity); } /** * 解锁技能栏 * @param skillList * @param protocol * @return */ private int unlockPetSkill(List<PetSkill> skillList, PetInfoProtocol protocol){ int state=PetSkillLearnCode.failed; List<PetSkill> petSkillList=new ArrayList<PetSkill>(); for (PetSkill tempSkill : skillList) { if (tempSkill.isSellLock()) { tempSkill.setSellLock(false); petSkillList.add(tempSkill); protocol.setPetSkillList(petSkillList); state = PetSkillLearnCode.openSell; return state; } } return state; } /** * 判断技能栏是否解锁 * @param skillList * @return */ private int isLockPetSkill(List<PetSkill> skillList){ int num=0; for (PetSkill tempSkill : skillList) { if (!tempSkill.isSellLock()) { num++; } } return num; } /** * 学习了多少个技能 * @param skillList * @return */ private int isLearnSkill(List<PetSkill> skillList){ int num=0; for (PetSkill tempSkill : skillList) { if (tempSkill.getSkillID() != 0) { num++; } } return num; } private int countMaxSkillLev(List<PetSkill> skillList,int skillLevelLimit){ int num=0; for (PetSkill tempSkill : skillList) { if (tempSkill.getSkillID() != 0 && !tempSkill.isSellLock()&&tempSkill.getLevel()<skillLevelLimit) { num++; } } return num; } /** * 计算宠物的战斗力 * @param pet */ public double countCombat(String playerID){ PetEntity petEntity=getEntity(playerID); double combat=0; if(petEntity!=null){ Map<Long,Pet> petMap=petEntity.getPetMap(); for (Entry<Long, Pet> entry : petMap.entrySet()) { Pet tempPet = entry.getValue(); if (tempPet.isWorked()) { List<PetSkill> skillList=tempPet.getSkillList(); for(PetSkill petSkill:skillList){ if(petSkill.getSkillID()!=0){ combat+=petSkill.getAttack()+petSkill.getMdef()+petSkill.getPdef()+petSkill.getHp()*0.2; } } } } } return combat; } /*学习新技能时或升级技能时,增加攻、防、血等属性的值*/ private void addPrototype(PetSkill tempSkill,Map<Integer,Integer> petSkillDataMap){ for (Entry<Integer, Integer> entry : petSkillDataMap.entrySet()) { int key=entry.getKey(); int value = entry.getValue(); switch (key) { case SysConstants.Hp://生命 tempSkill.setHp(tempSkill.getHp()+value); break; case SysConstants.Attack://攻击 tempSkill.setAttack(tempSkill.getAttack()+value); break; case SysConstants.PDef://物防 tempSkill.setPdef(tempSkill.getPdef()+value); break; case SysConstants.MDef://魔防 tempSkill.setMdef(tempSkill.getMdef()+value); break; } } } /** * 锁定技能 * */ public void lockSkill(String playerID, long petID, int skillID, PetInfoProtocol protocol) { PetEntity petEntity = this.getEntity(playerID); Map<Long, Pet> petMap = petEntity.getPetMap(); Pet pet = petMap.get(petID); if (pet == null) { logger.error("宠物未找到"); protocol.setCode(ErrorIds.PetNotFound); return; } boolean isFind = false; int lockNum = 0; List<PetSkill> petSkills = pet.getSkillList(); PetSkill petSkill = null; /*判断技能锁定数量*/ for (PetSkill tempSkill : petSkills) { if (tempSkill.isSkillLock()) { lockNum += 1; } } /*锁定或解锁*/ for (PetSkill tempSkill : petSkills) { if (tempSkill.getSkillID() == skillID) { if (tempSkill.isSkillLock()) { tempSkill.setSkillLock(false); }else{ tempSkill.setSkillLock(true); PetData petData = TemplateManager.getTemplateData(pet.getTemplateID(), PetData.class); int maxLockNum=petData.getLockNum(); if(lockNum<maxLockNum){ Map<Integer,Integer> map=petLockSkillData.get(lockNum+1); int gold =map.get(KindIDs.GOLDTYPE); Map<String, Object> itemMap = new HashMap<String, Object>(); RewardModule rewardModule = ModuleManager.getModule(ModuleNames.RewardModule, RewardModule.class); int code=rewardModule.useGoods(playerID, KindIDs.GOLDTYPE, gold, 0, true, null, itemMap, null); if(code!=0){ protocol.setCode(code); return; } /*元宝消耗记录*/ AnalyseModule analyseModule = ModuleManager.getModule(ModuleNames.AnalyseModule, AnalyseModule.class); analyseModule.goldCostLog(playerID, gold, 1, gold, "lockSkill", "pet"); protocol.setItemMap(itemMap); }else{ logger.error("宠物技能锁定数量已满"); protocol.setCode(ErrorIds.PET_SKILL_LOCK_EMP); return; } } petSkill = tempSkill; isFind = true; } } if (!isFind) { logger.error("未找到宠物技能"); protocol.setCode(ErrorIds.PetSkillNotFound); return; } protocol.setPetSkill(petSkill); protocol.setPetID(petID); this.saveEntity(petEntity); } /** * 重置技能 * */ public void resetSkill(String playerID, long petID, PetInfoProtocol protocol) { PetEntity petEntity = this.getEntity(playerID); Map<Long, Pet> petMap = petEntity.getPetMap(); Pet pet = petMap.get(petID); if (pet == null) { logger.error("宠物未找到"); protocol.setCode(ErrorIds.PetNotFound); return; } int skillPoint = pet.getSkillPoint(); int resetPoint = pet.getResetPoint(); if (resetPoint == 0) { int templateID = pet.getTemplateID(); PetData petData = TemplateManager.getTemplateData(templateID, PetData.class); resetPoint = petData.getInitialPrint(); } if (resetPoint == skillPoint) { logger.error("不需要重置"); protocol.setCode(ErrorIds.NotResetPetSkill); return; } List<PetSkill> skillList = pet.getSkillList(); List<PetSkill> lockSkillList=new ArrayList<PetSkill>(); boolean flag=false; for (PetSkill petSkill : skillList) { if (!petSkill.isSkillLock()) { if (!petSkill.isSellLock()) { petSkill.setSellLock(true); petSkill.setSkillID(0); petSkill.setLevel(0); /*重置之后将攻、防、血等属性设置为0*/ petSkill.setPdef(0); petSkill.setAttack(0); petSkill.setHp(0); petSkill.setMdef(0); petSkill.setLevelNum(0); flag=true; } } else { if(petSkill.getSkillID()!=0){ lockSkillList.add(petSkill); } } } if(!lockSkillList.isEmpty()){ int num=countPatent(pet,lockSkillList); for(PetSkill petSkill : lockSkillList){ int skillLevel = petSkill.getLevel(); int count=petSkill.getLevelNum()-num; resetPoint -= skillLevel + 2 - petSkill.getLevelNum(); if(count>0){ PetSkillData petSkillData = TemplateManager.getTemplateData(petSkill.getSkillID(), PetSkillData.class); Map<Integer,Integer> petSkillDataMap=petSkillData.getIntensify(); deletePrototype(petSkill,petSkillDataMap,count); } petSkill.setLevelNum(num); petSkill.setLevel(petSkill.getLevel()-count); } pet.setTalentNum(num); }else{ pet.setTalentNum(0); } if(!flag){ logger.error("不需要重置"); protocol.setCode(ErrorIds.NotResetPetSkill); return; } if (resetPoint < 0) { logger.error("数据异常"); protocol.setCode(ErrorIds.ResetPointWrong); return; } Map<String, Object> itemMap = new HashMap<String, Object>(); RewardModule rewardModule = ModuleManager.getModule(ModuleNames.RewardModule, RewardModule.class); int code=rewardModule.useGoods(playerID, KindIDs.GOLDTYPE, SysConstants.resetPetSkillGold, 0, true, null, itemMap, null); if(code!=0){ protocol.setCode(code); return; } // //// // // 元宝消耗记录 // /// AnalyseModule analyseModule = ModuleManager.getModule(ModuleNames.AnalyseModule, AnalyseModule.class); analyseModule.goldCostLog(playerID, SysConstants.resetPetSkillGold, 1, SysConstants.resetPetSkillGold, "resetSkill", "pet"); pet.setSkillPoint(resetPoint); protocol.setPet(pet); protocol.setItemMap(itemMap); protocol.setPetID(petID); this.saveEntity(petEntity); } private void deletePrototype(PetSkill tempSkill,Map<Integer,Integer> petSkillDataMap,int num){ for (Entry<Integer, Integer> entry : petSkillDataMap.entrySet()) { int key=entry.getKey(); int value = entry.getValue()*num; switch (key) { case SysConstants.Hp://生命 tempSkill.setHp(tempSkill.getHp()-value); break; case SysConstants.Attack://攻击 tempSkill.setAttack(tempSkill.getAttack()-value); break; case SysConstants.PDef://物防 tempSkill.setPdef(tempSkill.getPdef()-value); break; case SysConstants.MDef://魔防 tempSkill.setMdef(tempSkill.getMdef()-value); break; } } } /** * 判断开启天赋技能的数量 * @param pet * @param lockSkillList * @return */ private int countPatent(Pet pet,List<PetSkill> lockSkillList){ int num=0; PetData petData = TemplateManager.getTemplateData(pet.getTemplateID(), PetData.class); Map<Integer,Integer> map=petData.getPetTalent(); for (Entry<Integer, Integer> entry : map.entrySet()) { PetTalentData petTalentData = TemplateManager.getTemplateData(entry.getKey(), PetTalentData.class); for(PetSkill petSkill:lockSkillList){ if(petTalentData.getSkillReq()==petSkill.getSkillID()){//判断该技能是否是开启该宠物天赋技能的普通技能 int index=map.get(entry.getKey());//开启宠物的天赋属性需要的阶数 if(pet.getRank()>=index){//判断是否到开启天赋技能的级数 num+=petTalentData.getAddition(); } } } } return num; } /** * 领取特殊奖励 * */ public void getSpecialReward(String playerID, long petID, PetInfoProtocol protocol, IOMessage ioMessage) { PetEntity petEntity = this.getEntity(playerID); Map<Long, Pet> petMap = petEntity.getPetMap(); Pet pet = petMap.get(petID); if (pet == null) { logger.error("宠物未找到"); protocol.setCode(ErrorIds.PetNotFound); return; } int templateID = pet.getTemplateID(); PetData petData = TemplateManager.getTemplateData(templateID, PetData.class); long lastGetTime = pet.getSpecialSkillTime(); long nowTime = System.currentTimeMillis(); int specialID = petData.getPetSpecialSkillID(); PetSpecialSkillData specialSkillData = TemplateManager.getTemplateData(specialID, PetSpecialSkillData.class); if (specialSkillData == null) { logger.error("不存在该技能"); protocol.setCode(ErrorIds.NoPetSpecialSkill); return; } List<GoodsBean> goodsList = specialSkillData.getRewardItem(); long rewardTime = specialSkillData.getRewardTime() * 1000; if (lastGetTime + rewardTime <= nowTime) { Map<String, Object> itemMap = new HashMap<String, Object>(); RewardModule rewardModule = ModuleManager.getModule(ModuleNames.RewardModule, RewardModule.class); rewardModule.addGoods(playerID, goodsList, true, null, itemMap, ioMessage); protocol.setItemMap(itemMap); protocol.setShowMap(goodsList); } else { logger.error("未到领取时间"); protocol.setCode(ErrorIds.ArrivalGetItemTime); return; } pet.setSpecialSkillTime(nowTime); protocol.setSpecialSkillTime(nowTime); protocol.setPetID(petID); this.saveEntity(petEntity); } }
Ruby
UTF-8
4,333
3.078125
3
[]
no_license
def g_maxitem 50 end def g_maxeq 30 end #==============================# # Title system # #==============================# def default_male_title_list [ { :level=>0, :name=>"新人" }, { :level=>5, :name=>"武者" }, { :level=>10, :name=>"少侠" }, { :level=>20, :name=>"侠客" } ] end def default_female_title_list [ { :level=>0, :name=>"新人" }, { :level=>5, :name=>"女武者" }, { :level=>10, :name=>"女少侠" }, { :level=>20, :name=>"女侠" } ] end def titleForLevel(level, gender) if gender == 0 list = default_female_title_list # elsif gender == 1 else list = default_male_title_list end p "===>update_title5 level=#{level}, gender=#{gender}, list=#{list.inspect}" for i in 0..list.size-1 if list[i][:level] >=level return list[i][:name] end end return "" end def title_from_skill(skill, level) t = nil case skill when "caoyao" if level < 5 t = "小药童" elsif level < 10 t = "药童" elsif level < 20 t = "初级药师" elsif level < 30 t = "药师" elsif level < 40 t = "名医" elsif level < 50 t = "大国医" elsif level < 80 t = "药王" else t = "医仙" end end return t end # # set first title # def setTitle1(c) # title = c.tmp[:title] # t = titleForLevel(c.tmp[:level], c.tmp[:sex]) # if title!= nil and title.size>0 # titles = title.split(" "), # if titles.size>1 and title2[1]!=nil and title2[1].size>0 # t += " "+ titles[1] # end # end # end #==============================# # LEVEL BOSS # #==============================# def levelBosses { "5" => [ "objects/npc/hero/yezhu" ], "10" => [ "objects/npc/hero/weizhangtianxin" ], "15" =>[ "objects/npc/hero/guiwuzhe" ], "20" =>[] } end # the level means user level must be >= level of all heroes whose level is less than users level. # for example: user level is 5, then all heroes whose level <5 should be passed. # if user levelup to 6, then he need to pass all heroes whose level < 6, yezhu here. def hero_list [ { :name=> "objects/npc/hero/yezhu", :level=>5, }, { :name=>"objects/npc/hero/weizhangtianxin", :level=>10, }, { :name=> "objects/npc/hero/yeren", :level=>15, }, { :name=> "objects/npc/hero/guiwuzhe", :level=>20, }, { :name=> "objects/npc/hero/lanfenghuang", :level=>25, }, { :name=> "objects/npc/hero/blackknight", :level=>30, }, { :name=> "objects/npc/hero/guiwuzhe", :level=>35, }, { :name=> "objects/npc/hero/guiwuzhe", :level=>40, }, { :name=> "objects/npc/hero/guiwuzhe", :level=>45, }, { :name=> "objects/npc/hero/guiwuzhe", :level=>50, } ] end # return 6, 11, 16, 21 ... def getNextStageLevel(level) if level==0 h_level = 5 else if level/5*5 == level h_level = level else h_level = (level+5)/5*5 end end return h_level+1 end def BossForLevel(level) h_level = getNextStageLevel(level) BossForLevelupTo(h_level) end # boss needed to pass when up level to n # e.g. 5->6, yezhu # 10->11, yezhu & weizhangtianxin def BossForLevelupTo(level) ar = [] hero_list.each {|h| if h[:level] < level ar.push h end } # lb = levelBosses[level.to_s] return ar end
Java
UTF-8
1,437
2.4375
2
[]
no_license
package mg.yvan.truth.manager; import android.content.SharedPreferences; import android.preference.PreferenceManager; import com.facebook.AccessToken; import mg.yvan.truth.TruthApplication; /** * Created by Yvan on 09/06/16. */ public class SessionManager { private final static String LAST_BOOK = "book"; private final static String LAST_CHAPTER = "chapter"; private static SessionManager singleInstance; public static SessionManager getInstance() { if (singleInstance == null) { singleInstance = new SessionManager(); } return singleInstance; } public boolean isLogged() { return AccessToken.getCurrentAccessToken() != null; } public void saveLastBookAndChapter(int bookId, int chapter) { SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(TruthApplication.getAppContext()).edit(); editor.putInt(LAST_BOOK, bookId); editor.putInt(LAST_CHAPTER, chapter); editor.apply(); } public int[] retrieveLastBookAndChapter() { SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(TruthApplication.getAppContext()); final int bookId = settings.getInt(LAST_BOOK, 0); final int chapter = settings.getInt(LAST_CHAPTER, 0); int[] result = new int[2]; result[0] = bookId; result[1] = chapter; return result; } }
Shell
UTF-8
275
3.265625
3
[]
no_license
#!/bin/bash EXT_ASIS=".wav" #EXT_ASIS=".WAV" EXT_TOBE=".mp3" files=( `ls *$EXT_ASIS` ) for file in "${files[@]}" do echo "asis: $file" echo "tobe: ${file/$EXT_ASIS/$EXT_TOBE}" ffmpeg -i $file -vn -ar 44100 -ac 9 -b:a 192k "${file/$EXT_ASIS/$EXT_TOBE}" done
JavaScript
UTF-8
3,230
4.1875
4
[]
no_license
// Assignment Code var passwordLength; // Displaying all character and number possibilities var Specialcharacters = ["!", "#", "$", "%", "&", "'", "(", ")", "*", "+", ",", "-", ".", "/", ":", ";", "<", "=", ">", "?", "@", "[", "^", "_", "`", "{", "|", "}", "~"]; var Numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; var upperCase = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]; var lowerCase = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]; // Variable for which specification they choose var allCharacters = []; var generateBtn = document.querySelector("#generate"); // Write password to the #password input function writePassword() { var password = generatePassword(); var passwordText = document.querySelector("#password"); passwordText.value = password; } var generatePassword = function() { // Ask the user how long they want the password to be passwordLength = prompt("How many characters long would you like your password to be? (Minimum 8, Maximum 128)"); alert (passwordLength); // Quits the prompt if a number isn't entered if (!passwordLength) { alert("Please enter a number to proceed"); return; } // Quits the prompt if a number from 8-128 isn't entered else if (passwordLength < 8 || passwordLength > 128 ) { alert("Please choose a number between 8 and 128"); return; } //Ask the user which criterias they would like to apply to their generated password var confirmSpecialcharacters = confirm("Would you like your password to contain special characters?"); var confirmNumbers = confirm("Would you like your password to contain numbers?"); var confirmuppercase = confirm("Would you like your password to contain uppercase letters?"); var confirmlowercase = confirm("Would you like your password to contain lowercase letters?"); // Alert the user if no option is chosen if (!confirmSpecialcharacters && !confirmNumbers && !confirmuppercase && !confirmlowercase) { alert("You need to choose at least one option"); return; } // Use concat to merge the two strings if (confirmSpecialcharacters === true) { // User wants special characters allCharacters = allCharacters.concat(Specialcharacters); } if (confirmNumbers === true) { // User wants Numbers allCharacters = allCharacters.concat(Numbers); } if (confirmuppercase === true) { // User wants Uppercase allCharacters = allCharacters.concat(upperCase); } if (confirmlowercase === true) { // User wants Lowercase allCharacters = allCharacters.concat(lowerCase); } // Declare a variable for an empty string to be filled with the users password criteria var randompw = ""; // Run a for loop to generate a password determined by the selected criteria for (let i = 0; i < passwordLength; i++) { randompw = randompw + allCharacters[Math.floor(Math.random() * allCharacters.length)]; } // Display the generated password in the text box return randompw; } // Add event listener to generate button generateBtn.addEventListener("click", writePassword);
C
UTF-8
7,416
2.828125
3
[]
no_license
/*====================================================================== Behaviour: Implementation of preemptive RIOS for the HC11 Runs 2 example programs: Sequence: Loops through a sequence of 3 outputs (Bit2 -> Bit1 -> Bit0) Toggle: Toggles an output (Bit0) on and off. Assumptions: Program is executed through the Buffalo Monitor and can access the Buffalo Monitor Interrupt Jump Table Program uses interrupts to its advantage. Pins: Program is designed to use the following I/O pins on the HC11: OUT: Sequence: PA6 -> State(Bit2) PA5 -> State(Bit1) PA4 -> State(Bit0) Toggle: PA7 -> State(Bit0) Assumptions: Program is executed through the Buffalo Monitor and can access the Buffalo Monitor Interrupt Jump Table Program uses interrupts to its advantage. Author: Matthew Hird Date: Mar 4 2020 ======================================================================*/ // HC11 Vector, Flag, & Port Access Points #define jump_table_toc2_opcode *(volatile unsigned char *)(0x00dc) #define jump_table_toc2_isr *(volatile short int *)(0x00dd) #define port_a *(volatile unsigned char *)(0x1000) #define tcnt *(volatile short int *)(0x100e) #define toc2 *(volatile short int *)(0x1018) #define tctl1 *(volatile unsigned char *)(0x1020) #define tmsk1 *(volatile unsigned char *)(0x1022) #define tflg1 *(volatile unsigned char *)(0x1023) #define pactl *(volatile unsigned char *)(0x1026) #define TIME_PER_INTERRUPT 20000 #define HC11_MILLISECOND 2000 #define TOC2_MS_PER_INTERRUPT 30 #define TOC2_INTERRUPT_TIME (TOC2_MS_PER_INTERRUPT * HC11_MILLISECOND) // HC11 Opcodes #define OPCODE_JMP_EXTENDED (0x7e) // OC2 Masks #define OC2_MASK (0x40) #define CLEAR_OC2_MASK (OC2_MASK) // Data Direction Bits #define DDRA3 (0x08) // PA3 #define DDRA7 (0x80) // PA7 // OUTPUT #define SEQ_TSK_OUT_BIT2 (0x40) // PA6 #define SEQ_TSK_OUT_BIT1 (0x20) // PA5 #define SEQ_TSK_OUT_BIT0 (0x10) // PA4 #define SEQ_TSK_OUT_MASK (SEQ_TSK_OUT_BIT2 | SEQ_TSK_OUT_BIT1 | SEQ_TSK_OUT_BIT0) #define SEQ_TSK_STATE_100 (SEQ_TSK_OUT_BIT2) #define SEQ_TSK_STATE_010 (SEQ_TSK_OUT_BIT1) #define SEQ_TSK_STATE_001 (SEQ_TSK_OUT_BIT0) #define TOG_TSK_OUT_BIT (0x80) // PA7 #define TOG_TSK_OUT_MASK (TOG_TSK_OUT_BIT) #define TOG_TSK_STATE_ON (TOG_TSK_OUT_BIT) #define TOG_TSK_STATE_OFF (0x00) #define NUMBER_OF_TASKS 2 #define TASK_PERIOD_GCD 20 // Timer tick rate in 10 ms #define TOGGLE_TSK_PERIOD 100 // in 10 ms #define SEQUENCE_TSK_PERIOD 20 // in 10 ms #define IDLE_TASK 255 // 0 highest priority, 255 lowest // Readability Constants #define TRUE 1 #define FALSE 0 typedef struct task { volatile unsigned short period; // Rate at which the task should tick volatile unsigned short elapsed_time; // Time since task's last tick volatile unsigned char state; volatile unsigned char is_running; unsigned char (*tick_func)(unsigned short cur_state); // Function to call for task's tick } task_t; volatile unsigned short toc2_interrupt_count = 0; volatile task_t tasks[NUMBER_OF_TASKS]; volatile unsigned char running_tasks[4] = { IDLE_TASK }; // Track running tasks-[0] always IDLE_TASK volatile unsigned char current_task_index = 0; // Index of highest priority task in running_tasks // Forward Declarations void init_tasks(void); unsigned short toggle_tsk_tick_func(unsigned short state); unsigned short sequence_tsk_tick_func(unsigned short state); void toc2_isr(void) __attribute__((interrupt)); unsigned char _start() { __asm__("sei"); volatile unsigned char i = 0; tasks[i].period = SEQUENCE_TSK_PERIOD; tasks[i].elapsed_time = SEQUENCE_TSK_PERIOD; tasks[i].state = SEQ_TSK_STATE_001; tasks[i].is_running = FALSE; tasks[i].tick_func = &sequence_tsk_tick_func; ++i; pactl |= DDRA7; tasks[i].period = TOGGLE_TSK_PERIOD; tasks[i].elapsed_time = TOGGLE_TSK_PERIOD; tasks[i].state = TOG_TSK_STATE_OFF; tasks[i].is_running = FALSE; tasks[i].tick_func = &toggle_tsk_tick_func; ++i; jump_table_toc2_opcode = OPCODE_JMP_EXTENDED; jump_table_toc2_isr = (short int *) toc2_isr; tmsk1 |= OC2_MASK; tflg1 |= CLEAR_OC2_MASK; toc2 = tcnt + TOC2_INTERRUPT_TIME; toc2_interrupt_count = TASK_PERIOD_GCD; __asm__("cli"); while(TRUE) {}; return 0; } // Task: Toggle an output unsigned short toggle_tsk_tick_func(unsigned short state) { switch(state) { case TOG_TSK_STATE_ON: state = TOG_TSK_STATE_OFF; break; case TOG_TSK_STATE_OFF: state = TOG_TSK_STATE_ON; break; default: state = TOG_TSK_STATE_OFF; break; } port_a = (port_a & (~TOG_TSK_OUT_MASK)) | state; return state; } // Task: Sequence a 1 across 3 outputs, high to low unsigned short sequence_tsk_tick_func(unsigned short state) { switch(state) { case SEQ_TSK_STATE_100: state = SEQ_TSK_STATE_010; break; case SEQ_TSK_STATE_010: state = SEQ_TSK_STATE_001; break; case SEQ_TSK_STATE_001: state = SEQ_TSK_STATE_100; break; default: state = SEQ_TSK_STATE_100; break; } port_a = (port_a & (~SEQ_TSK_OUT_MASK)) | state; return state; } // preemptive rios scheduler interrupt routine void toc2_isr(void) { volatile unsigned char i; volatile unsigned char is_tick = FALSE; if (toc2_interrupt_count < TASK_PERIOD_GCD) { ++toc2_interrupt_count; } else { is_tick = TRUE; toc2_interrupt_count = 0; } toc2 += TOC2_INTERRUPT_TIME; tflg1 |= CLEAR_OC2_MASK; __asm__("cli"); if (is_tick) { for (i=0; i < NUMBER_OF_TASKS; ++i) { // Heart of scheduler code if ( (tasks[i].elapsed_time >= tasks[i].period) // Task ready && (running_tasks[current_task_index] > i) // Task priority > current task priority && (!tasks[i].is_running) // Task not already running (no self-preemption) ) { __asm__("sei"); // Critical section tasks[i].elapsed_time = 0; // Reset time since last tick tasks[i].is_running = TRUE; // Mark as running current_task_index += 1; running_tasks[current_task_index] = i; // Add to running_tasks __asm__("cli"); tasks[i].state = tasks[i].tick_func(tasks[i].state); // Execute tick __asm__("sei"); // Critical section tasks[i].is_running = FALSE; running_tasks[current_task_index] = IDLE_TASK; // Remove from running_tasks current_task_index -= 1; __asm__("cli"); } tasks[i].elapsed_time += TASK_PERIOD_GCD; } } }
C#
UTF-8
809
3.390625
3
[]
no_license
namespace CsharpExam { //https://leetcode-cn.com/problems/xuan-zhuan-shu-zu-de-zui-xiao-shu-zi-lcof/ // 11 旋转数组里的最小数字 public class Offer_20220203_11 { public int MinArray(int[] numbers) { int left = 0, right = numbers.Length - 1; while (left < right) { int middle = (left + right) / 2; if (numbers[middle] > numbers[right]) { left = middle + 1; } else if (numbers[middle] < numbers[right]) { right = middle; } else { right -= 1; } } return numbers[left]; } } }
PHP
UTF-8
6,964
3
3
[]
no_license
<?php function consultarDepartamento($db,$numeroempleado){ $sql="select dept_name,dept_emp.dept_no,from_date,to_date from departments,dept_emp where dept_emp.dept_no=departments.dept_no and emp_no='$numeroempleado';"; $resultado=mysqli_query($db, $sql); $contador=mysqli_num_rows($resultado); echo "Trabajador ".$numeroempleado." "; nombreApellidosEmpleado($db,$numeroempleado); echo "<br>"; echo $contador. ' Resultados <br>'; echo "<table border='1'>"; echo "<th> Nombre Departamento</th><th>Codigo Departamento</th><th>Fecha Inicial</th><th>Fecha Final</th>"; echo '</tr>'; if (mysqli_num_rows($resultado) > 0) { while($row = mysqli_fetch_assoc($resultado)) { echo '<tr>'; echo "<td>". $row["dept_name"]."</td><td>".$row["dept_no"]."</td><td>".$row['from_date']."</td><td>".$row['to_date']."</td>"; echo '</tr>'; } echo '</table>'; echo '<br>'; } else { echo "0 results"; } } function nombreApellidosEmpleado($db,$numeroempleado){ $sql="select first_name,last_name from employees where emp_no='$numeroempleado';"; $resultado2=mysqli_query($db, $sql); $contador=mysqli_num_rows($resultado2); if (mysqli_num_rows($resultado2) > 0) { while($row = mysqli_fetch_assoc($resultado2)) { echo $row["first_name"]." ".$row["last_name"]; } } } function consultarSalario($db,$empleado){ $sql="select salary,salaries.from_date,salaries.to_date from salaries where emp_no='$empleado';"; $resultado=mysqli_query($db, $sql); $contador=mysqli_num_rows($resultado); echo "Trabajador ".$empleado." "; nombreApellidosEmpleado($db,$empleado); echo "<br>"; echo $contador. ' Resultados <br>'; echo "<table border='1'>"; echo "<th>Salario</th><th>Fecha Inicio</th><th>Fecha Final</th>"; echo '</tr>'; if (mysqli_num_rows($resultado) > 0) { while($row = mysqli_fetch_assoc($resultado)) { echo '<tr>'; echo "<td>". $row["salary"]."</td><td>".$row["from_date"]."</td><td>".$row['to_date']."</td>"; echo '</tr>'; } echo '</table>'; echo '<br>'; } else { echo "0 results"; } } function consultarCategoria($db,$empleado){ $sql="select title,from_date,to_date from titles where emp_no='$empleado';"; $resultado=mysqli_query($db, $sql); $contador=mysqli_num_rows($resultado); echo "Trabajador ".$empleado." "; nombreApellidosEmpleado($db,$empleado); echo "<br>"; echo $contador. ' Resultados <br>'; echo "<table border='1'>"; echo "<th>Categoria</th><th>Fecha Inicio</th><th>Fecha Final</th>"; echo '</tr>'; if (mysqli_num_rows($resultado) > 0) { while($row = mysqli_fetch_assoc($resultado)) { echo '<tr>'; echo "<td>". $row["title"]."</td><td>".$row["from_date"]."</td><td>".$row['to_date']."</td>"; echo '</tr>'; } echo '</table>'; echo '<br>'; } else { echo "0 results"; } } function cambiarDepartamento($db,$empleado,$departamento){ $sql="select dept_emp.dept_no from departments,dept_emp where dept_emp.dept_no=departments.dept_no and emp_no='$empleado' and to_date='9999-01-01';"; $aux=mysqli_query($db,$sql); $arrayid=mysqli_fetch_array($aux); $dept=$arrayid[0]; //echo $dept; //echo $departamento; if($departamento==$dept){ echo "<h3 style='color=red'>Ya Pertenece A Este Departamento.</h3>"; } else{ $sql2="update dept_emp set to_date=curdate() where to_date='9999-01-01' and emp_no='$empleado';"; if($sentencia=mysqli_query($db,$sql2)){ $sql3="insert into dept_emp(emp_no,dept_no,from_date,to_date) values ('$empleado','$departamento',curdate(),'9999-01-01');"; //var_dump($sql3); if($sentencia2=mysqli_query($db,$sql3)){ mysqli_commit($db); echo "<h3 style='color=green'> Trabajador ".$empleado." "; nombreApellidosEmpleado($db,$empleado); echo " ha cambiado de departamento con existo a ".$departamento." "; nombreDepartamento($db,$departamento); echo "</h3>"; } else{ echo "Ya ha pertenecido a este departamento y no puede volver <br>"; mysqli_rollback($db); } } else{ //echo "error1"; mysqli_rollback($db); } } } function nombreDepartamento($db,$departamento){ $sql="select dept_name from departments where dept_no='$departamento';"; $resultado2=mysqli_query($db, $sql); $contador=mysqli_num_rows($resultado2); if (mysqli_num_rows($resultado2) > 0) { while($row = mysqli_fetch_assoc($resultado2)) { echo $row["dept_name"]; } } } function CambiarSalario($db,$empleado,$salario){ $sql="select max(from_date) from salaries where emp_no='$empleado'"; $aux=mysqli_query($db,$sql); $arrayid=mysqli_fetch_array($aux); $fecha=$arrayid[0]; $sql2="select curdate()"; $aux2=mysqli_query($db,$sql2); $arrayid2=mysqli_fetch_array($aux2); $fechaactual=$arrayid2[0]; if($fecha==$fechaactual){ echo "No se puede Cambiar de Salario el mismo dia, Espera a mañana <br>"; } else{ $sql3="update salaries set to_date=curdate() where to_date='9999-01-01' and emp_no='$empleado';"; if($sentencia=mysqli_query($db,$sql3)){ $sql4="insert into salaries(emp_no,salary,from_date,to_date) values ('$empleado','$salario',curdate(),'9999-01-01');"; if($sentencia2=mysqli_query($db,$sql4)){ mysqli_commit($db); echo "<h3>Salario Cambiado con existo a "; nombreApellidosEmpleado($db,$empleado); echo "</h3>"; } else{ mysqli_rollback($db); } } else{ mysqli_rollback($db); } } } function cambiarCategoria($db,$empleado,$categoria){ $sql="select max(from_date) from titles where emp_no='$empleado'"; $aux=mysqli_query($db,$sql); $arrayid=mysqli_fetch_array($aux); $fecha=$arrayid[0]; $sql2="select curdate()"; $aux2=mysqli_query($db,$sql2); $arrayid2=mysqli_fetch_array($aux2); $fechaactual=$arrayid2[0]; $sql3="select title from titles where emp_no='$empleado' and to_date='9999-01-01'"; $aux3=mysqli_query($db,$sql3); $arrayid3=mysqli_fetch_array($aux3); $categoriaactual=$arrayid3[0]; if($fecha==$fechaactual && $categoriaactual==$categoria){ echo "No se puede cambiar a la misma Categoria el mismo dia. Espera a mañana"; } else{ $sql4="update titles set to_date=curdate() where to_date='9999-01-01' and emp_no='$empleado';"; if($sentencia=mysqli_query($db,$sql4)){ $sql5="insert into titles(emp_no,title,from_date,to_date) values ('$empleado','$categoria',curdate(),'9999-01-01');"; if($sentencia2=mysqli_query($db,$sql5)){ mysqli_commit($db); echo "<h3>Categoria Cambiadoa con existo a "; nombreApellidosEmpleado($db,$empleado); echo "</h3>"; } else{ mysqli_rollback($db); } } else{ mysqli_rollback($db); } } } ?>
C#
UTF-8
3,689
3.46875
3
[ "BSD-3-Clause" ]
permissive
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AdvUtils.Regression { public class MultipleLinearRegression { private double[] coefficients; private bool addIntercept; /// <summary> /// Creates a new Multiple Linear Regression. /// </summary> /// /// <param name="inputs">The number of inputs for the regression.</param> /// <param name="intercept">Whether add intercept into coefficients</param> public MultipleLinearRegression(int inputs, bool intercept = false) { if (intercept) inputs++; this.coefficients = new double[inputs]; this.addIntercept = intercept; } /// <summary> /// Gets the coefficients used by the regression model. If the model /// contains an intercept term, it will be in the end of the vector. /// </summary> /// public double[] Coefficients { get { return coefficients; } } /// <summary> /// Performs the regression using the input vectors and output /// data, returning the sum of squared errors of the fit. /// </summary> /// /// <param name="inputs">The input vectors to be used in the regression.</param> /// <param name="outputs">The output values for each input vector.</param> /// <returns>The Sum-Of-Squares error of the regression.</returns> /// public virtual double Regress(double[][] inputs, double[] outputs) { if (inputs.Length != outputs.Length) throw new ArgumentException("Number of input and output samples does not match", "outputs"); double[,] X; return regress(inputs, outputs, out X); } private double regress(double[][] inputs, double[] outputs, out double[,] X) { if (inputs.Length != outputs.Length) throw new ArgumentException("Number of input and output samples does not match", "outputs"); int rows = inputs.Length; // inputs int cols = inputs[0].Length; // points if (addIntercept) { X = new double[rows, cols + 1]; for (int i = 0; i < rows; i++) X[i, cols] = 1; } else { X = new double[rows, cols]; } for (int i = 0; i < inputs.Length; i++) for (int j = 0; j < inputs[i].Length; j++) X[i, j] = inputs[i][j]; // Solve V*C = B to find C (the coefficients) coefficients = new SingularValueDecomposition(X).Solve(outputs); // Calculate Sum-Of-Squares error double error = 0.0; double e; for (int i = 0; i < outputs.Length; i++) { e = outputs[i] - Compute(inputs[i]); error += e * e; } return error; } /// <summary> /// Computes the Multiple Linear Regression for an input vector. /// </summary> /// /// <param name="input">The input vector.</param> /// /// <returns>The calculated output.</returns> /// public double Compute(double[] input) { double output = 0.0; for (int i = 0; i < input.Length; i++) output += coefficients[i] * input[i]; if (addIntercept) output += coefficients[input.Length]; return output; } } }
C
UTF-8
1,163
3
3
[]
no_license
#include "get_next_line.h" int main(int ac, char **av) { int fd; int fd2; char *line; char *line2; fd = 0; fd2 = 0; // printf("first\n"); if (ac == 2) fd = open(av[1], O_RDONLY); if (ac == 3) { fd = open(av[1], O_RDONLY); fd2 = open(av[2], O_RDONLY); } // get_next_line(fd, &line); // printf(KGRN"-%s-\n", line); // get_next_line(fd2, &line2); // printf(KGRN"-%s-\n", line2); // get_next_line(fd, &line); // printf(KGRN"-%s-\n", line); // get_next_line(fd2, &line); // printf(KGRN"-%s-\n", line); // get_next_line(fd, &line); // printf(KGRN"-%s-\n", line); // get_next_line(fd2, &line2); // printf(KGRN"-%s-\n", line2); // get_next_line(fd, &line); // printf(KGRN"-%s-\n", line); // get_next_line(fd2, &line2); // printf(KGRN"-%s-\n", line2); if (ac == 3) { while (get_next_line(fd2, &line2) > 0) printf(KGRN"-%s-\n", line2); printf(KWHT"\n#-----------------------------------------------#\n\n"); close(fd2); } int ret; while ((ret = get_next_line(fd, &line)) > 0) { printf(KGRN"-%s- ", line); printf("ret: %d\n", ret); } close(fd); return (ret); }
Java
UTF-8
148
1.882813
2
[]
no_license
package com.jfx.springlearn.spring中常用设计模式.观察者模式; public enum TeacherEventEnum { ON_START_CLASS, ON_END_CLASS; }
SQL
UTF-8
9,527
3.109375
3
[]
no_license
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Base de datos: `transito` -- CREATE DATABASE IF NOT EXISTS `transito` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_spanish_ci; USE `transito`; -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `aseguradora` -- CREATE TABLE `aseguradora` ( `idAseguradora` int(11) NOT NULL, `aseguradora` varchar(20) COLLATE utf8mb4_spanish_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_spanish_ci; -- -- RELACIONES PARA LA TABLA `aseguradora`: -- -- -- Volcado de datos para la tabla `aseguradora` -- INSERT INTO `aseguradora` (`idAseguradora`, `aseguradora`) VALUES (1, 'GNP'), (2, 'MAPFRE'), (3, 'AXA'), (4, 'ZURICH'), (5, 'Qualitas'), (6, 'HDI'), (7, 'ABA'), (8, 'Atlas'), (9, 'MetLife'), (10, 'BBVA Bancomer'); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `cargo` -- CREATE TABLE `cargo` ( `idCargo` int(11) NOT NULL, `cargo` varchar(20) COLLATE utf8mb4_spanish_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_spanish_ci; -- -- RELACIONES PARA LA TABLA `cargo`: -- -- -- Volcado de datos para la tabla `cargo` -- INSERT INTO `cargo` (`idCargo`, `cargo`) VALUES (1, 'Administrativo'), (2, 'Perito'), (3, 'Soporte'), (4, 'Atención'); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `conductor` -- CREATE TABLE `conductor` ( `idConductor` int(11) NOT NULL, `nombre` varchar(30) COLLATE utf8mb4_spanish_ci NOT NULL, `apellidoPaterno` varchar(45) COLLATE utf8mb4_spanish_ci NOT NULL, `apellidoMaterno` varchar(45) COLLATE utf8mb4_spanish_ci DEFAULT NULL, `fechaNacimiento` date NOT NULL, `numLicencia` int(11) NOT NULL, `numCelular` varchar(10) COLLATE utf8mb4_spanish_ci NOT NULL, `contrasenia` varchar(18) COLLATE utf8mb4_spanish_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_spanish_ci; -- -- RELACIONES PARA LA TABLA `conductor`: -- -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `dictamen` -- CREATE TABLE `dictamen` ( `idDictamen` int(11) NOT NULL, `descripcion` varchar(250) COLLATE utf8mb4_spanish_ci NOT NULL, `fechaHora` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, `idPersonal` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_spanish_ci; -- -- RELACIONES PARA LA TABLA `dictamen`: -- -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `implicado` -- CREATE TABLE `implicado` ( `idImplicado` int(11) NOT NULL, `idAseguradora` int(11) DEFAULT NULL, `nombre` varchar(50) COLLATE utf8mb4_spanish_ci DEFAULT NULL, `placas` varchar(10) COLLATE utf8mb4_spanish_ci NOT NULL, `poliza` varchar(20) COLLATE utf8mb4_spanish_ci DEFAULT NULL, `marca` varchar(20) COLLATE utf8mb4_spanish_ci NOT NULL, `modelo` varchar(20) COLLATE utf8mb4_spanish_ci NOT NULL, `color` varchar(25) COLLATE utf8mb4_spanish_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_spanish_ci; -- -- RELACIONES PARA LA TABLA `implicado`: -- `idAseguradora` -- `aseguradora` -> `idAseguradora` -- -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `personal` -- CREATE TABLE `personal` ( `idPersonal` int(11) NOT NULL, `idCargo` int(11) NOT NULL, `nombre` varchar(128) COLLATE utf8mb4_spanish_ci NOT NULL, `usuario` varchar(10) COLLATE utf8mb4_spanish_ci NOT NULL, `contrasenia` varchar(18) COLLATE utf8mb4_spanish_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_spanish_ci; -- -- RELACIONES PARA LA TABLA `personal`: -- `idCargo` -- `cargo` -> `idCargo` -- -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `reporte` -- CREATE TABLE `reporte` ( `idReporte` int(11) NOT NULL, `idConductor` int(11) NOT NULL, `idImplicado` int(11) NOT NULL, `idDictamen` int(11) DEFAULT NULL, `imgs` tinyint(1) NOT NULL DEFAULT '0', `placas` varchar(10) COLLATE utf8mb4_spanish_ci NOT NULL, `latitud` double NOT NULL, `longitud` double NOT NULL, `fechaHora` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_spanish_ci; -- -- RELACIONES PARA LA TABLA `reporte`: -- `idConductor` -- `conductor` -> `idConductor` -- `idImplicado` -- `implicado` -> `idImplicado` -- `idDictamen` -- `dictamen` -> `idDictamen` -- `placas` -- `vehiculo` -> `placas` -- -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `vehiculo` -- CREATE TABLE `vehiculo` ( `placas` varchar(10) COLLATE utf8mb4_spanish_ci NOT NULL, `idConductor` int(11) NOT NULL, `idAseguradora` int(11) DEFAULT NULL, `marca` varchar(20) COLLATE utf8mb4_spanish_ci NOT NULL, `modelo` varchar(20) COLLATE utf8mb4_spanish_ci NOT NULL, `anio` int(4) NOT NULL, `color` varchar(25) COLLATE utf8mb4_spanish_ci NOT NULL, `poliza` varchar(20) COLLATE utf8mb4_spanish_ci DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_spanish_ci; -- -- RELACIONES PARA LA TABLA `vehiculo`: -- `idConductor` -- `conductor` -> `idConductor` -- `idAseguradora` -- `aseguradora` -> `idAseguradora` -- -- -- Índices para tablas volcadas -- -- -- Indices de la tabla `aseguradora` -- ALTER TABLE `aseguradora` ADD PRIMARY KEY (`idAseguradora`) USING BTREE; -- -- Indices de la tabla `cargo` -- ALTER TABLE `cargo` ADD PRIMARY KEY (`idCargo`); -- -- Indices de la tabla `conductor` -- ALTER TABLE `conductor` ADD PRIMARY KEY (`idConductor`); -- -- Indices de la tabla `dictamen` -- ALTER TABLE `dictamen` ADD PRIMARY KEY (`idDictamen`) USING BTREE; -- -- Indices de la tabla `implicado` -- ALTER TABLE `implicado` ADD PRIMARY KEY (`idImplicado`) USING BTREE, ADD KEY `idAseguradora` (`idAseguradora`); -- -- Indices de la tabla `personal` -- ALTER TABLE `personal` ADD PRIMARY KEY (`idPersonal`), ADD UNIQUE KEY `usuario` (`usuario`), ADD KEY `idCargo` (`idCargo`); -- -- Indices de la tabla `reporte` -- ALTER TABLE `reporte` ADD PRIMARY KEY (`idReporte`) USING BTREE, ADD KEY `idDictamen` (`idDictamen`) USING BTREE, ADD KEY `reporte_ibfk_2` (`idImplicado`), ADD KEY `reporte_ibfk_1` (`idConductor`), ADD KEY `reporte_ibfk_3` (`placas`) USING BTREE; -- -- Indices de la tabla `vehiculo` -- ALTER TABLE `vehiculo` ADD PRIMARY KEY (`placas`), ADD KEY `idConductor` (`idConductor`), ADD KEY `idAseguradora` (`idAseguradora`); -- -- AUTO_INCREMENT de las tablas volcadas -- -- -- AUTO_INCREMENT de la tabla `aseguradora` -- ALTER TABLE `aseguradora` MODIFY `idAseguradora` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=11; -- -- AUTO_INCREMENT de la tabla `cargo` -- ALTER TABLE `cargo` MODIFY `idCargo` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5; -- -- AUTO_INCREMENT de la tabla `conductor` -- ALTER TABLE `conductor` MODIFY `idConductor` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT de la tabla `dictamen` -- ALTER TABLE `dictamen` MODIFY `idDictamen` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT de la tabla `implicado` -- ALTER TABLE `implicado` MODIFY `idImplicado` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT de la tabla `personal` -- ALTER TABLE `personal` MODIFY `idPersonal` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT de la tabla `reporte` -- ALTER TABLE `reporte` MODIFY `idReporte` int(11) NOT NULL AUTO_INCREMENT; -- -- Restricciones para tablas volcadas -- -- -- Filtros para la tabla `implicado` -- ALTER TABLE `implicado` ADD CONSTRAINT `implicado_ibfk_1` FOREIGN KEY (`idAseguradora`) REFERENCES `aseguradora` (`idAseguradora`) ON DELETE NO ACTION ON UPDATE NO ACTION; -- -- Filtros para la tabla `personal` -- ALTER TABLE `personal` ADD CONSTRAINT `personal_ibfk_1` FOREIGN KEY (`idCargo`) REFERENCES `cargo` (`idCargo`) ON DELETE NO ACTION ON UPDATE NO ACTION; -- -- Filtros para la tabla `reporte` -- ALTER TABLE `reporte` ADD CONSTRAINT `reporte_ibfk_1` FOREIGN KEY (`idConductor`) REFERENCES `conductor` (`idConductor`) ON UPDATE NO ACTION, ADD CONSTRAINT `reporte_ibfk_2` FOREIGN KEY (`idImplicado`) REFERENCES `implicado` (`idImplicado`) ON DELETE NO ACTION ON UPDATE NO ACTION, ADD CONSTRAINT `reporte_ibfk_3` FOREIGN KEY (`idDictamen`) REFERENCES `dictamen` (`idDictamen`) ON DELETE NO ACTION ON UPDATE NO ACTION, ADD CONSTRAINT `reporte_ibfk_4` FOREIGN KEY (`placas`) REFERENCES `vehiculo` (`placas`) ON UPDATE NO ACTION; -- -- Filtros para la tabla `vehiculo` -- ALTER TABLE `vehiculo` ADD CONSTRAINT `vehiculo_ibfk_1` FOREIGN KEY (`idConductor`) REFERENCES `conductor` (`idConductor`) ON DELETE NO ACTION ON UPDATE NO ACTION, ADD CONSTRAINT `vehiculo_ibfk_2` FOREIGN KEY (`idAseguradora`) REFERENCES `aseguradora` (`idAseguradora`) ON DELETE NO ACTION ON UPDATE NO ACTION; COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
Python
UTF-8
1,173
4.03125
4
[]
no_license
""" Given a binary tree, return the tilt of the whole tree. The tilt of a tree node is defined as the absolute difference between the sum of all left subtree node values and the sum of all right subtree node values. Null node has tilt 0. The tilt of the whole tree is defined as the sum of all nodes' tilt. Example: Input: 1 / \ 2 3 Output: 1 Explanation: Tilt of node 2 : 0 Tilt of node 3 : 0 Tilt of node 1 : |2-3| = 1 Tilt of binary tree : 0 + 0 + 1 = 1 Note: The sum of node values in any subtree won't exceed the range of 32-bit integer. All the tilt values won't exceed the range of 32-bit integer. """ class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None # Post order traversal class Solution: def findTilt(self, root: TreeNode) -> int: res = [0] self.dfs(root, res) return res[0] def dfs(self, node: TreeNode, res: List[int]) -> int: if not node: return 0 left = self.dfs(node.left, res) right = self.dfs(node.right, res) res[0] += abs(left - right) return node.val + left + right
C
UTF-8
3,892
3.3125
3
[]
no_license
#include "thread_semaphore.h" #include <pthread.h> #include <stdlib.h> #include <string.h> enum thread_semaphore_flag { TSF_WAIT, /* bloccati in attesa */ TSF_GO /* status ora è valido */ }; struct thread_semaphore{ pthread_mutex_t mutex; pthread_cond_t cond; enum thread_semaphore_flag flag; int status; void* data; }; struct thread_semaphore* thread_semaphore_init() { struct thread_semaphore* ans; ans = malloc(sizeof(struct thread_semaphore)); if (ans == NULL) return NULL; memset(ans, 0, sizeof(struct thread_semaphore)); if (pthread_mutex_init(&ans->mutex, NULL) != 0) { free(ans); return NULL; } if (pthread_cond_init(&ans->cond, NULL) != 0) { pthread_mutex_destroy(&ans->mutex); free(ans); return NULL; } return ans; } int thread_semaphore_wait(struct thread_semaphore* ts) { if (pthread_mutex_lock(&ts->mutex) != 0) return -1; while (ts->flag == TSF_WAIT) if (pthread_cond_wait(&ts->cond, &ts->mutex) != 0) return -1; if (pthread_mutex_unlock(&ts->mutex) != 0) return -1; return 0; } int thread_semaphore_get_status(struct thread_semaphore* ts, int* status, void** data) { if (ts == NULL) return -1; if (status != NULL) *status = ts->status; if (data != NULL) *data = ts->data; return 0; } int thread_semaphore_destroy(struct thread_semaphore* ts) { if (ts == NULL) return -1; if (pthread_cond_destroy(&ts->cond) != 0) return -1; if (pthread_mutex_destroy(&ts->mutex) != 0) return -1; return 0; } int thread_semaphore_signal(struct thread_semaphore* ts, int status, void* data) { if (ts == NULL) return -1; if (pthread_mutex_lock(&ts->mutex) != 0) { return -1; } ts->status = status; ts->data = data; ts->flag = TSF_GO; /* il padre può proseguire */ if (pthread_cond_signal(&ts->cond) != 0) { return -1; } if (pthread_mutex_unlock(&ts->mutex) != 0) { return -1; } return 0; } int start_long_life_thread(pthread_t *thread, void*(*t_fun)(void *), void* args, void** data) { pthread_t t; struct thread_semaphore* ts; int status; void* d; void* argv[2]; ts = thread_semaphore_init(); if (ts == NULL) return -1; argv[0] = ts; argv[1] = args; if (pthread_create(&t, NULL, t_fun, (void*)argv) != 0) { thread_semaphore_destroy(ts); return -1; } if (thread_semaphore_wait(ts) != 0) { thread_semaphore_destroy(ts); return -1; } if (thread_semaphore_get_status(ts, &status, &d) != 0) { thread_semaphore_destroy(ts); return -1; } if (status != 0) { pthread_detach(t); /* il figlio è andato, staccalo */ thread_semaphore_destroy(ts); return -1; } if (thread_semaphore_destroy(ts) != 0) return -1; if (thread == NULL) { /* se il creatore non è interessato * a conoscere l'id del figlio * "fire and forget" */ if (pthread_detach(t) != 0) { return -1; } } else { /* altrimenti il figlio rimarrà joinable */ *thread = t; } if (data != NULL) *data = d; return 0; } /** Compie un lavoro complementare a quello svolto * da start_long_life_thread */ struct thread_semaphore* thread_semaphore_form_args(void* args) { /* argomenti mancanti */ if (args == NULL) return NULL; return (struct thread_semaphore*)((void**)args)[0]; } void* thread_semaphore_get_args(void* args) { /* argomenti mancanti */ if (args == NULL) return NULL; return (struct thread_semaphore*)((void**)args)[1]; }
C++
UTF-8
4,019
2.890625
3
[]
no_license
#include <iostream> #include <fstream> #include <string> /* Conversion (c++11) */ #include <iomanip> #include <locale> #include <sstream> #include "CazanoveGulinoMartinMaupas-Loader.h" #include "conio.h" using namespace std; Loader::Loader() : _files() { } Loader::~Loader() { } Automate* Loader::get(std::string path) { return _files[path]; } bool Loader::test_path(const std::string &path) const { FILE *file = NULL; bool test; file = fopen(path.c_str(), "r"); test = file; fclose(file); return test; } bool Loader::load(const std::string &path) { ifstream file(path, ios::in); gotoxy(1, 10); if (file) { _files[path] = new Automate; string line; /* Language */ getline(file, line); if (line != "<language>") return false; else { do { getline(file, line); if (line != "</language>") { _files[path]->add_to_language(line.c_str()[1]); } }while (line != "</language>"); } /* States */ getline(file, line); if (line != "<states>") return false; else { getline(file, line); int states = strtol(line.c_str(), 0, 10); for (int i = 0; i < states; i++) { ostringstream convert; convert << i+1; _files[path]->add_state(convert.str()); } getline(file, line); if (line != "</states>") return false; } /* Input */ getline(file, line); if (line != "<input>") return false; else { do { getline(file, line); if (line != "</input>") { _files[path]->add_input(line); } }while (line != "</input>"); } /* Output */ getline(file, line); if (line != "<output>") return false; else { do { getline(file, line); if (line != "</output>") { _files[path]->add_output(line); } }while (line != "</output>"); } /* Transitions */ getline(file, line); if (line != "<transition>") return false; else { do { getline(file, line); string state1, state2; char c; if (line != "</transition>") { unsigned int i; for (i = 0; line[i] >= '0' and line [i] <= '9'; i++) state1.push_back(line[i]); c = line[i]; for (i = i+1; i < line.size(); i++) state2.push_back(line[i]); _files[path]->add_transition(state1, state2, c); } }while (line != "</transition>"); } } return true; } void Loader::show_load_error() const { gotoxy(1, 5); cout << "Le chargement du fichier n'a pas reussi. Veuillez verifier que celui-ci n'est pas corrompu et que sa syntaxe suit celle-ci-dessous :\n\n"; textcolor(RED); cout << "<language>\n"; textcolor(LIGHTGRAY); cout << "a\nb\n"; textcolor(RED); cout << "</language>\n<states>\n"; textcolor(LIGHTGRAY); cout << "4\n"; textcolor(RED); cout << "</states>\n<input>\n"; textcolor(LIGHTGRAY); cout << "1\n3\n"; textcolor(RED); cout << "</input>\n<output>\n"; textcolor(LIGHTGRAY); cout << "2\n4\n"; textcolor(RED); cout << "</output>\n<transition>\n"; textcolor(LIGHTGRAY); cout << "1a2\n3b4\n"; textcolor(RED); cout << "</transition>\n" << endl; textcolor(LIGHTGRAY); }
Markdown
UTF-8
924
3.046875
3
[ "MIT" ]
permissive
# Modal A _modal_ component is use to display content to the user and capture an action ## Basic Use _modal_ markup - `.modal` - `.modal-dismiss` - `.modal-header` - `.modal-title` - `.modal-body` - `.modal-footer` <snippeter> <pre> <div class="modal"> <button class="modal-dismiss"> <svg viewbox="0 0 24 24" class="icon"> <path d="M20.71,4.71,13.41,12l7.3,7.29a1,1,0,0,1,0,1.42,1,1,0,0,1-1.42,0L12,13.41l-7.29,7.3a1,1,0,0,1-1.42,0,1,1,0,0,1,0-1.42L10.59,12,3.29,4.71A1,1,0,0,1,4.71,3.29L12,10.59l7.29-7.3a1,1,0,1,1,1.42,1.42Z"></path> </svg> </button> <div class="modal-header"> <h4 class="modal-title">Your title</h4> </div> <div class="modal-body"> <p>Your awesome content goes here!</p> </div> <div class="modal-footer"> <button href="#" class="button">Ok</button> <button href="#" class="button shadow-no">Cancel</button> </div> </div> </pre> </snippeter>
Java
UTF-8
195
1.867188
2
[]
no_license
package com.example.moviemvvm.model; import java.util.List; public class FavouriteList { List<Favourite> results; public List<Favourite> getItems() { return results; } }
C++
UTF-8
750
2.640625
3
[]
no_license
#include <cstdio> #include <vector> #define MAX(A,B) ((A>=B)? A:B) int main(int argc, char** argv) { int cases; scanf("%d",&cases); while(cases--){ int elem,W; scanf("%d %d",&elem,&W); std::vector<int> weights; for(int i=0;i<elem;i++){ int aux; scanf("%d",&aux); weights.push_back(aux); } std::vector<int> m; m.push_back(0); for(int i=1;i<=W;i++){ int max=0; for(int j=0;j<elem;j++){ if(weights[j]<=i){ max= MAX(max, weights[j]+m[i-weights[j]]); } } m.push_back(max); } printf("%d\n",m[W]); } }
PHP
UTF-8
867
2.6875
3
[]
no_license
<?php session_start(); //$userId = $_GET["userId"]; include("../includes/db-config.php"); $tripId = 2; $userId = 1; ?> <h1> Are you sure you want to delete the following member? </h1> <?php // $userdata = $pdo->prepare("SELECT `users`.`fullName`, `users`.`userId` FROM `users`, `users-groups` WHERE `users-groups`.`userId` = '$userId' "); // $userdata->execute(); // // $row2 = $userdata->fetch(); // // var_dump($row2); // // while($row2 = $userdata->fetch()) { // // echo("<br>"); // echo($row2["fullName"]); // echo($row2["userId"]); // //echo($row2["userId"]); // echo("<br>"); // // } ?> <form action="group-delete-process.php" method="POST"> <input type="hidden" name="userId" value="<?php echo($userId); ?>" > <input type="hidden" name='tripId' value="<?php echo($tripId); ?>" > <input type="submit" value="CONFIRM DELETE"/> </form>
Markdown
UTF-8
1,556
2.75
3
[]
no_license
--- title: Developers description: The Cupcake Component Library provides front-end developers &engineers a collection of reusable HTML and SCSS partials to build user interfaces. --- #### Customization You may need to add, remove, or extend the core of Cupcake. You can customize your version by editing and recompiling the scss files in the /src directory. {% callout warning %} #### Autoprefixer: Make sure your build process uses autoprefixer to ensure vendor prefixes are automatically added to your output CSS. {% endcallout %} **Importing Sass** Any customization of Cupcake should be done by importing the scss source files. In this way, you can keep Cupcake up to date without conflicts, use the establish variables to stay in line with the Design Language, and keep your application code seperated from the Cupcake core. <br> **1.) First, install Cupcake via NPM or other package managers.** {% highlight sh %} npm install @cupcake-ds/cupcake --save {% endhighlight %} <br> **2.) Create your scss file to define your variables.** {% highlight scss %} /* import cupcake support files */ @import "cupcake/scss/support"; /* -------begin customization-------- */ // Define variables to override default ones $primary-color: #fc7800; $dark-color: #000; /* -------end customization-------- */ /* finally, import Cupcake core file to set the changes! */ @import "cupcake"; {% endhighlight %} <br> <br> {% callout info %} #### More advanced styling instructions for maps, loops, mixins, and functions coming soon {% endcallout %}
Python
UTF-8
3,219
2.828125
3
[]
no_license
from random import random import numpy as np import math f = open('day15-1_input.txt') # f = open('day15-1_debug.txt') text = f.readlines() f.close() program = [int(i) for i in text[0].strip().split(',')] program.extend([0 for _ in range(10**5)]) grid = np.ones((50, 50)) * -1 grid[:,0] = 0 grid[:,-1] = 0 grid[0,:] = 0 grid[-1,:] = 0 row = col = 50 // 2 pos = 0 rel = 0 inp = 1 moves = 0 while moves < 10**6: command = str(program[pos]) command = '0'*(5-len(command)) + command opcode = command[-2:] modes = command[0:-2] if opcode == '99': break if modes[2] == '0': first = program[program[pos+1]] if modes[2] == '1': first = program[pos+1] if modes[2] == '2': first = program[rel + program[pos+1]] if opcode in ['01', '02', '05', '06', '07', '08']: if modes[1] == '0': second = program[program[pos+2]] if modes[1] == '1': second = program[pos+2] if modes[1] == '2': second = program[rel + program[pos+2]] if opcode in ['01', '02', '07', '08']: if modes[0] == '0': third = program[pos+3] if modes[0] == '1': third = pos+3 if modes[0] == '2': third = rel + program[pos+3] if opcode == '01': program[third] = first + second pos += 4 elif opcode == '02': program[third] = first * second pos += 4 elif opcode == '03': moves += 1 if moves % 10**5 == 0: print(f'PROCESSING: {moves}') if modes[2] == '0': program[program[pos+1]] = inp if modes[2] == '1': program[pos+1] = inp if modes[2] == '2': program[rel + program[pos+1]] = inp pos += 2 elif opcode == '04': out = first if out == 0: if inp == 1: grid[row-1,col] = 0 elif inp == 2: grid[row+1,col] = 0 elif inp == 3: grid[row,col-1] = 0 elif inp == 4: grid[row,col+1] = 0 else: print('ERROR');break inp = math.ceil((4*random())) elif out == 1: if inp == 1: grid[row-1,col] = 1;row -= 1 elif inp == 2: grid[row+1,col] = 1;row += 1 elif inp == 3: grid[row,col-1] = 1;col -= 1 elif inp == 4: grid[row,col+1] = 1;col += 1 else: print('ERROR');break inp = math.ceil((4*random())) elif out == 2: if inp == 1: grid[row-1,col] = 2;row -= 1 elif inp == 2: grid[row+1,col] = 2;row += 1 elif inp == 3: grid[row,col-1] = 2;col -= 1 elif inp == 4: grid[row,col+1] = 2;col += 1 else: print('ERROR');break # break else: print('ERROR');break pos += 2 elif opcode == '05': if first == 0: pos += 3 elif first != 0: pos = second elif opcode == '06': if first != 0: pos += 3 elif first == 0: pos = second elif opcode == '07': if first < second: program[third] = 1 else: program[third] = 0 pos += 4 elif opcode == '08': if first == second: program[third] = 1 else: program[third] = 0 pos += 4 elif opcode == '09': rel += first pos += 2 else: print('ERROR');break print(moves)
C++
UTF-8
1,869
3.03125
3
[]
no_license
#include<iostream> using namespace std; // 0 0 0 1 2 0 1 0 1 2 3 0 1 0 1 2 3 //2: 0 0 0 1 1 1 1 1 1 2 3 3 3 3 3 4 5 //3: 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 2 bool isHalfPrime(int n, int F[]) { return F[n] != 0 && F[n / F[n]] == 0 && n / F[n] != 1; } int main() { int max_size = 1000000; int F[max_size+1]; for (int i = 0; i < max_size+1; i++) { F[i] = 0; } for (int i = 2; i * i < max_size + 1; i++) { if (!F[i]) { for (int k = i * i; k < max_size + 1; k += i) { if (!F[k]) { F[k] = i; } } } } int halfprimes[max_size+1]; halfprimes[0] = 0; halfprimes[1] = 0; for (int i = 2; i < max_size+1; i++) { halfprimes[i] = isHalfPrime(i, F); } int *prefixes1 = new int[max_size+1]; int *prefixes2 = new int[max_size+1]; int *prefixes3 = new int[max_size+1]; prefixes1[0] = 0; prefixes2[0] = 0; prefixes3[0] = 0; for (int i = 1; i < max_size+1; i++) { prefixes1[i] = prefixes1[i-1]; prefixes2[i] = prefixes2[i-1]; prefixes3[i] = prefixes3[i-1]; if (halfprimes[i]) { prefixes1[i]++; if (halfprimes[i - 1]) { prefixes2[i]++; if (i > 2 && halfprimes[i-2]) { prefixes3[i]++; } } } } int z; cin>>z; for (int ii = 0; ii < z; ii++) { int a, b; cin>>a>>b; if (prefixes3[b] - prefixes3[a+1] > 0) { cout<<3<<endl; } else if (prefixes2[b] - prefixes2[a] > 0) { cout<<2<<endl; } else if (prefixes1[b] - prefixes1[a-1] > 0) { cout<<1<<endl; } else { cout<<0<<endl; } } }
PHP
UTF-8
8,534
3.359375
3
[]
no_license
<?php require_once 'Crypt/DiffieHellman/Math.php'; class Crypt_DiffieHellman { private $_prime = null; private $_generator = null; /** * A private number set by the local user. It's optional and will * be generated if not set. * * @var string */ private $_privateKey = null; private $_math = null; /** * The public key generated by this instance after calling generateKeys(). * * @var string */ private $_publicKey = null; /** * The shared secret key resulting from a completed Diffie Hellman * exchange * * @var string */ private $_secretKey = null; /** * Constants; used to define inputs or outputs as binary or big numbers. * Binary form is often used as the exchange form for public keys. */ const BINARY = 'binary'; const NUMBER = 'number'; const BTWOC = 'btwoc'; /** * Constructor; if set construct the object using the parameter array to * set values for Prime, Generator and Private. * If a Private Key is not set, one will be generated at random. * * @param string|integer $prime * @param string|integer $generator * @param string|integer $privateKey * @param string $privateKeyType * @param string $mathExtension */ public function __construct($prime, $generator, $privateKey = null, $privateKeyType = null, $mathExtension = null) { $this->setPrime($prime); $this->setGenerator($generator); if (!is_null($privateKey)) { if (is_null($privateKeyType)) { $privateKeyType = self::NUMBER; } $this->setPrivateKey($privateKey, $privateKeyType); } $this->setBigIntegerMath($mathExtension); } /** * Generate own public key. If a private number has not already been * set, one will be generated at this stage. * * @return Crypt_DiffieHellman */ public function generateKeys() { $this->_publicKey = $this->_math->powmod($this->getGenerator(), $this->getPrivateKey(), $this->getPrime()); return $this; } /** * Returns own public key for communication to the second party to this * transaction. * * @param string $type * @return string */ public function getPublicKey($type = self::NUMBER) { if (is_null($this->_publicKey)) { require_once 'Crypt/DiffieHellman/Exception.php'; throw new Crypt_DiffieHellman_Exception('A public key has not yet been generated using a prior call to generateKeys()'); } if ($type == self::BINARY) { return $this->_math->toBinary($this->_publicKey); } elseif ($type == self::BTWOC) { return $this->_math->btwoc($this->_math->toBinary($this->_publicKey)); } return $this->_publicKey; } /** * Compute the shared secret key based on the public key received from the * the second party to this transaction. This should agree to the secret * key the second party computes on our own public key. * Once in agreement, the key is known to only to both parties. * By default, the function expects the public key to be in binary form * which is the typical format when being transmitted. * * @param string $publicKey * @param string $type * @return void */ public function computeSecretKey($publicKey, $type = self::NUMBER) { if ($type == self::BINARY) { $publicKey = $this->_math->fromBinary($publicKey); } if (!preg_match("/^\d+$/", $publicKey)) { require_once('Crypt/DiffieHellman/Exception.php'); throw new Crypt_DiffieHellman_Exception('invalid parameter; not a positive natural number'); } $this->_secretKey = $this->_math->powmod($publicKey, $this->getPrivateKey(), $this->getPrime()); return $this; } /** * Return the computed shared secret key from the DiffieHellman transaction * * @param string $type * @return string */ public function getSharedSecretKey($type = self::NUMBER) { if (!isset($this->_secretKey)) { require_once('Crypt/DiffieHellman/Exception.php'); throw new Crypt_DiffieHellman_Exception('A secret key has not yet been computed; call computeSecretKey()'); } if ($type == self::BINARY) { return $this->_math->toBinary($this->_secretKey); } elseif ($type == self::BTWOC) { return $this->_math->btwoc($this->_math->toBinary($this->_secretKey)); } return $this->_secretKey; } /** * Setter for the value of the prime number * * @param string $number * @return Crypt_DiffieHellman */ public function setPrime($number) { if (!preg_match("/^\d+$/", $number) || $number < 11) { require_once('Crypt/DiffieHellman/Exception.php'); throw new Crypt_DiffieHellman_Exception('invalid parameter; not a positive natural number or too small: should be a large natural number prime'); } $this->_prime = (string) $number; return $this; } /** * Getter for the value of the prime number * * @param string $type * @return string */ public function getPrime($type = self::NUMBER) { if (!isset($this->_prime)) { require_once('Crypt/DiffieHellman/Exception.php'); throw new Crypt_DiffieHellman_Exception('No prime number has been set'); } if ($type == self::NUMBER) { return $this->_prime; } else if ($type == self::BTWOC) { return $this->_math->btwoc($this->_math->toBinary($this->_prime)); } return $this->_math->toBinary($this->_prime); } /** * Setter for the value of the generator number * * @param string $number * @return Crypt_DiffieHellman */ public function setGenerator($number) { if (!preg_match("/^\d+$/", $number) || $number < 2) { require_once('Crypt/DiffieHellman/Exception.php'); throw new Crypt_DiffieHellman_Exception('invalid parameter; not a positive natural number greater than 1'); } $this->_generator = (string) $number; return $this; } /** * Getter for the value of the generator number * * @param string $type * @return string */ public function getGenerator($type = self::NUMBER) { if (!isset($this->_generator)) { require_once('Crypt/DiffieHellman/Exception.php'); throw new Crypt_DiffieHellman_Exception('No generator number has been set'); } if ($type == self::NUMBER) { return $this->_generator; } else if ($type == self::BTWOC) { return $this->_math->btwoc($this->_math->toBinary($this->_generator)); } return $this->_math->toBinary($this->_generator); } public function setPrivateKey($number, $type = self::NUMBER) { if ($type == self::BINARY) { $number = $this->_math->fromBinary($number); } if (!preg_match("/^\d+$/", $number)) { require_once('Crypt/DiffieHellman/Exception.php'); throw new Crypt_DiffieHellman_Exception('invalid parameter; not a positive natural number'); } $this->_privateKey = (string) $number; return $this; } public function getPrivateKey($type = self::NUMBER) { if (!isset($this->_privateKey)) { $this->setPrivateKey($this->_generatePrivateKey(), self::BINARY); } if ($type == self::BINARY) { return $this->_math->toBinary($this->_privateKey); } elseif ($type == self::BTWOC) { return $this->_math->btwoc($this->_math->toBinary($this->_privateKey)); } return $this->_privateKey; } * * @param string $extension * @return void */ public function setBigIntegerMath($extension = null) { $this->_math = new Crypt_DiffieHellman_Math($extension); } /** * In the event a private number/key has not been set by the user, * generate one at random. * * @return string */ protected function _generatePrivateKey() { $rand = $this->_math->rand($this->getGenerator(), $this->getPrime()); return $rand; } }
Java
UTF-8
5,364
2.6875
3
[]
no_license
package swarm_robotics.map; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; public class Main extends JFrame{ public Main(){ super("Map generation"); Container c = getContentPane(); c.setLayout(new BoxLayout(c, BoxLayout.PAGE_AXIS)); //width switcher with label JPanel widthPanel = new JPanel(); widthPanel.setBorder(BorderFactory.createEmptyBorder(5,10,5,15)); widthPanel.setLayout(new BoxLayout(widthPanel, BoxLayout.X_AXIS)); Label widthLabel = new Label("Width: "); widthLabel.setFont(new Font("Dialog", Font.PLAIN, 16)); SpinnerModel model1 = new SpinnerNumberModel(19, //initial value 5, //min 10000, //max 1); JSpinner widthSpinner = new JSpinner(model1); widthSpinner.setMaximumSize(new Dimension(200, 35)); widthSpinner.setFont(new Font("Dialog", Font.PLAIN, 16)); widthPanel.add(widthLabel); widthPanel.add(widthSpinner); c.add(widthPanel); //height switcher with label JPanel heightPanel = new JPanel(); heightPanel.setBorder(BorderFactory.createEmptyBorder(5,10,5,15)); heightPanel.setLayout(new BoxLayout(heightPanel, BoxLayout.X_AXIS)); Label heightLabel = new Label("Height: "); heightLabel.setFont(new Font("Dialog", Font.PLAIN, 16)); SpinnerModel model2 = new SpinnerNumberModel(19, //initial value 5, //min 10000, //max 1); JSpinner heightSpinner = new JSpinner(model2); heightSpinner.setMaximumSize(new Dimension(200, 35)); heightSpinner.setFont(new Font("Dialog", Font.PLAIN, 16)); heightPanel.add(heightLabel); heightPanel.add(heightSpinner); c.add(heightPanel); //block size switcher with label JPanel sizePanel = new JPanel(); sizePanel.setBorder(BorderFactory.createEmptyBorder(5,10,5,15)); sizePanel.setLayout(new BoxLayout(sizePanel, BoxLayout.X_AXIS)); Label sizeLabel = new Label("Block size: "); sizeLabel.setFont(new Font("Dialog", Font.PLAIN, 16)); SpinnerModel blockModel = new SpinnerNumberModel(10, //initial value 1, //min 10000, //max 1); //step JSpinner sizeSpinner = new JSpinner(blockModel); sizeSpinner.setMaximumSize(new Dimension(200, 35)); sizeSpinner.setFont(new Font("Dialog", Font.PLAIN, 16)); sizePanel.add(sizeLabel); sizePanel.add(sizeSpinner); c.add(sizePanel); //net parameters JPanel netPanel = new JPanel(); netPanel.setBorder(BorderFactory.createEmptyBorder(5,10,5,15)); netPanel.setLayout(new BoxLayout(netPanel, BoxLayout.X_AXIS)); JCheckBox netCheckBox = new JCheckBox("Add net "); netCheckBox.setFont(new Font("Dialog", Font.PLAIN, 16)); SpinnerModel netModel = new SpinnerNumberModel(3, //initial value 3, //min 10000, //max 1); //step JSpinner netSpinner = new JSpinner(netModel); netSpinner.setEnabled(false); netSpinner.setMaximumSize(new Dimension(100, 35)); netSpinner.setFont(new Font("Dialog", Font.PLAIN, 16)); netPanel.add(netCheckBox); netPanel.add(netSpinner); c.add(netPanel); //add check listener netCheckBox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { netSpinner.setEnabled(!netSpinner.isEnabled()); } }); //button JPanel buttonPanel = new JPanel(); buttonPanel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10)); buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.X_AXIS)); Button button = new Button("Generate"); button.setBackground(new Color(0xD7D9D8)); button.setFont(new Font("Dialog", Font.PLAIN, 16)); buttonPanel.add(button); c.add(buttonPanel); setSize(300,250); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); setResizable(false); setLocationRelativeTo(null); //on button click ActionListener listener = new ActionListener() { public void actionPerformed(ActionEvent event) { int width = (int)widthSpinner.getValue(); int height = (int)heightSpinner.getValue(); int blockSize = (int)sizeSpinner.getValue(); MazeGenerator generator = new MazeGenerator(width,height); Cell[][] maze = generator.generateMaze(); //check if net needed if (netCheckBox.isSelected()){ generator.addNet((int)netSpinner.getValue()); } try { XmlBuilder.buildXML(maze, width, height, blockSize); }catch (Exception e){ e.printStackTrace(); } } }; button.addActionListener(listener); } public static void main(String[] args) { new Main(); } }
Python
UTF-8
705
3.28125
3
[]
no_license
#! /usr/bin/env python class Name: def __init__(self, culture, first=None, last=None): self.culture = culture if not culture: raise RuntimeError("Name does not have a culture!") if not culture.language: raise RuntimeError("Name does not have a culture with a language!") self.last = last or culture.language.word(validator=culture.last_name_validator) for n in range(100): self.first = first or culture.language.word(validator=culture.first_name_validator) if self.first != self.last: break def __str__(self): return "{} {}".format(str(self.first).title(), str(self.last).title())
JavaScript
UTF-8
1,624
2.546875
3
[]
no_license
const express = require('express'); const router = express.Router(); const {message}= require('../../models/message'); //post request - to send data router.post('/', (req, res) => { //create object of message callled myMessage - send details of message using request.body object const myMessage = new message({ sender_id: req.body.sender_id, receiver_id: req.body.receiver_id, sender_name: req.body.sender_name, receiver_name: req.body.receiver_name, content: req.body.content, created_date: req.body.created_date }); //insert new record into mongo database using the save object myMessage.save((err, doc)=> { if (!err) {res.send(doc);} else {console.log('Error in Message Save : ' + JSON.stringify(err, undefined, 2));} }); }); router.get('/', (req, res) => { message.find((err, docs) => { if (!err) { //res.send(docs); socket.emit(res); console.log('emit working'); } else {console.log('Error in Retrieving Messages : ' + JSON.stringify(err, undefined, 2));} }); }); //to get messages between two users router.post('/getMessages', (req, res, next) => { message.find() .or([ { $and: [{sender_id: req.body.user1}, {receiver_id: req.body.user2}] }, { $and: [{sender_id: req.body.user2}, {receiver_id: req.body.user1}] } ]) .exec(function (err, results) { if (!err) {res.send(results);} else {console.log('Error in Retrieving Messages : ' + JSON.stringify(err, undefined, 2));} }); }); module.exports=router;
Markdown
UTF-8
2,957
3.171875
3
[ "MIT" ]
permissive
--- title: análisis de nodos date: 2019-03-03 category: metodos-numericos theme: iot syntax_theme: atom-one-light --- ## Análisis de nodos en circuitos eléctricos Métodos numéricos en ingeniería --- ### Método de tensiones nodales Se configura y resuelve un sistema de ecuaciones en el que las incógnitas son los voltajes en los nodos principales del circuito. Notes: En este método, configuramos y resolvemos un sistema de ecuaciones en el que las incógnitas son los voltajes en los nodos principales del circuito. A partir de estos voltajes nodales, las corrientes en las diversas ramas del circuito se determinan fácilmente. --- ## Pasos para el análisis de nodos --- 1. Contar y numerar los nodos 2. Identificar los voltajes 3. Elegir un nodo y asignarle un voltaje $0​$ --- 4. Para cada nodo, excepto el nodo de referencia, anotar la **ley de corrientes de Kirchoff**. $I_a + I_b + I_c = 0$ ![Circuito 1](/assets/img/content/circuito.png) <!-- .element: style="padding: 2rem;" --> Notes: "La suma algebraica de las corrientes que fluyen desde un nodo es igual a cero" Por suma algebraica queremos decir que una corriente que fluye en un nodo debe considerarse una corriente negativa que fluye fuera del nodo. --- 5. Expresar la corriende de cada rama usando la **ley de Ohm** ($I = \frac{V}{R}$) ### Por ejempo $\to$ <!-- .element: class="fragment" data-fragment-index="1" --> --- La corriente descendente del nodo 1 depende de la diferencia de voltaje $V1-V2$ y la resistencia en la rama. ![Circuito 2](/assets/img/content/circuito1.png) <!-- .element: style="padding: 2rem;" --> --- En este caso, la diferencia de voltaje en la resistencia es $V1 - V2$ menos el voltaje en la fuente de alimentación. ![Circuito 3](/assets/img/content/circuito2.png) <!-- .element: style="padding: 2rem;" --> --- En este caso, la diferencia de voltaje a través de la resistencia debe ser 100 voltios mayor que la diferencia $V1 - V2$. ![Circuito 4](/assets/img/content/circuito3.png) <!-- .element: style="padding: 2rem;" --> --- 6. Formar, después de la simplificación, un sistema de $m$ ecuaciones lineales en $m$ voltajes nodales desconocidos (donde $m$ es uno menos que el número de nodos; $m = n - 1$). ### Resolver el sistema <!-- .element: class="fragment" data-fragment-index="1" --> --- ### Ejercicio ![Circuito 5](/assets/img/content/circuito4.png) <!-- .element: style="padding: 2rem;" --> --- ## Solución --- Tener en cuenta que el "par de nodos" en la parte inferior es en realidad un nodo extendido. ![Circuito 6](/assets/img/content/circuito5.png) <!-- .element: style="padding: 2rem;" width="60%" --> --- $\frac{V_1}{30} + \frac{V_1-100}{5} + \frac{V_1 - V_3}{10} = 0$ $\frac{V_3-V_1}{10} + \frac{V_3}{10} + \frac{V_3}{20} = 0$ ### = $(\frac{1}{30}+\frac{1}{5}+\frac{1}{10})V_1 - (\frac{1}{10})V_3 = \frac{100}{5}$ $-(\frac{1}{10})V_1 + (\frac{1}{10}+\frac{1}{10}+\frac{1}{20})V_3 = 0$
JavaScript
UTF-8
439
2.90625
3
[]
no_license
var dinosaur = 'triceratops'; var replacement = dinosaur.toUpperCase(); var text = 'Velociraptor is a genus of herbivorous ceratopsid dinosaur that first appeared during the late Maastrichtian stage of the late Cretaceous period.'; var text2 = text.replace('Velociraptor', ''); var replacedText = (replacement + text2); var numberChars = replacedText.length/2; var halfOftext = replacedText.slice(0, numberChars); console.log(halfOftext);
PHP
UTF-8
974
2.921875
3
[]
no_license
<?php class feeling extends bdd{ protected $id; protected $type; protected $user; protected $activities; protected $date_heure; public function __construct(){ parent::__construct(); } public function setFromBdd($var = []){ foreach($var as $key => $value){ $this->$key = $value; } } public function get_id(){ return $this->id; } public function get_type(){ return $this->type; } public function get_user(){ return $this->user; } public function get_activities(){ return $this->activities; } public function get_date_heure(){ return $this->date_heure; } public function set_id($id){ $this->id = $id; } public function set_type($type){ $this->type = $type; } public function set_user($user){ $this->user = $user; } public function set_activities($activities){ $this->activities = $activities; } public function set_date_heure($date_heure){ $this->date_heure = $date_heure; } } ?>
C++
UTF-8
2,514
2.84375
3
[]
no_license
/** * Copyright 2010 Jason Stredwick * * 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. */ #ifndef __PhylogeneticTree_Interface_TreeIterator_h__ #define __PhylogeneticTree_Interface_TreeIterator_h__ #include <vector> namespace PhylogeneticTree { class iTreeNode; class TreeNode; // The TreeIterator uses a specific ordering for tree traversal. // It first assumes that any given node can have more than two // children and that there are no cycles. For a simplified // description consider a tree with a root and three children // the order that will be retrieved will be // child1, child2, child3, root class TreeIterator { private: TreeNode *node; int depth; TreeIterator(TreeNode *startNode=0, int depth=0); public: TreeIterator(const TreeIterator &); ~TreeIterator(void); const TreeIterator &operator=(const TreeIterator &); // Traversal void operator++(void); // prefix void operator++(int); // postfix void operator--(void); // prefix void operator--(int); // postfix void Up(void); // Data Access const iTreeNode *operator*(void) const; // dereference int GetDepth(void) const { return depth; } TreeIterator GetParent(void) const; std::vector<TreeIterator> GetChildren(void) const; private: void Next_Depth(void); void Previous_Depth(void); friend const bool operator< (const TreeIterator &, const TreeIterator &); friend const bool operator==(const TreeIterator &, const TreeIterator &); friend const bool operator!=(const TreeIterator &, const TreeIterator &); friend class Tree; }; const bool operator< (const TreeIterator &, const TreeIterator &); const bool operator==(const TreeIterator &, const TreeIterator &); const bool operator!=(const TreeIterator &, const TreeIterator &); } // namespace PhylogeneticTree #endif // __PhylogeneticTree_Interface_TreeIterator_h__
SQL
UTF-8
7,510
3.515625
4
[]
no_license
---Project 047 Case study of Individual Spots for Sky 1 and other channels--- --drop table #viewing_segment_summary_sky_1; select channel_name_inc_hd ,corrected_spot_transmission_start_datetime ,corrected_spot_transmission_end_datetime ,spot_duration --,adsmartable_box ,demograph ,adsmartable_box ,isba_tv_region ,case when household_affluence_level in (16,17) then '01: Very High' when household_affluence_level in (13,14,15) then '02: High' when household_affluence_level in (11,12) then '03: Mid High' when household_affluence_level in (9,10) then '04: Mid' when household_affluence_level in (7,8) then '05: Mid Low' when household_affluence_level in (5,6) then '06: Low' when household_affluence_level in (1,2,3,4) then '07: Very Low' when household_affluence_level is null then '08: Unknown' else '08: Unknown' end as affluence_group ,case when head_hh_agef in (1,2,3) then '01: 18-34' when head_hh_agef in (4,5,6,7) then '02: 35-54' when head_hh_agef >7 then '03: 55+' else '04: Unknown' end as age_group ,sum(households_viewing) as total_hh_viewing ,sum(case when demograph = 'ADULTS' then households_viewing when demograph = 'HOUSEWIVES' then households_viewing when unknown_demographic_households_viewing>0 then 0 when demograph = 'ADULTS 16-34' then adult_18_34_households_viewing when demograph = 'ADULTS 16-44' then adult_18_44_households_viewing when demograph = 'ADULTS 16-54' then adult_18_54_households_viewing when demograph = 'ADULTS 25-44' then adult_25_44_households_viewing when demograph = 'ADULTS ABC1' then adult_ABC1_households_viewing when demograph = 'CHILDREN' then hh_with_children_households_viewing when demograph = 'HOUSEWIVES 16-44' then adult_18_44_households_viewing when demograph = 'HOUSEWIVES 16-54' then adult_18_54_households_viewing when demograph = 'HOUSEWIVES ABC1' then adult_ABC1_households_viewing when demograph = 'HOUSEWIVES WITH CHILDREN' then hh_with_children_households_viewing when demograph = 'MEN' then adult_male_households_viewing when demograph = 'MEN 16-34' then adult_male_18_34_households_viewing when demograph = 'MEN ABC1' then adult_male_ABC1_households_viewing when demograph = 'WOMEN' then adult_female_households_viewing when demograph = 'WOMEN 16-34' then adult_female_18_34_households_viewing when demograph = 'WOMEN 16-44' then adult_female_18_44_households_viewing when demograph = 'WOMEN 16-54' then adult_female_18_54_households_viewing when demograph = 'WOMEN ABC1' then adult_female_ABC1_households_viewing else 0 end) as target_demographic_households_viewing ,sum(case when demograph in ('ADULTS','HOUSEWIVES') then 0 else unknown_demographic_households_viewing end) as unknown_demographic into #viewing_segment_summary_sky_1 from vespa_analysts.vespa_spots_with_trading_metric_counts_with_hh_attributes_02_16_jan where demograph is not null and channel_name_inc_hd = 'Sky 1' and cast(corrected_spot_transmission_start_datetime as date) ='2012-01-15' group by channel_name_inc_hd ,corrected_spot_transmission_start_datetime ,corrected_spot_transmission_end_datetime ,spot_duration ,adsmartable_box ,demograph ,adsmartable_box ,affluence_group ,age_group ,isba_tv_region order by channel_name_inc_hd ,corrected_spot_transmission_start_datetime ,corrected_spot_transmission_end_datetime ,spot_duration ,adsmartable_box ,demograph ,adsmartable_box ,affluence_group ,age_group ,isba_tv_region ; select channel_name_inc_hd ,corrected_spot_transmission_start_datetime ,corrected_spot_transmission_end_datetime ,spot_duration ,demograph , sum(total_hh_viewing) as total_households_viewing_spot , sum(target_demographic_households_viewing) as target_demographic_households_viewing_spot , sum(unknown_demographic) as unknown_segment_viewing_spot , sum(total_hh_viewing-target_demographic_households_viewing-unknown_demographic) as mirror_segment_viewing_spot , sum(case when adsmartable_box = 1 then total_hh_viewing else 0 end ) as total_households_viewing_spot_adsmartable_box , sum(case when adsmartable_box = 1 then target_demographic_households_viewing else 0 end) as target_demographic_households_viewing_spot_adsmartable_box , sum(case when adsmartable_box = 1 then unknown_demographic else 0 end) as unknown_segment_viewing_spot_adsmartable_box , sum(case when adsmartable_box = 1 then total_hh_viewing-target_demographic_households_viewing-unknown_demographic else 0 end) as mirror_segment_viewing_spot_adsmartable_box from #viewing_segment_summary_sky_1 where adsmartable_box is not null group by channel_name_inc_hd ,corrected_spot_transmission_start_datetime ,corrected_spot_transmission_end_datetime ,spot_duration ,demograph order by channel_name_inc_hd ,corrected_spot_transmission_start_datetime ,corrected_spot_transmission_end_datetime ,spot_duration ,demograph ; ---Repeat but with Affluence Profile --- select channel_name_inc_hd ,corrected_spot_transmission_start_datetime ,corrected_spot_transmission_end_datetime ,spot_duration ,demograph , sum(total_hh_viewing) as total_households_viewing_spot , sum(target_demographic_households_viewing) as target_demographic_households_viewing_spot , sum(unknown_demographic) as unknown_segment_viewing_spot , sum(total_hh_viewing-target_demographic_households_viewing-unknown_demographic) as mirror_segment_viewing_spot , sum(case when affluence_group ='01: Very High' then total_hh_viewing-target_demographic_households_viewing-unknown_demographic else 0 end) as mirror_segment_viewing_spot_very_high_affluence , sum(case when affluence_group = '02: High' then total_hh_viewing-target_demographic_households_viewing-unknown_demographic else 0 end) as mirror_segment_viewing_spot_high_affluence , sum(case when affluence_group = '03: Mid High' then total_hh_viewing-target_demographic_households_viewing-unknown_demographic else 0 end) as mirror_segment_viewing_spot_mid_high_affluence , sum(case when affluence_group = '04: Mid' then total_hh_viewing-target_demographic_households_viewing-unknown_demographic else 0 end) as mirror_segment_viewing_spot_mid_affluence , sum(case when affluence_group = '05: Mid Low' then total_hh_viewing-target_demographic_households_viewing-unknown_demographic else 0 end) as mirror_segment_viewing_spot_mid_low_affluence , sum(case when affluence_group = '06: Low' then total_hh_viewing-target_demographic_households_viewing-unknown_demographic else 0 end) as mirror_segment_viewing_spot_low_affluence , sum(case when affluence_group = '07: Very Low' then total_hh_viewing-target_demographic_households_viewing-unknown_demographic else 0 end) as mirror_segment_viewing_spot_very_low_affluence , sum(case when affluence_group = '08: Unknown' then total_hh_viewing-target_demographic_households_viewing-unknown_demographic else 0 end) as mirror_segment_viewing_spot_unknown_affluence from #viewing_segment_summary_sky_1 where adsmartable_box is not null group by channel_name_inc_hd ,corrected_spot_transmission_start_datetime ,corrected_spot_transmission_end_datetime ,spot_duration ,demograph order by channel_name_inc_hd ,corrected_spot_transmission_start_datetime ,corrected_spot_transmission_end_datetime ,spot_duration ,demograph ; select tx_start_datetime_utc,epg_title from sk_prod.vespa_epg_dim where tx_date ='20120115' and channel_name ='Sky1' and bss_name = 'Sky 1 Digital' order by tx_date_time_utc
JavaScript
UTF-8
827
2.625
3
[]
no_license
module.exports = { firstTime() { return 'El siguiente paso es calcular las distancias parcialmente. Partiendo del nodo 0, vemos que solo poodemos ' + 'acceder al nodo 1 y 2. Como podemos observar, la distancia al nodo 1 es 20, y como hasta ahora no teníamos ninguna distancia previa, ' + 'colocamos 20 como distancia. Lo mismo hacemos con la distancia al nodo 2, que en este caso es 10. Al no poder acceder a los nodos 3 y 4 ' + 'directamente desde el nodo 0, no sabemos aún cual es su distancia mínima, así que colocamos, infinito. Si desea volver a escuchar ' + 'esta explicación diga, repetir, y en caso de querer continuar con la explicación, diga, siguiente.'; }, withVolverIntent() { return 'Has vuelto a la pantalla del paso de inicialización donde se muestra el conjunto de distancias'; } };
Java
UTF-8
60
1.6875
2
[]
no_license
package secret.model; public enum Carte { LUMOS, NOX }
C++
UTF-8
721
2.734375
3
[]
no_license
#include "SDLManager.h" #include "SDL.h" #include "SDL_ttf.h" #include "SDL_image.h" #include <iostream> void SDLManager::Setup() { m_initSuccess = false; if (SDL_Init(SDL_INIT_VIDEO) != SDL_INIT_SUCCESS) { SDL_LOG("Failed to Init Core"); return; } if (TTF_Init() != TTF_INIT_SUCCESS) { SDL_LOG("Failed to Init TTF"); return; } const int flag = IMG_INIT_PNG; const int initted = IMG_Init(flag); if ((initted&flag) != flag) { SDL_LOG("Failed to Init Image"); return; } m_initSuccess = true; } void SDLManager::Close() { TTF_Quit(); IMG_Quit(); SDL_Quit(); } void SDLManager::Update() { // No Update needed for SDLManager } bool SDLManager::InitSucceed() const { return m_initSuccess; }
C
UTF-8
907
2.609375
3
[]
no_license
#include <lib.compile/compile-action.h> #include <lib.compile/compile-print.h> #include <lib.core/memory.h> #include <lib.core/string.h> CompileAction *compile_action_create (CompileActionType type) { CompileAction *action; if (type != COMPILE_ACTION_CC && type != COMPILE_ACTION_ARCH && type != COMPILE_ACTION_INDEX && type != COMPILE_ACTION_BUILD && type != COMPILE_ACTION_SILENT) { compile_debug_invalid_arguments (); return NULL; } if (!(action = memory_create (sizeof (CompileAction)))) { compile_debug_allocate_memory (); return NULL; } action->type = type; action->print = NULL; action->command = NULL; return action; } void compile_action_destroy (CompileAction *action) { if (!action) { return; } if (action->print) { string_destroy (action->print); } if (action->command) { string_destroy (action->command); } memory_destroy (action); }
Python
UTF-8
1,255
3.015625
3
[]
no_license
from robot import Robot from sr2013 import VisionShim from devices import Mbed, MotorMbed class Arm(object): def __init__(self, mbed): self._mbed = mbed self.lifted = False def setLifted(self, lifted, timeout=10.0): """Moves the arm to a specified state. :param lifted: whether the arm should be lifted (True) or lowered (False) :type lifted: bool :param timeout: the amount of time after which the operation should time out and raise an exception. :type timeout: float or None :returns: a bool representing whether the operation succeeded. :raises: mbed.Timeout -- if the arm failed to move to the specified state in time """ if self.lifted != lifted: self._mbed.sendCommand('A' + int(lifted), timeout=timeout) self.lifted = lifted return True class LifterBot(Robot): def __init__(self, mode): self.mbed = Mbed('/dev/ttyACM0', 115200) self.vision = VisionShim('/dev/video0') self.leftMotor = MotorMbed(self.mbed, 0) self.rightMotor = MotorMbed(self.mbed, 1) super(LifterBot, self).__init__(mode)
Markdown
UTF-8
2,111
3.953125
4
[ "MIT" ]
permissive
--- layout: post title: AVL Tree comments: true tags: - Algorithm --- The following is definition of AVL Tree according to [Wikipedia](https://en.wikipedia.org/wiki/AVL_tree) > In computer science, an AVL tree is a self-balancing binary search tree. It was the first such data structure to be invented. In an AVL tree, the heights of the two child subtrees of any node differ by at most one; if at any time they differ by more than one, rebalancing is done to restore this property. ## **Big-O Complexity** *Note: N is the number of nodes in the tree prior to the operation* Lookup, insertion, and deletion all take O(log N) time in both the average and worst cases because it is self-balancing. The diffrence between heights of left and right sub-trees are not more than one for all nodes. The following site has a great table for comparing complexities. <br/> [Big-O Algorithm Complexity Cheat Sheet](http://bigocheatsheet.com/) ## **Implementation** ```ruby class AVLTree class Node attr_reader :value, :left, :right def initialize(value) @value = value @left = nil @right = nil end def insert(v) case @value <=> v when -1 # insert into right subtree @right.nil? ? @right = Node.new(v) : @right.insert(v) when 1 # insert into left subtree @left.nil? ? @left = Node.new(v) : @left.insert(v) end end end def initialize(v) @root = Node.new(v) end def insert(v) @root.insert(v) end def is_balanced?(node=@root) h_left = get_height(node.left) h_right = get_height(node.right) h_diff = h_left - h_right return h_diff.abs > 1 ? false : true end def get_height(node=@root) return 0 if node.nil? # base case h_left = get_height(node.left) h_right = get_height(node.right) return [h_left, h_right].max + 1 end end # Create an AVL Tree avl_tree = AVLTree.new(10) avl_tree.insert(5) avl_tree.insert(15) puts avl_tree.get_height puts avl_tree.is_balanced? puts avl_tree.inspect ``` ## Resource * [Source code](https://github.com/hodoolee/ruby-algorithms)
Python
UTF-8
376
3.359375
3
[]
no_license
def minion_game(string): cnt1 = 0 cnt2 = 0 for i in range(0,len(string)): if string[i] in ("A","E","I","O","U"): cnt2 += len(string) - i else: cnt1 += len(string) - i if cnt1 > cnt2: print("Stuart " + str(cnt1)) elif cnt1 < cnt2: print("Kevin " + str(cnt2)) else: print("Draw")
Java
UTF-8
359
2.734375
3
[]
no_license
package ceng.anadolu.bim492.project2; public class Swordsman extends Soldier { public Swordsman(){ attackBehavior = new InfantryAttack(); movementBehavior = new SlowWalk(); } @Override public void display() { blank(); System.out.println("I'm a Swordsman."); System.out.println("I can use sword. I'm strong for pikemans,skirmishers"); } }
Markdown
UTF-8
2,434
2.53125
3
[]
no_license
Formats: [HTML](/news/2011/09/23/south-korean-prosecutors-raid-the-offices-of-seven-savings-banks-whose-operations-were-suspended-last-week-with-the-president-of-one-bank-c.html) [JSON](/news/2011/09/23/south-korean-prosecutors-raid-the-offices-of-seven-savings-banks-whose-operations-were-suspended-last-week-with-the-president-of-one-bank-c.json) [XML](/news/2011/09/23/south-korean-prosecutors-raid-the-offices-of-seven-savings-banks-whose-operations-were-suspended-last-week-with-the-president-of-one-bank-c.xml) ### [2011-09-23](/news/2011/09/23/index.md) ##### South Korea # South Korean prosecutors raid the offices of seven savings banks whose operations were suspended last week, with the president of one bank committing suicide. ### Sources: 1. [Yonhap](http://english.yonhapnews.co.kr/national/2011/09/23/0302000000AEN20110923005800315.HTML) ### Related: 1. [ Former South Korean President Roh Moo-hyun commits suicide. ](/news/2009/05/23/former-south-korean-president-roh-moo-hyun-commits-suicide.md) _Context: South Korea, suicide_ 2. [South Korea states that North Korea is willing to hold talks with the United States on denuclearization on the Korean Peninsula. ](/news/2018/03/6/south-korea-states-that-north-korea-is-willing-to-hold-talks-with-the-united-states-on-denuclearization-on-the-korean-peninsula.md) _Context: South Korea_ 3. [The South Korean Aviation and Railway Accident Investigation Board issues its final report on a near-collision between a China Southern Airbus A319 and a Korean Air Boeing 737-800 on a runway in Cheongju, South Korea. The Board reports the Airbus crew misunderstood the full meaning of the specific ground control runway instruction. ](/news/2018/03/27/the-south-korean-aviation-and-railway-accident-investigation-board-issues-its-final-report-on-a-near-collision-between-a-china-southern-airb.md) _Context: South Korea_ 4. [South Korea and the United States reach agreements on trade and steel tariffs. ](/news/2018/03/25/south-korea-and-the-united-states-reach-agreements-on-trade-and-steel-tariffs.md) _Context: South Korea_ 5. [A passenger ferry grounds off the coast of South Korea, injuring at least six people with The South Korean Coastguard evacuating all 163 on board. ](/news/2018/03/25/a-passenger-ferry-grounds-off-the-coast-of-south-korea-injuring-at-least-six-people-with-the-south-korean-coastguard-evacuating-all-163-on.md) _Context: South Korea_
Python
UTF-8
530
2.984375
3
[]
no_license
import pickle import datetime def save_data(gym_store, folder="gym_data/"): filename_date = folder + str(datetime.datetime.now().strftime("%Y_%m_%d")) + ".dat" with open(filename_date, "wb") as f: pickle.dump(gym_store, f) """ #This shows how to read pickled list with open(filename_date, "rb") as f: for i in pickle.load(f): print("Gym ") print(i.name) print(i.address) print(i.link) print("*******************************") """
Markdown
UTF-8
559
2.59375
3
[]
no_license
# Blog with a photo gallery and CMS ## Introduction It was built with the use of PHP, JS, jQuery, Bootstrap, MySqli ## Getting Started 1. Create database with 4 tables: - users (id, username, password, first_name, last_name, rights, filename, created_at, last_modified) - posts (id, author, title, body, created_at, last_modified) - photos (id, title, description, filename, alt_text, type, size, created_at, last_modified, author) - comments (id, photo_id, author, body, created_at) 2. Fill in DB details in /admin/includes/db_config.php 3. Ready to use
Java
UTF-8
2,083
4.125
4
[]
no_license
package CodeWars.josephus_survivor; //In this kata you have to correctly return who is the "survivor", ie: the last element of a Josephus permutation. // // Basically you have to assume that n people are put into a circle and that they are eliminated in steps of k elements, like this: // // josephus_survivor(7,3) => means 7 people in a circle; // one every 3 is eliminated until one remains // [1,2,3,4,5,6,7] - initial sequence // [1,2,4,5,6,7] => 3 is counted out // [1,2,4,5,7] => 6 is counted out // [1,4,5,7] => 2 is counted out // [1,4,5] => 7 is counted out // [1,4] => 5 is counted out // [4] => 1 counted out, 4 is the last element - the survivor! // The above link about the "base" kata description will give you a more thorough insight about the origin of this kind of permutation, // but basically that's all that there is to know to solve this kata. // // Notes and tips: using the solution to the other kata to check your function may be helpful, but as much larger numbers will be used, using an array/list to compute the number of the survivor may be too slow; you may assume that both n and k will always be >=1. import java.util.ArrayList; import java.util.List; import java.util.ListIterator; public class Solution { //n = number of people in cricle, k = every k people die protected static int josephusSurvivor(final int n, final int k) { //build the arrayList List<Integer> circle = new ArrayList<>(); for (int i = 0; i<n; i++) circle.add(i+1); int currentPosition = 0; while (circle.size() > 1) { for (ListIterator<Integer> i = circle.listIterator(); i.hasNext();) { Integer element = i.next(); currentPosition++; if (currentPosition == k) { if (circle.size() == 1) break; i.remove(); currentPosition = 0; } } } return circle.get(0); } }
C
WINDOWS-1250
1,953
3.5
4
[]
no_license
/* Napisati program koji iz datoteke ita dio teksta, rije po rije i unosi ih u red s prioritetom (maksimalna duljina rijei 1024 znaka, prioritet=1 => rije poinje samoglasnikom, prioritet=2 => rije poinje suglasnikom;). Rijei u redu moraju biti sortirane po prioritetu. Iz tako kreiranog reda kreirati dvije datoteke, u prvoj e se nalaziti rijei sa prioritetom=1, a u drugoj rijei s prioritetom=2; s tim da su te rijei u datoteci zapisane sortirane po abecedi. */ #include <stdio.h> #include <stdlib.h> #include <conio.h> typedef struct list *pos; typedef struct list { char rijec[1024]; int prioritet; pos next; }list; void unosIzFilea(pos); //void printList(pos); void printListUFileove(pos); int main() { list head; head.next = NULL; unosIzFilea(&head); //printList(&head); printListUFileove(&head); return 0; } void unosIzFilea(pos P) { FILE *dat; dat = fopen("Text.txt", "r"); while (!feof(dat)) { pos temp = (pos)malloc(sizeof(list)); fscanf(dat, " %s", temp->rijec); switch (temp->rijec[0]) { case 'a': case 'e': case 'i': case 'o': case 'u': case 'A': case 'E': case 'I': case 'O': case 'U': temp->prioritet = 1; break; default: temp->prioritet = 2; break; } temp->next = P->next; P->next = temp; } fclose(dat); } void printListUFileove(pos P) { FILE *samoglasnik, *suglasnik; samoglasnik = fopen("samoglasnici.txt", "w"); suglasnik = fopen("suglasnici.txt", "w"); P = P->next; while (NULL != P) { if (1 == P->prioritet) { fprintf(samoglasnik, "\n%s", P->rijec); } else { fprintf(suglasnik, "\n%s", P->rijec); } P = P->next; } fclose(samoglasnik); fclose(suglasnik); } //void printList(pos P) //{ // P = P->next; // while (NULL != P) // { // printf("\n\t%s %d", P->rijec, P->prioritet); // P = P->next; // } //}
Python
UTF-8
3,254
3
3
[ "AFL-2.1", "AFL-3.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
#!/usr/bin/env python3 """ EV is a simple ES-like EA invented by Ken De Jong for educational purposes. Essentially, an EV uses a real-valued representation, and a pre-defined, static standard deviation applied to the Gaussian mutation operator. Note that there are sibling examples the demonstrate more true evolutionary strategy-like approaches. """ import os from toolz import pipe from leap_ec import Individual, context, test_env_var from leap_ec import ops, util from leap_ec.decoder import IdentityDecoder from leap_ec.real_rep.problems import SpheroidProblem from leap_ec.real_rep.initializers import create_real_vector from leap_ec.real_rep.ops import mutate_gaussian def print_population(population, generation): """ Convenience function for pretty printing a population that's associated with a given generation :param population: :param generation: :return: None """ for individual in population: print(generation, individual.genome, individual.fitness) BROOD_SIZE = 3 # how many offspring each parent will reproduce POPULATION_SIZE = 10 # When running the test harness, just run for two generations # (we use this to quickly ensure our examples don't get bitrot) if os.environ.get(test_env_var, False) == 'True': MAX_GENERATIONS = 2 else: MAX_GENERATIONS = 5 ############################## # Entry point ############################## if __name__ == '__main__': # Define the real value bounds for initializing the population. In this # case, we define a genome of four bounds. # the (-5.12,5.12) was what was originally used for this problem in # Ken De Jong's 1975 dissertation, so was used for historical reasons. bounds = [(-5.12, 5.12), (-5.12, 5.12), (-5.12, 5.12), (-5.12, 5.12)] parents = Individual.create_population(POPULATION_SIZE, initialize=create_real_vector( bounds), decoder=IdentityDecoder(), problem=SpheroidProblem(maximize=False)) # Evaluate initial population parents = Individual.evaluate_population(parents) # print initial, random population print_population(parents, generation=0) max_generation = MAX_GENERATIONS # Set up a generation counter using the default global context variable generation_counter = util.inc_generation() while generation_counter.generation() < max_generation: offspring = pipe(parents, ops.random_selection, ops.clone, mutate_gaussian(std=.1, expected_num_mutations=1), ops.evaluate, ops.pool( size=len(parents) * BROOD_SIZE), # create the brood ops.insertion_selection(parents=parents)) parents = offspring generation_counter() # increment to the next generation # Just to demonstrate that we can also get the current generation from # the context print_population(parents, context['leap']['generation'])
Rust
UTF-8
7,984
3
3
[ "MIT", "Apache-2.0", "LicenseRef-scancode-free-unknown" ]
permissive
use std::f64; use std::num::Wrapping; use std::convert::TryFrom; use gml::symbol::Symbol; use gml::{self, vm}; pub struct State { random_seed: Wrapping<i32>, } impl Default for State { fn default() -> State { State { random_seed: Wrapping(0), } } } #[gml::bind] impl State { /// Emulate Delphi's LCG to advance the current random state. fn random_next(&mut self) -> u32 { self.random_seed = self.random_seed * Wrapping(0x8088405) + Wrapping(1); let Wrapping(seed) = self.random_seed; seed as u32 } /// Emulate Delphi's LCG to produce a random value in the range [0, x). /// /// This works by taking the top 32 bits of the 64-bit product of the seed and the max value. /// Because the seed is in the range [0, 2^32), it can be viewed as the fractional part of a /// 64-bit fixed-point number in the range [0, 1). fn random_u32(&mut self, x: u32) -> u32 { let seed = self.random_next(); (seed as u64 * x as u64 >> 32) as u32 } /// Emulate Delphi's LCG to produce a random value in the range [0, 1). /// /// This works by dividing the seed's value, in the range [0, 2^32), by 2^32. fn random_f64(&mut self) -> f64 { let seed = self.random_next(); seed as f64 / 0x1_0000_0000u64 as f64 } #[gml::api] pub fn random(&mut self, x: f64) -> f64 { self.random_f64() * x } #[gml::api] pub fn random_range(&mut self, x1: f64, x2: f64) -> f64 { x1 + self.random(x2 - x1) } #[gml::api] pub fn irandom(&mut self, x: u32) -> u32 { self.random_u32(x + 1) } #[gml::api] pub fn irandom_range(&mut self, x1: u32, x2: u32) -> u32 { x1 + self.irandom(x2 - x1 + 1) } #[gml::api] pub fn random_set_seed(&mut self, seed: i32) { self.random_seed = Wrapping(seed); } #[gml::api] pub fn random_get_seed(&mut self) -> i32 { let Wrapping(seed) = self.random_seed; seed } #[gml::api] pub fn randomize(&mut self) { // TODO: set the seed to the low bits of QueryPerformanceCounter } #[gml::api] pub fn choose(&mut self, vals: &[vm::Value]) -> vm::Value { vals[self.irandom(vals.len() as u32 - 1) as usize].clone() } #[gml::api] pub fn abs(x: f64) -> f64 { f64::abs(x) } #[gml::api] pub fn sign(x: f64) -> f64 { f64::signum(x) } /// Round x to the nearest integer. /// /// The rounding actually occurs in i32::try_from(vm::Value), to ensure consistency with other /// instances of rounding in the language. #[gml::api] pub fn round(x: i32) -> i32 { x } #[gml::api] pub fn floor(x: f64) -> f64 { f64::floor(x) } #[gml::api] pub fn ceil(x: f64) -> f64 { f64::ceil(x) } #[gml::api] pub fn frac(x: f64) -> f64 { f64::fract(x) } #[gml::api] pub fn sqrt(x: f64) -> f64 { f64::sqrt(x) } #[gml::api] pub fn sqr(x: f64) -> f64 { x * x } #[gml::api] pub fn power(x: f64, n: f64) -> f64 { f64::powf(x, n) } #[gml::api] pub fn exp(x: f64) -> f64 { f64::exp(x) } #[gml::api] pub fn ln(x: f64) -> f64 { f64::ln(x) } #[gml::api] pub fn log2(x: f64) -> f64 { f64::log2(x) } #[gml::api] pub fn log10(x: f64) -> f64 { f64::log10(x) } #[gml::api] pub fn logn(n: f64, x: f64) -> f64 { f64::log(x, n) } #[gml::api] pub fn sin(x: f64) -> f64 { f64::sin(x) } #[gml::api] pub fn cos(x: f64) -> f64 { f64::cos(x) } #[gml::api] pub fn tan(x: f64) -> f64 { f64::tan(x) } #[gml::api] pub fn arcsin(x: f64) -> f64 { f64::asin(x) } #[gml::api] pub fn arccos(x: f64) -> f64 { f64::acos(x) } #[gml::api] pub fn arctan(x: f64) -> f64 { f64::atan(x) } #[gml::api] pub fn arctan2(y: f64, x: f64) -> f64 { f64::atan2(y, x) } #[gml::api] pub fn degtorad(x: f64) -> f64 { x / 180.0 * f64::consts::PI } #[gml::api] pub fn radtodeg(x: f64) -> f64 { x * 180.0 / f64::consts::PI } #[gml::api] pub fn min(vals: &[vm::Value]) -> vm::Value { let (mut min, rest) = match vals.split_first() { None => return vm::Value::default(), Some((first, rest)) => (first.borrow(), rest), }; for val in rest { let val = val.borrow(); // GM treats `val` as the same type as `min` here, regardless of its actual type. match min.decode() { vm::Data::Real(real) => if f64::try_from(val).unwrap_or_default() < real { min = val; } vm::Data::String(string) => if Symbol::try_from(val).unwrap_or_default() < string { min = val; } _ => {} } } min.clone() } #[gml::api] pub fn max(vals: &[vm::Value]) -> vm::Value { let (mut max, rest) = match vals.split_first() { None => return vm::Value::default(), Some((first, rest)) => (first.borrow(), rest), }; for val in rest { let val = val.borrow(); // GM treats `val` as the same type as `max` here, regardless of its actual type. match max.decode() { vm::Data::Real(real) => if f64::try_from(val).unwrap_or_default() > real { max = val; } vm::Data::String(string) => if Symbol::try_from(val).unwrap_or_default() > string { max = val; } _ => {} } } max.clone() } #[gml::api] pub fn mean(vals: &[vm::Value]) -> f64 { let sum: f64 = vals.iter() .map(|val| f64::try_from(val.borrow()).unwrap_or_default()) .sum(); if vals.len() > 0 { sum / vals.len() as f64 } else { 0.0 } } #[gml::api] pub fn median(vals: &[vm::Value]) -> f64 { // Because vm::Value is NaN-boxed, sorting shouldn't encounter NaNs. // TODO: this may no longer be true in GMS let mut vals: Vec<_> = vals.iter() .map(|val| f64::try_from(val.borrow()).unwrap_or_default()) .collect(); vals.sort_by(|a, b| f64::partial_cmp(a, b).unwrap()); if vals.len() > 0 { vals[vals.len() / 2] } else { 0.0 } } #[gml::api] pub fn point_distance(x1: f64, y1: f64, x2: f64, y2: f64) -> f64 { let x = x2 - x1; let y = y2 - y1; f64::sqrt(x * x + y * y) } #[gml::api] pub fn point_direction(x1: f64, y1: f64, x2: f64, y2: f64) -> f64 { let x = x2 - x1; let y = y2 - y1; Self::radtodeg(Self::arctan2(y, x)) } #[gml::api] pub fn lengthdir_x(len: f64, dir: f64) -> f64 { len * Self::cos(dir) } #[gml::api] pub fn lengthdir_y(len: f64, dir: f64) -> f64 { len * -Self::sin(dir) } #[gml::api] pub fn is_real(x: vm::ValueRef) -> bool { match x.decode() { vm::Data::Real(_) => true, _ => false } } #[gml::api] pub fn is_string(x: vm::ValueRef) -> bool { match x.decode() { vm::Data::String(_) => true, _ => false } } } #[cfg(test)] mod tests { use super::*; #[test] fn random_sequence() { let mut state = State::default(); state.random_set_seed(236732942); assert_eq!(state.irandom(10), 3); assert_eq!(state.random_get_seed(), 1493992007); assert_eq!(state.irandom(10), 5); assert_eq!(state.random_get_seed(), 2057512804); assert_eq!(state.irandom(10), 9); assert_eq!(state.random_get_seed(), -526428939); assert_eq!(state.irandom(10), 9); assert_eq!(state.random_get_seed(), -627901238); assert_eq!(state.irandom(10), 2); assert_eq!(state.random_get_seed(), 1166481395); } }
SQL
UTF-8
2,204
3.109375
3
[]
no_license
INSERT INTO client (name, description) VALUES ('Miguel Bandeira', 'Vereador da C.M. Braga'); INSERT INTO catalog (title, description) VALUES ('Sinais de Transito', 'Sinais rodoviarios da cidade de Braga'); INSERT INTO client_catalog VALUES (1, 1, 'Contracto Atlas Innovation - CMBraga'); INSERT INTO feature (title, icon, pathtotrainingdataset) VALUES ('B2 - Paragem obrigatoria no cruzamento ou entroncamento', 'https://github.com/taniaesteves/UCE15/blob/master/Code/Model/Catalogs/sinais_de_transito/icons/B2.png?raw=true', 'trainingdataset.png'); INSERT INTO feature (title, icon, pathtotrainingdataset) VALUES ('D4 - Rotunda', 'https://github.com/taniaesteves/UCE15/blob/master/Code/Model/Catalogs/sinais_de_transito/icons/D4.png?raw=true', 'trainingdataset2.png'); INSERT INTO feature (title, icon, pathtotrainingdataset) VALUES ('D1A - Sentido obrigatório', 'https://github.com/taniaesteves/UCE15/blob/master/Code/Model/Catalogs/sinais_de_transito/icons/D1A.png?raw=true', 'trainingdataset2.png'); INSERT INTO catalog_feature VALUES (1, 1); INSERT INTO catalog_feature VALUES (1, 2); INSERT INTO marker (featureid, latitude, longitude, imagepath, timestamp, precision) VALUES (1, 41.560404, -8.4056225, 'https://github.com/taniaesteves/UCE15/blob/master/Code/Model/Catalogs/sinais_de_transito/figures/b2_2017-11-25_20-38-25.PNG?raw=true', '2017-11-25 20:38:25', 89); INSERT INTO marker (featureid, latitude, longitude, imagepath, timestamp, precision) VALUES (3, 41.560404, -8.4056225, 'https://github.com/taniaesteves/UCE15/blob/master/Code/Model/Catalogs/sinais_de_transito/figures/d4_2017-11-25_19-02-14.PNG?raw=true', '2017-11-25 20:38:54', 68); INSERT INTO marker (featureid, latitude, longitude, imagepath, timestamp, precision) VALUES (2, 41.5580814, -8.3976456, 'https://github.com/taniaesteves/UCE15/blob/master/Code/Model/Catalogs/sinais_de_transito/figures/d1a_2017-11-25_20-38-54.PNG?raw=true', '2017-11-25 19:02:14', 74); --SELECT title, description, icon, latitude, longitude, imagepath --FROM ((image i JOIN marker m ON m.id=i.markerid) mi JOIN feature f ON f.id=mi.featureid) fm --JOIN catalog_feature cf ON cf.featureid=fm.featureid --WHERE cf.catalogid=1;
C#
UTF-8
3,226
3.828125
4
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AdditionTask1 { /*Используя Visual Studio, создайте проект по шаблону Console Application. Создайте программу, в которой создайте класс Car (машина) который содержит в себе полями с название, цвет, цена, const полем CompanyName. Создать два конструктора – по умолчанию и с параметрами.Создать свойство доступа к полю цвет. Определить методы Input () - для ввода данных о машине с консоли , Print () - для вывода данных о машине на консоль и ChangePrice (double x) - для изменения цены на х%. Ввести данные о 3 авто.Уменьшить их цену на 10%, вывести данные об авто. Ввести новый цвет и покрасить авто с цветом white в указанный цвет.*/ class Program { static void Main(string[] args) { Car car1 = new Car("Yaris","Black",7000); Car car2 = new Car("Сamry","Red",7500); Car car3 = new Car("Corolla","White",8000); car1.Print(); car2.Print(); car3.Print(); car3.Color = "Blue"; car1.ChangePrice(-10); car2.ChangePrice(-10); car3.ChangePrice(-10); car1.Print(); car2.Print(); car3.Print(); Console.ReadLine(); } } public class Car { private const string companyName = "Toyota"; private string name; private string color; private double cost; public string Name { get { return name; } set { name = value; } } public string CompanyName { get { return companyName; } } public string Color { get { return color; } set { color = value; } } public double Cost { get { return cost; } set { cost = value; } } public Car() { } public Car(string name,string color,double cost) {Color = color; Cost = cost; Name = name; } public void Input() { Console.Write("Choose car name: "); Name = Console.ReadLine(); Console.Write("Choose car color: "); Color = Console.ReadLine(); Console.Write("Choose car price: "); Cost = double.Parse(Console.ReadLine()); } public double ChangePrice(double interest) { Cost = interest / 100 * Cost + Cost; return Cost; } public void Print() { Console.WriteLine(CompanyName+": "+Name); Console.WriteLine("Color: "+Color); Console.WriteLine("Price: "+Cost); Console.WriteLine(); } } }
Java
UTF-8
2,035
2.046875
2
[]
no_license
/* * Copyright (c) 2016 Tata Consultancy Services and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.centinel.impl.ipfix; import java.util.ArrayList; import java.util.List; public class IPFIXSetsDAO extends PacketLength { private List<DataSetRecord> dataRecords = new ArrayList<DataSetRecord>(); private List<TemplateRecord> templateRecords = new ArrayList<TemplateRecord>(); private List<OptionTemplateRecord> optionTemplateRecords = new ArrayList<OptionTemplateRecord>(); private final static int SETHEADERLENGTH = 4; private int setID; public int getSetID() { return setID; } public void setSetID(int setID) { this.setID = setID; } public List<DataSetRecord> getDataRecords() { return dataRecords; } public void setDataRecords(List<DataSetRecord> dataRecords) { this.dataRecords = dataRecords; updateLength(); } public List<TemplateRecord> getTemplateRecords() { return templateRecords; } public void setTemplateRecords(List<TemplateRecord> templateRecords) { this.templateRecords = templateRecords; updateLength(); } public List<OptionTemplateRecord> getOptionTemplateRecords() { return optionTemplateRecords; } public void setOptionTemplateRecords(List<OptionTemplateRecord> optionTemplateRecords) { this.optionTemplateRecords = optionTemplateRecords; updateLength(); } private void updateLength() { int newLength = SETHEADERLENGTH; for (TemplateRecord template : templateRecords) { newLength += template.getLength(); } for (DataSetRecord record : dataRecords) { newLength += record.getLength(); } this.length = newLength; } }
Markdown
UTF-8
2,932
3.3125
3
[]
no_license
# 简单配置Redux.md ### App.js(redux的设置) ```js import React, { Component } from 'react'; import './App.css'; import { HashRouter as Router, Route, Link } from "react-router-dom"; import Xheader from './page/Xheader.jsx' import Xlist from './page/Xlist.jsx' //先安装react-redux和redux,然后引入redux依赖 import { Provider } from 'react-redux'; import { createStore } from 'redux'; //创建state仓库 const store =createStore((state = { count: 0, name:'aaa', age:'10' }, action) { //判断action.type switch (action.type) { case 'increase': //推荐写法,返回值会直接更新state仓库,如果只返回state.count=10,则state仓库的其他数据将会被覆盖 return { ...state, count: state.count + 2 } case 'multi': return Object.assign({}, state, { name: action.name }); default: return state } }) class App extends Component { state = { num: 10 } render() { return ( //要用Provider标签套着,把仓库设置store加载到其属性上, 原理:把仓库store放到父context(不懂可以回去看基础-老谢的context的定义), 利用react自带的context加上redux的reducer和state的设置组合成react-redux <Provider store={store}> <Router> <div> <ul> <li><Link to="/">Xheader</Link></li> <li><Link to={`/about/${this.state.num}`}>Xlist</Link></li> </ul> <hr /> <Route exact path="/" component={Xheader} /> <Route path="/about/:idx" component={Xlist} /> </div> </Router> </Provider> ); } } export default App; ``` ### Xheader.jsx(子组件映射) ```jsx import React from 'react'; //引入依赖 import { connect } from 'react-redux'; class Xheader extends React.Component { render() { return ( <div> <h2>Xheader</h2> //获取仓库的值 <h4>{this.props.count}</h4> //点击后触发下面定义的方法onIncreaseClick <button onClick={this.props.onIncreaseClick}>点击</button> </div> ) } } //connect要传两个函数,1.返回仓库中的所有值或指定值。2.定义方法onIncreaseClick,触发dispatch仓库中的type:'increase'的case。 //第一个函数映射state用于获取仓库的值。第二个函数映射dispatch用于修改仓库的值 export default connect((state) => { return state }, (dispatch) => { return {onIncreaseClick: () => { dispatch({type:'increase'}) },onTest(){ //可以触发多个仓库中的case。在仓库中通过action.test获取参数'lalala' dispatch({type:'仓库中没有这个action.type',test:'lalala'}) dispatch({type:'仓库中没有这个action.type',test:'hahaha'}) }} })(Xheader) ```
Markdown
UTF-8
1,558
3.046875
3
[]
no_license
# Item Catalog ## About This is the fourth project in the Full Stack Web Developer Nanodegree program from Udacity. The project is a web application item catalog allowing authenticated users to perform CRUD operations within a relational database. A google+ OAuth 2.0 sign in is used to authenticate users. Authenticated Users can create, update and delete items from the catalog using a local permissioin system allowing only users that created an item or category to edit or delete that item. JSON endpoints are provided for all items in the database with their respective HTTP links. The app is built with the Flask web framework and uses a SQLite database. The webpages are styled with the bootstrap CSS framework. ## Requirements * Python 2 ## Installation Instructions 1. install virtualenv `sudo pip install virtualenv` article explaining virtualenv and its importance: https://www.dabapps.com/blog/introduction-to-pip-and-virtualenv-python/ 2. clone this repository `git clone https://github.com/dylance/Udacity-FSND-Project4` 3. change directory into git repo `cd Udacity-FSND-Project4` 4. create local virtualenv environment `virtualenv venv` 5. activate virtualenv environment `source venv/bin/activate` 6. install dependencies `pip install --editable .` 7. change directory into item_catalog `cd item_catalog` 8. set up db `python database_setup.py` 9. add default categories to database (optional) `python add_categories.py` 10. run server `python server.py` 11. view web app in browser at localhost:8000/ ## Creator Dylan Ellison
Markdown
UTF-8
92,813
2.578125
3
[]
no_license
# SPD (S&D) <p align="center"><a href="#voting-intentions">Voting Intentions</a> | <a href="#seats">Seats</a></p> ## Voting Intentions Last result: **27.3%** (General Election of 25 May 2014) ### Confidence Intervals | Period | Polling firm/Commissioner(s) | Median | 80% Confidence Interval | 90% Confidence Interval | 95% Confidence Interval | 99% Confidence Interval | |:----------:|:----------------:|:-----------:|:-----------------------:|:-----------------------:|:-----------------------:|:-----------------------:| | N/A | [Poll Average](average.html) | 16.9% | 15.4–18.6% | 15.0–19.0% | 14.7–19.3% | 14.2–20.0% | | [20–23 May 2019](2019-05-23-ForschungsgruppeWahlen.html) | Forschungsgruppe Wahlen <br> ZDF | 17.9% | 16.8–19.1% | 16.4–19.4% | 16.2–19.7% | 15.6–20.3% | | [17–20 May 2019](2019-05-20-INSA.html) | INSA | 18.0% | 16.9–19.1% | 16.6–19.4% | 16.4–19.7% | 15.9–20.3% | | [13–17 May 2019](2019-05-17-Forsa.html) | Forsa | 16.0% | 15.0–17.1% | 14.7–17.4% | 14.4–17.7% | 13.9–18.2% | | [14–16 May 2019](2019-05-16-ForschungsgruppeWahlen.html) | Forschungsgruppe Wahlen <br> ZDF | 17.0% | 15.7–18.4% | 15.3–18.8% | 15.0–19.1% | 14.4–19.8% | | [14–15 May 2019](2019-05-15-Infratestdimap.html) | Infratest dimap <br> ARD | 17.3% | 16.1–18.7% | 15.8–19.0% | 15.5–19.3% | 15.0–20.0% | | [10–13 May 2019](2019-05-13-INSAandYouGov.html) | INSA and YouGov <br> Bild | 16.1% | 15.0–17.1% | 14.7–17.4% | 14.5–17.7% | 14.0–18.2% | | [6–10 May 2019](2019-05-10-Forsa.html) | Forsa <br> Stern and RTL | 15.0% | 14.1–15.9% | 13.9–16.2% | 13.6–16.4% | 13.2–16.9% | | [7–9 May 2019](2019-05-09-ForschungsgruppeWahlen.html) | Forschungsgruppe Wahlen <br> ZDF | 16.1% | 14.9–17.5% | 14.5–17.9% | 14.2–18.3% | 13.6–18.9% | | [2–8 May 2019](2019-05-08-GMS.html) | GMS | 17.0% | 15.5–18.6% | 15.2–19.1% | 14.8–19.4% | 14.1–20.2% | | [2–8 May 2019](2019-05-08-Emnid.html) | Emnid <br> Bild am Sonntag | 16.0% | 15.1–17.0% | 14.8–17.3% | 14.6–17.5% | 14.1–18.0% | | [3 April–6 May 2019](2019-05-06-INSAandYouGov.html) | INSA and YouGov <br> Bild | 15.9% | 15.0–17.0% | 14.7–17.3% | 14.4–17.6% | 14.0–18.1% | | [29 April–3 May 2019](2019-05-03-Forsa.html) | Forsa <br> Stern and RTL | 15.0% | 13.9–16.2% | 13.5–16.6% | 13.3–16.9% | 12.8–17.5% | | [29–30 April 2019](2019-04-30-Infratestdimap.html) | Infratest dimap <br> ARD | 19.0% | 17.8–20.4% | 17.4–20.7% | 17.1–21.1% | 16.5–21.7% | | [25–30 April 2019](2019-04-30-Emnid.html) | Emnid <br> Bild am Sonntag | 17.0% | 16.0–18.2% | 15.7–18.5% | 15.4–18.8% | 14.9–19.4% | | [26–29 April 2019](2019-04-29-YouGov.html) | YouGov <br> RedaktionsNetzwerk Deutschland | 18.0% | 16.9–19.3% | 16.5–19.7% | 16.2–20.0% | 15.7–20.6% | | [26–29 April 2019](2019-04-29-INSAandYouGov.html) | INSA and YouGov <br> Bild | 16.0% | 15.0–17.1% | 14.7–17.4% | 14.5–17.7% | 14.0–18.2% | | [23–26 April 2019](2019-04-26-Forsa.html) | Forsa <br> Stern and RTL | 17.0% | 15.8–18.3% | 15.5–18.7% | 15.2–19.0% | 14.6–19.6% | | [18–24 April 2019](2019-04-24-Emnid.html) | Emnid <br> Bild am Sonntag | 17.0% | 15.8–18.4% | 15.5–18.7% | 15.2–19.1% | 14.6–19.7% | | [18–21 April 2019](2019-04-21-INSAandYouGov.html) | INSA and YouGov <br> Bild | 16.0% | 14.6–17.6% | 14.2–18.0% | 13.9–18.4% | 13.2–19.2% | | [15–18 April 2019](2019-04-18-Forsa.html) | Forsa <br> Stern and RTL | 17.0% | 15.8–18.3% | 15.5–18.6% | 15.2–18.9% | 14.6–19.6% | | [11–17 April 2019](2019-04-17-Emnid.html) | Emnid <br> Bild am Sonntag | 18.0% | 17.1–19.0% | 16.8–19.3% | 16.6–19.5% | 16.2–20.0% | | [12–15 April 2019](2019-04-15-INSAandYouGov.html) | INSA and YouGov <br> Bild | 15.5% | 14.5–16.6% | 14.2–16.9% | 14.0–17.1% | 13.5–17.7% | | [8–12 April 2019](2019-04-12-Forsa.html) | Forsa <br> Stern and RTL | 16.0% | 15.0–17.1% | 14.7–17.4% | 14.4–17.7% | 13.9–18.3% | | [1–12 April 2019](2019-04-12-Allensbach.html) | Allensbach <br> Frankfurter Allgemeine Zeitung | 18.5% | 17.1–19.9% | 16.8–20.3% | 16.4–20.7% | 15.8–21.4% | | [9–11 April 2019](2019-04-11-ForschungsgruppeWahlen.html) | Forschungsgruppe Wahlen <br> ZDF | 18.0% | 16.7–19.5% | 16.3–19.9% | 16.0–20.2% | 15.4–20.9% | | [10 April 2019](2019-04-10-Emnid.html) | Emnid <br> Bild am Sonntag | 17.0% | 16.1–18.0% | 15.8–18.3% | 15.6–18.5% | 15.2–19.0% | | [5–8 April 2019](2019-04-08-INSAandYouGov.html) | INSA and YouGov <br> Bild | 15.5% | 14.5–16.6% | 14.2–16.9% | 14.0–17.1% | 13.5–17.7% | | [1–5 April 2019](2019-04-05-Forsa.html) | Forsa <br> Stern and RTL | 16.0% | 14.9–17.1% | 14.6–17.5% | 14.4–17.7% | 13.9–18.3% | | [1–3 April 2019](2019-04-03-Infratestdimap.html) | Infratest dimap <br> ARD | 17.0% | 15.8–18.3% | 15.5–18.7% | 15.2–19.0% | 14.7–19.7% | | [28 March–3 April 2019](2019-04-03-GMS.html) | GMS | 15.0% | 13.6–16.5% | 13.2–16.9% | 12.9–17.3% | 12.3–18.1% | | [28 March–3 April 2019](2019-04-03-Emnid.html) | Emnid <br> Bild am Sonntag | 17.0% | 16.0–18.0% | 15.8–18.3% | 15.5–18.6% | 15.1–19.1% | | [28 March–1 April 2019](2019-04-01-INSAandYouGov.html) | INSA and YouGov <br> Bild | 16.5% | 15.8–17.3% | 15.5–17.5% | 15.4–17.7% | 15.0–18.1% | | [25–29 March 2019](2019-03-29-Forsa.html) | Forsa <br> Stern and RTL | 16.0% | 14.9–17.1% | 14.6–17.5% | 14.4–17.7% | 13.9–18.3% | | [25–27 March 2019](2019-03-27-ForschungsgruppeWahlen.html) | Forschungsgruppe Wahlen <br> ZDF | 18.0% | 16.7–19.5% | 16.4–19.9% | 16.0–20.2% | 15.5–20.9% | | [21–27 March 2019](2019-03-27-Emnid.html) | Emnid <br> Bild am Sonntag | 16.0% | 15.1–17.0% | 14.8–17.3% | 14.6–17.6% | 14.1–18.0% | | [22–26 March 2019](2019-03-26-YouGov.html) | YouGov <br> RedaktionsNetzwerk Deutschland | 18.0% | 16.8–19.3% | 16.5–19.6% | 16.2–20.0% | 15.7–20.6% | | [18–22 March 2019](2019-03-22-Forsa.html) | Forsa <br> Stern and RTL | 16.0% | 14.9–17.1% | 14.6–17.5% | 14.4–17.7% | 13.9–18.3% | | [7–21 March 2019](2019-03-21-Allensbach.html) | Allensbach <br> Frankfurter Allgemeine Zeitung | 18.0% | 16.7–19.5% | 16.3–20.0% | 15.9–20.3% | 15.3–21.0% | | [14–20 March 2019](2019-03-20-Emnid.html) | Emnid <br> Bild am Sonntag | 17.0% | 15.8–18.3% | 15.5–18.7% | 15.2–19.0% | 14.6–19.6% | | [11–15 March 2019](2019-03-15-Forsa.html) | Forsa <br> Stern and RTL | 15.0% | 14.0–16.1% | 13.7–16.4% | 13.5–16.7% | 13.0–17.2% | | [12–14 March 2019](2019-03-14-ForschungsgruppeWahlen.html) | Forschungsgruppe Wahlen <br> ZDF | 18.0% | 16.7–19.4% | 16.3–19.8% | 16.0–20.2% | 15.4–20.9% | | [11–13 March 2019](2019-03-13-Infratestdimap.html) | Infratest dimap <br> ARD | 19.0% | 17.8–20.4% | 17.4–20.8% | 17.1–21.1% | 16.5–21.8% | | [7–13 March 2019](2019-03-13-Emnid.html) | Emnid <br> Bild am Sonntag | 16.0% | 15.0–17.1% | 14.7–17.5% | 14.4–17.7% | 13.9–18.3% | | [4–8 March 2019](2019-03-08-Forsa.html) | Forsa <br> Stern and RTL | 15.0% | 14.0–16.1% | 13.7–16.4% | 13.5–16.7% | 13.0–17.2% | | [28 February–6 March 2019](2019-03-06-Emnid.html) | Emnid <br> Bild am Sonntag | 17.0% | 15.9–18.2% | 15.6–18.5% | 15.4–18.8% | 14.9–19.3% | | [27 February–1 March 2019](2019-03-01-INSAandYouGov.html) | INSA and YouGov <br> Bild | 16.0% | 16.2–17.8% | 16.0–18.0% | 15.9–18.2% | 15.5–18.6% | | [27 February–1 March 2019](2019-03-01-INSA.html) | INSA <br> SWG | 16.0% | 15.3–16.8% | 15.1–17.0% | 14.9–17.2% | 14.6–17.5% | | [25 February–1 March 2019](2019-03-01-Forsa.html) | Forsa <br> Stern and RTL | 16.0% | 15.1–17.0% | 14.8–17.2% | 14.6–17.5% | 14.2–18.0% | | [21–27 February 2019](2019-02-27-GMS.html) | GMS | 16.0% | 14.6–17.6% | 14.2–18.0% | 13.9–18.4% | 13.2–19.2% | | [21–27 February 2019](2019-02-27-Emnid.html) | Emnid <br> Bild am Sonntag | 18.0% | 16.8–19.4% | 16.4–19.8% | 16.1–20.1% | 15.5–20.8% | | [22–26 February 2019](2019-02-26-YouGov.html) | YouGov <br> RedaktionsNetzwerk Deutschland | 18.0% | 16.8–19.3% | 16.5–19.7% | 16.2–20.0% | 15.7–20.6% | | [22–25 February 2019](2019-02-25-INSAandYouGov.html) | INSA and YouGov <br> Bild | 18.0% | 17.0–19.2% | 16.7–19.5% | 16.4–19.8% | 15.9–20.3% | | [18–22 February 2019](2019-02-22-Forsa.html) | Forsa <br> Stern and RTL | 16.0% | 14.9–17.1% | 14.6–17.5% | 14.4–17.7% | 13.9–18.3% | | [19–21 February 2019](2019-02-21-ForschungsgruppeWahlen.html) | Forschungsgruppe Wahlen <br> ZDF | 18.0% | 16.7–19.5% | 16.3–19.9% | 16.0–20.3% | 15.3–21.0% | | [14–20 February 2019](2019-02-20-Emnid.html) | Emnid <br> Bild am Sonntag | 19.0% | 17.7–20.3% | 17.4–20.7% | 17.1–21.1% | 16.5–21.7% | | [15–18 February 2019](2019-02-18-INSAandYouGov.html) | INSA and YouGov <br> Bild | 18.0% | 16.9–19.1% | 16.6–19.4% | 16.4–19.7% | 15.9–20.3% | | [11–15 February 2019](2019-02-15-Forsa.html) | Forsa <br> Stern and RTL | 17.0% | 15.9–18.2% | 15.6–18.5% | 15.4–18.8% | 14.9–19.3% | | [11–13 February 2019](2019-02-13-Infratestdimap.html) | Infratest dimap <br> ARD | 18.0% | 16.8–19.4% | 16.5–19.7% | 16.2–20.1% | 15.6–20.7% | | [7–13 February 2019](2019-02-13-Emnid.html) | Emnid <br> Bild am Sonntag | 19.0% | 17.9–20.2% | 17.5–20.5% | 17.3–20.8% | 16.8–21.4% | | [1–13 February 2019](2019-02-13-Allensbach.html) | Allensbach <br> Frankfurter Allgemeine Zeitung | 18.0% | 16.6–19.5% | 16.3–19.9% | 15.9–20.3% | 15.3–21.0% | | [8–11 February 2019](2019-02-11-INSAandYouGov.html) | INSA and YouGov <br> Bild | 15.4% | 14.4–16.5% | 14.1–16.8% | 13.9–17.0% | 13.4–17.6% | | [4–8 February 2019](2019-02-08-Forsa.html) | Forsa <br> Stern and RTL | 15.0% | 14.0–16.1% | 13.7–16.4% | 13.5–16.7% | 13.0–17.2% | | [5–7 February 2019](2019-02-07-ForschungsgruppeWahlen.html) | Forschungsgruppe Wahlen <br> ZDF | 16.0% | 14.8–17.3% | 14.4–17.7% | 14.1–18.1% | 13.6–18.7% | | [31 January–6 February 2019](2019-02-06-Emnid.html) | Emnid <br> Bild am Sonntag | 17.0% | 15.9–18.2% | 15.6–18.5% | 15.4–18.8% | 14.9–19.3% | | [1–4 February 2019](2019-02-04-INSAandYouGov.html) | INSA and YouGov <br> Bild | 14.5% | 13.5–15.6% | 13.3–15.9% | 13.0–16.1% | 12.6–16.6% | | [28 January–1 February 2019](2019-02-01-Forsa.html) | Forsa <br> Stern and RTL | 15.0% | 14.0–16.1% | 13.7–16.4% | 13.4–16.7% | 13.0–17.2% | | [24–30 January 2019](2019-01-30-Emnid.html) | Emnid <br> Bild am Sonntag | 16.0% | 14.8–17.3% | 14.4–17.6% | 14.2–18.0% | 13.6–18.6% | | [25–29 January 2019](2019-01-29-YouGov.html) | YouGov <br> RedaktionsNetzwerk Deutschland | 15.0% | 13.9–16.2% | 13.6–16.6% | 13.3–16.9% | 12.8–17.5% | | [25–28 January 2019](2019-01-28-INSAandYouGov.html) | INSA and YouGov <br> Bild | 15.0% | 14.0–16.0% | 13.7–16.3% | 13.5–16.6% | 13.0–17.1% | | [21–25 January 2019](2019-01-25-Forsa.html) | Forsa <br> Stern and RTL | 14.0% | 13.0–15.1% | 12.7–15.4% | 12.5–15.6% | 12.0–16.2% | | [22–24 January 2019](2019-01-24-ForschungsgruppeWahlen.html) | Forschungsgruppe Wahlen <br> ZDF | 14.0% | 12.8–15.3% | 12.5–15.7% | 12.2–16.0% | 11.7–16.7% | | [22–23 January 2019](2019-01-23-Infratestdimap.html) | Infratest dimap <br> ARD | 15.0% | 13.7–16.5% | 13.3–17.0% | 13.0–17.3% | 12.4–18.1% | | [16–23 January 2019](2019-01-23-GMS.html) | GMS | 14.0% | 12.6–15.5% | 12.3–15.9% | 11.9–16.2% | 11.3–17.0% | | [17–23 January 2019](2019-01-23-Emnid.html) | Emnid <br> Bild am Sonntag | 16.0% | 15.0–17.1% | 14.7–17.4% | 14.5–17.7% | 14.0–18.2% | | [18–21 January 2019](2019-01-21-INSAandYouGov.html) | INSA and YouGov <br> Bild | 13.5% | 12.6–14.5% | 12.3–14.8% | 12.1–15.1% | 11.6–15.6% | | [14–18 January 2019](2019-01-18-Forsa.html) | Forsa <br> Stern and RTL | 15.0% | 14.0–16.1% | 13.7–16.4% | 13.4–16.7% | 13.0–17.2% | | [5–17 January 2019](2019-01-17-Allensbach.html) | Allensbach <br> Frankfurter Allgemeine Zeitung | 16.5% | 15.2–17.9% | 14.8–18.3% | 14.5–18.7% | 13.9–19.4% | | [10–16 January 2019](2019-01-16-Emnid.html) | Emnid <br> Bild am Sonntag | 15.0% | 13.8–16.2% | 13.5–16.6% | 13.2–16.9% | 12.7–17.5% | | [11–14 January 2019](2019-01-14-INSAandYouGov.html) | INSA and YouGov <br> Bild | 14.5% | 13.5–15.5% | 13.3–15.9% | 13.0–16.1% | 12.6–16.6% | | [9–11 January 2019](2019-01-11-Forsa.html) | Forsa <br> Stern and RTL | 15.0% | 13.9–16.3% | 13.6–16.6% | 13.3–16.9% | 12.8–17.5% | | [8–10 January 2019](2019-01-10-ForschungsgruppeWahlen.html) | Forschungsgruppe Wahlen <br> ZDF | 14.0% | 12.8–15.3% | 12.5–15.7% | 12.2–16.0% | 11.6–16.6% | | [7–9 January 2019](2019-01-09-Infratestdimap.html) | Infratest dimap <br> ARD | 15.0% | 13.9–16.3% | 13.6–16.6% | 13.3–16.9% | 12.8–17.5% | | [3–9 January 2019](2019-01-09-Emnid.html) | Emnid <br> Bild am Sonntag | 15.0% | 14.0–16.1% | 13.7–16.4% | 13.5–16.7% | 13.0–17.2% | | [5–7 January 2019](2019-01-07-INSAandYouGov.html) | INSA and YouGov <br> Bild | 14.3% | 13.4–15.3% | 13.1–15.6% | 12.8–15.9% | 12.4–16.4% | | [2–4 January 2019](2019-01-04-Forsa.html) | Forsa <br> Stern and RTL | 15.0% | 13.7–16.4% | 13.3–16.8% | 13.0–17.2% | 12.4–17.9% | | [2–3 January 2019](2019-01-03-INSAandYouGov.html) | INSA and YouGov <br> Bild | 15.0% | 13.6–16.5% | 13.2–16.9% | 12.9–17.3% | 12.3–18.0% | | [21–27 December 2018](2018-12-27-YouGov.html) | YouGov <br> RedaktionsNetzwerk Deutschland | 16.0% | 14.9–17.2% | 14.6–17.5% | 14.3–17.8% | 13.8–18.4% | | [20–21 December 2018](2018-12-21-INSAandYouGov.html) | INSA and YouGov <br> Bild | 14.0% | 12.7–15.5% | 12.3–15.9% | 12.0–16.3% | 11.4–17.0% | | [17–21 December 2018](2018-12-21-Forsa.html) | Forsa <br> Stern and RTL | 14.0% | 13.0–15.0% | 12.7–15.3% | 12.5–15.6% | 12.0–16.1% | | [13–19 December 2018](2018-12-19-Emnid.html) | Emnid <br> Bild am Sonntag | 15.0% | 14.0–16.1% | 13.7–16.4% | 13.4–16.7% | 13.0–17.2% | | [14–17 December 2018](2018-12-17-INSAandYouGov.html) | INSA and YouGov <br> Bild | 15.0% | 14.1–16.1% | 13.8–16.4% | 13.5–16.6% | 13.1–17.1% | | [10–14 December 2018](2018-12-14-Forsa.html) | Forsa <br> Stern and RTL | 15.0% | 14.0–16.1% | 13.7–16.4% | 13.5–16.7% | 13.0–17.2% | | [11–13 December 2018](2018-12-13-ForschungsgruppeWahlen.html) | Forschungsgruppe Wahlen <br> ZDF | 15.0% | 13.8–16.3% | 13.4–16.7% | 13.1–17.1% | 12.6–17.7% | | [11–12 December 2018](2018-12-12-Infratestdimap.html) | Infratest dimap <br> ARD | 15.0% | 13.6–16.5% | 13.3–16.9% | 12.9–17.3% | 12.3–18.0% | | [6–12 December 2018](2018-12-12-GMS.html) | GMS | 14.0% | 12.7–15.5% | 12.3–16.0% | 12.0–16.3% | 11.4–17.1% | | [6–12 December 2018](2018-12-12-Emnid.html) | Emnid <br> Bild am Sonntag | 15.0% | 14.0–16.1% | 13.7–16.4% | 13.5–16.7% | 13.1–17.2% | | [1–12 December 2018](2018-12-12-Allensbach.html) | Allensbach <br> Frankfurter Allgemeine Zeitung | 16.5% | 15.3–17.9% | 14.9–18.3% | 14.6–18.7% | 14.0–19.3% | | [8–10 December 2018](2018-12-10-INSAandYouGov.html) | INSA and YouGov <br> Bild | 16.5% | 15.5–17.6% | 15.2–17.9% | 15.0–18.2% | 14.5–18.7% | | [7–9 December 2018](2018-12-09-Forsa.html) | Forsa <br> Stern and RTL | 14.0% | 12.8–15.4% | 12.5–15.8% | 12.2–16.2% | 11.6–16.8% | | [3–6 December 2018](2018-12-06-Forsa.html) | Forsa <br> Stern and RTL | 14.0% | 13.0–15.1% | 12.8–15.3% | 12.5–15.6% | 12.1–16.1% | | [3–5 December 2018](2018-12-05-Infratestdimap.html) | Infratest dimap <br> ARD | 14.0% | 12.9–15.2% | 12.6–15.5% | 12.3–15.8% | 11.8–16.4% | | [29 November–5 December 2018](2018-12-05-Emnid.html) | Emnid <br> Bild am Sonntag | 15.0% | 14.1–15.9% | 13.8–16.2% | 13.6–16.5% | 13.2–16.9% | | [30 November–3 December 2018](2018-12-03-INSAandYouGov.html) | INSA and YouGov <br> Bild | 13.5% | 12.6–14.5% | 12.3–14.8% | 12.1–15.0% | 11.6–15.5% | | [26–30 November 2018](2018-11-30-Forsa.html) | Forsa <br> Stern and RTL | 14.0% | 13.0–15.1% | 12.8–15.4% | 12.5–15.7% | 12.1–16.2% | | [27–28 November 2018](2018-11-28-Infratestdimap.html) | Infratest dimap <br> ARD | 14.0% | 12.7–15.4% | 12.3–15.9% | 12.0–16.2% | 11.4–16.9% | | [22–28 November 2018](2018-11-28-Emnid.html) | Emnid <br> Bild am Sonntag | 15.0% | 13.9–16.3% | 13.6–16.6% | 13.3–16.9% | 12.8–17.5% | | [23–27 November 2018](2018-11-27-YouGov.html) | YouGov <br> RedaktionsNetzwerk Deutschland | 15.0% | 13.9–16.2% | 13.6–16.6% | 13.3–16.9% | 12.8–17.5% | | [23–26 November 2018](2018-11-26-INSAandYouGov.html) | INSA and YouGov <br> Bild | 14.0% | 13.1–15.0% | 12.8–15.3% | 12.6–15.6% | 12.1–16.1% | | [19–23 November 2018](2018-11-23-Forsa.html) | Forsa <br> Stern and RTL | 14.0% | 13.0–15.0% | 12.8–15.3% | 12.5–15.6% | 12.1–16.1% | | [20–22 November 2018](2018-11-22-ForschungsgruppeWahlen.html) | Forschungsgruppe Wahlen <br> ZDF | 14.0% | 12.8–15.3% | 12.5–15.7% | 12.2–16.0% | 11.7–16.6% | | [15–21 November 2018](2018-11-21-Emnid.html) | Emnid <br> Bild am Sonntag | 15.0% | 14.1–16.0% | 13.8–16.3% | 13.6–16.5% | 13.2–17.0% | | [16–19 November 2018](2018-11-19-INSAandYouGov.html) | INSA and YouGov <br> Bild | 14.5% | 13.5–15.6% | 13.3–15.9% | 13.0–16.1% | 12.6–16.6% | | [12–16 November 2018](2018-11-16-Forsa.html) | Forsa <br> Stern and RTL | 14.0% | 13.0–15.1% | 12.7–15.4% | 12.5–15.6% | 12.0–16.2% | | [12–14 November 2018](2018-11-14-Infratestdimap.html) | Infratest dimap <br> ARD | 14.0% | 12.9–15.2% | 12.6–15.6% | 12.3–15.9% | 11.8–16.5% | | [8–14 November 2018](2018-11-14-Emnid.html) | Emnid <br> Bild am Sonntag | 15.0% | 14.0–16.1% | 13.7–16.4% | 13.5–16.6% | 13.0–17.2% | | [9–12 November 2018](2018-11-12-INSAandYouGov.html) | INSA and YouGov <br> Bild | 14.2% | 13.2–15.2% | 12.9–15.5% | 12.7–15.7% | 12.3–16.2% | | [5–9 November 2018](2018-11-09-Forsa.html) | Forsa <br> Stern and RTL | 14.0% | 13.0–15.1% | 12.8–15.4% | 12.5–15.6% | 12.1–16.2% | | [6–8 November 2018](2018-11-08-ForschungsgruppeWahlen.html) | Forschungsgruppe Wahlen <br> ZDF | 14.0% | 12.8–15.4% | 12.4–15.7% | 12.1–16.1% | 11.6–16.8% | | [5–7 November 2018](2018-11-07-Emnid.html) | Emnid <br> Bild am Sonntag | 15.0% | 13.9–16.3% | 13.6–16.6% | 13.3–16.9% | 12.8–17.5% | | [2–5 November 2018](2018-11-05-INSAandYouGov.html) | INSA and YouGov <br> Bild | 13.7% | 12.9–14.5% | 12.7–14.8% | 12.5–15.0% | 12.2–15.4% | | [28 October–4 November 2018](2018-11-04-YouGov.html) | YouGov <br> RedaktionsNetzwerk Deutschland | 14.0% | 12.9–15.2% | 12.6–15.5% | 12.4–15.8% | 11.9–16.4% | | [29 October–2 November 2018](2018-11-02-Forsa.html) | Forsa <br> Stern and RTL | 13.0% | 12.0–14.0% | 11.8–14.3% | 11.5–14.6% | 11.1–15.1% | | [25–31 October 2018](2018-10-31-Emnid.html) | Emnid <br> Bild am Sonntag | 14.0% | 13.0–15.1% | 12.7–15.4% | 12.5–15.7% | 12.0–16.2% | | [26–29 October 2018](2018-10-29-INSAandYouGov.html) | INSA and YouGov <br> Bild | 14.0% | 13.0–15.0% | 12.8–15.3% | 12.5–15.6% | 12.1–16.1% | | [22–26 October 2018](2018-10-26-Forsa.html) | Forsa <br> Stern and RTL | 14.0% | 13.1–14.9% | 12.9–15.2% | 12.7–15.4% | 12.3–15.9% | | [18–24 October 2018](2018-10-24-Emnid.html) | Emnid <br> Bild am Sonntag | 15.0% | 14.0–16.1% | 13.7–16.4% | 13.5–16.7% | 13.0–17.2% | | [19–22 October 2018](2018-10-22-INSAandYouGov.html) | INSA and YouGov <br> Bild | 16.0% | 14.8–17.4% | 14.4–17.8% | 14.1–18.2% | 13.5–18.9% | | [15–19 October 2018](2018-10-19-Forsa.html) | Forsa <br> Stern and RTL | 14.0% | 13.0–15.1% | 12.7–15.4% | 12.5–15.7% | 12.0–16.2% | | [16–18 October 2018](2018-10-18-ForschungsgruppeWahlen.html) | Forschungsgruppe Wahlen <br> ZDF | 14.0% | 12.7–15.4% | 12.3–15.8% | 12.1–16.1% | 11.5–16.8% | | [16–17 October 2018](2018-10-17-Infratestdimap.html) | Infratest dimap <br> ARD | 14.0% | 12.7–15.5% | 12.4–15.9% | 12.1–16.3% | 11.5–17.0% | | [11–17 October 2018](2018-10-17-Emnid.html) | Emnid <br> Bild am Sonntag | 15.0% | 13.9–16.2% | 13.6–16.5% | 13.3–16.8% | 12.8–17.4% | | [12–15 October 2018](2018-10-15-INSAandYouGov.html) | INSA and YouGov <br> Bild | 15.0% | 14.0–16.0% | 13.7–16.4% | 13.5–16.6% | 13.1–17.1% | | [8–12 October 2018](2018-10-12-Forsa.html) | Forsa <br> Stern and RTL | 16.0% | 14.9–17.1% | 14.6–17.5% | 14.3–17.8% | 13.8–18.3% | | [28 September–11 October 2018](2018-10-11-Allensbach.html) | Allensbach <br> Frankfurter Allgemeine Zeitung | 19.0% | 17.6–20.5% | 17.2–20.9% | 16.9–21.2% | 16.3–22.0% | | [8–10 October 2018](2018-10-10-Infratestdimap.html) | Infratest dimap <br> ARD | 15.0% | 13.9–16.2% | 13.5–16.6% | 13.3–16.9% | 12.7–17.5% | | [4–10 October 2018](2018-10-10-GMS.html) | GMS | 15.0% | 13.6–16.5% | 13.2–17.0% | 12.9–17.3% | 12.3–18.1% | | [4–10 October 2018](2018-10-10-Emnid.html) | Emnid <br> Bild am Sonntag | 17.0% | 15.9–18.2% | 15.6–18.5% | 15.4–18.8% | 14.9–19.3% | | [5–8 October 2018](2018-10-08-INSAandYouGov.html) | INSA and YouGov <br> Bild | 16.0% | 15.0–17.1% | 14.7–17.4% | 14.5–17.7% | 14.0–18.2% | | [1–5 October 2018](2018-10-05-Forsa.html) | Forsa <br> Stern and RTL | 16.0% | 14.8–17.3% | 14.4–17.6% | 14.2–18.0% | 13.6–18.6% | | [27 September–2 October 2018](2018-10-02-Emnid.html) | Emnid <br> Bild am Sonntag | 17.0% | 15.8–18.3% | 15.5–18.7% | 15.2–19.0% | 14.7–19.6% | | [28 September–1 October 2018](2018-10-01-INSAandYouGov.html) | INSA and YouGov <br> Bild | 16.0% | 15.0–17.1% | 14.7–17.4% | 14.5–17.7% | 14.0–18.2% | | [24–28 September 2018](2018-09-28-Forsa.html) | Forsa <br> Stern and RTL | 16.0% | 14.9–17.2% | 14.6–17.5% | 14.3–17.8% | 13.8–18.4% | | [25–27 September 2018](2018-09-27-ForschungsgruppeWahlen.html) | Forschungsgruppe Wahlen <br> ZDF | 17.0% | 15.7–18.4% | 15.3–18.8% | 15.0–19.2% | 14.4–19.9% | | [20–26 September 2018](2018-09-26-GMS.html) | GMS | 16.0% | 14.6–17.6% | 14.2–18.0% | 13.9–18.4% | 13.2–19.2% | | [20–26 September 2018](2018-09-26-Emnid.html) | Emnid <br> Bild am Sonntag | 16.0% | 14.9–17.1% | 14.6–17.4% | 14.4–17.7% | 13.9–18.3% | | [21–25 September 2018](2018-09-25-YouGov.html) | YouGov <br> RedaktionsNetzwerk Deutschland | 17.0% | 15.8–18.3% | 15.5–18.7% | 15.2–19.0% | 14.6–19.6% | | [21–24 September 2018](2018-09-24-INSAandYouGov.html) | INSA and YouGov <br> Bild | 16.0% | 15.0–17.1% | 14.7–17.4% | 14.5–17.6% | 14.0–18.2% | | [17–21 September 2018](2018-09-21-Forsa.html) | Forsa <br> Stern and RTL | 17.0% | 15.9–18.2% | 15.5–18.5% | 15.3–18.8% | 14.8–19.4% | | [17–19 September 2018](2018-09-19-Infratestdimap.html) | Infratest dimap <br> ARD | 17.0% | 15.6–18.6% | 15.2–19.0% | 14.8–19.4% | 14.2–20.2% | | [19 September 2018](2018-09-19-INSA.html) | INSA <br> Focus | 16.5% | 15.1–18.1% | 14.7–18.5% | 14.4–18.9% | 13.7–19.7% | | [13–19 September 2018](2018-09-19-Emnid.html) | Emnid <br> Bild am Sonntag | 17.0% | 16.0–18.0% | 15.8–18.3% | 15.5–18.6% | 15.1–19.1% | | [14–17 September 2018](2018-09-17-INSAandYouGov.html) | INSA and YouGov <br> Bild | 17.0% | 16.0–18.1% | 15.7–18.4% | 15.4–18.7% | 14.9–19.2% | | [10–14 September 2018](2018-09-14-Forsa.html) | Forsa <br> Stern and RTL | 18.0% | 16.9–19.2% | 16.6–19.5% | 16.3–19.8% | 15.8–20.4% | | [11–13 September 2018](2018-09-13-ForschungsgruppeWahlen.html) | Forschungsgruppe Wahlen <br> ZDF | 20.0% | 18.7–21.5% | 18.3–21.9% | 18.0–22.3% | 17.3–23.0% | | [1–13 September 2018](2018-09-13-Allensbach.html) | Allensbach <br> Frankfurter Allgemeine Zeitung | 19.5% | 18.1–21.0% | 17.7–21.4% | 17.4–21.8% | 16.7–22.5% | | [6–12 September 2018](2018-09-12-Emnid.html) | Emnid <br> Bild am Sonntag | 18.0% | 16.9–19.2% | 16.6–19.5% | 16.4–19.8% | 15.9–20.3% | | [7–10 September 2018](2018-09-10-INSAandYouGov.html) | INSA and YouGov <br> Bild | 17.0% | 16.0–18.1% | 15.7–18.4% | 15.4–18.7% | 14.9–19.2% | | [4–10 September 2018](2018-09-10-GMS.html) | GMS | 17.0% | 15.6–18.7% | 15.2–19.1% | 14.8–19.5% | 14.2–20.3% | | [3–7 September 2018](2018-09-07-Forsa.html) | Forsa <br> Stern and RTL | 16.0% | 15.0–17.2% | 14.6–17.5% | 14.4–17.8% | 13.9–18.3% | | [3–5 September 2018](2018-09-05-Infratestdimap.html) | Infratest dimap <br> ARD | 18.0% | 16.8–19.3% | 16.4–19.7% | 16.1–20.0% | 15.5–20.7% | | [30 August–5 September 2018](2018-09-05-Emnid.html) | Emnid <br> Bild am Sonntag | 17.0% | 16.0–18.0% | 15.8–18.3% | 15.6–18.5% | 15.1–19.0% | | [31 August–3 September 2018](2018-09-03-INSAandYouGov.html) | INSA and YouGov <br> Bild | 16.0% | 15.0–17.1% | 14.7–17.4% | 14.5–17.6% | 14.0–18.2% | | [27–31 August 2018](2018-08-31-Forsa.html) | Forsa <br> Stern and RTL | 17.0% | 15.9–18.2% | 15.6–18.5% | 15.3–18.8% | 14.8–19.4% | | [28–30 August 2018](2018-08-30-ForschungsgruppeWahlen.html) | Forschungsgruppe Wahlen <br> ZDF | 18.0% | 16.7–19.5% | 16.3–19.9% | 15.9–20.3% | 15.3–21.0% | | [23–29 August 2018](2018-08-29-Emnid.html) | Emnid <br> Bild am Sonntag | 19.0% | 18.0–20.1% | 17.7–20.4% | 17.5–20.6% | 17.0–21.1% | | [24–28 August 2018](2018-08-28-YouGov.html) | YouGov <br> RedaktionsNetzwerk Deutschland | 17.0% | 15.8–18.3% | 15.5–18.6% | 15.2–18.9% | 14.6–19.6% | | [24–27 August 2018](2018-08-27-INSAandYouGov.html) | INSA and YouGov <br> Bild | 16.5% | 15.5–17.6% | 15.2–17.9% | 15.0–18.2% | 14.5–18.7% | | [20–24 August 2018](2018-08-24-Forsa.html) | Forsa <br> Stern and RTL | 18.0% | 16.9–19.2% | 16.6–19.5% | 16.3–19.8% | 15.8–20.4% | | [20–22 August 2018](2018-08-22-Infratestdimap.html) | Infratest dimap <br> ARD | 18.0% | 16.5–19.6% | 16.1–20.0% | 15.7–20.4% | 15.1–21.2% | | [16–22 August 2018](2018-08-22-Emnid.html) | Emnid <br> Bild am Sonntag | 18.0% | 16.9–19.2% | 16.6–19.5% | 16.3–19.8% | 15.8–20.4% | | [16–20 August 2018](2018-08-20-INSAandYouGov.html) | INSA and YouGov <br> Bild | 16.5% | 15.7–17.4% | 15.4–17.6% | 15.2–17.8% | 14.8–18.3% | | [13–17 August 2018](2018-08-17-Forsa.html) | Forsa <br> Stern and RTL | 18.0% | 16.9–19.2% | 16.6–19.5% | 16.3–19.8% | 15.8–20.4% | | [9–15 August 2018](2018-08-15-Emnid.html) | Emnid <br> Bild am Sonntag | 17.0% | 16.1–17.9% | 15.9–18.2% | 15.7–18.4% | 15.3–18.9% | | [10–13 August 2018](2018-08-13-INSAandYouGov.html) | INSA and YouGov <br> Bild | 17.4% | 16.4–18.5% | 16.1–18.8% | 15.8–19.1% | 15.3–19.7% | | [6–10 August 2018](2018-08-10-Forsa.html) | Forsa <br> Stern and RTL | 18.0% | 16.9–19.2% | 16.6–19.5% | 16.3–19.8% | 15.8–20.4% | | [7–9 August 2018](2018-08-09-ForschungsgruppeWahlen.html) | Forschungsgruppe Wahlen <br> ZDF | 18.0% | 16.7–19.4% | 16.3–19.8% | 16.0–20.2% | 15.4–20.9% | | [27 July–9 August 2018](2018-08-09-Allensbach.html) | Allensbach <br> Frankfurter Allgemeine Zeitung | 20.0% | 18.6–21.5% | 18.2–21.9% | 17.9–22.3% | 17.3–23.0% | | [2–8 August 2018](2018-08-08-Emnid.html) | Emnid <br> Bild am Sonntag | 17.0% | 16.0–18.0% | 15.8–18.3% | 15.6–18.5% | 15.1–19.0% | | [3–6 August 2018](2018-08-06-INSAandYouGov.html) | INSA and YouGov <br> Bild | 17.0% | 16.0–18.1% | 15.7–18.4% | 15.4–18.7% | 15.0–19.2% | | [30 July–3 August 2018](2018-08-03-Forsa.html) | Forsa <br> Stern and RTL | 18.0% | 16.9–19.2% | 16.6–19.5% | 16.3–19.8% | 15.8–20.4% | | [30 July–1 August 2018](2018-08-01-Infratestdimap.html) | Infratest dimap <br> ARD | 18.0% | 16.8–19.3% | 16.4–19.7% | 16.1–20.0% | 15.5–20.7% | | [26 July–1 August 2018](2018-08-01-Emnid.html) | Emnid <br> Bild am Sonntag | 18.0% | 17.0–19.0% | 16.8–19.3% | 16.5–19.6% | 16.1–20.1% | | [25–31 July 2018](2018-07-31-GMS.html) | GMS | 17.0% | 15.6–18.6% | 15.2–19.1% | 14.8–19.5% | 14.1–20.3% | | [27–30 July 2018](2018-07-30-INSAandYouGov.html) | INSA and YouGov <br> Bild | 18.0% | 16.9–19.1% | 16.6–19.4% | 16.4–19.7% | 15.9–20.3% | | [23–27 July 2018](2018-07-27-Forsa.html) | Forsa <br> Stern and RTL | 18.0% | 16.9–19.2% | 16.6–19.5% | 16.3–19.8% | 15.8–20.4% | | [24–25 July 2018](2018-07-25-Infratestdimap.html) | Infratest dimap <br> ARD | 18.0% | 16.5–19.6% | 16.1–20.0% | 15.7–20.4% | 15.1–21.2% | | [19–25 July 2018](2018-07-25-Emnid.html) | Emnid <br> Bild am Sonntag | 18.0% | 16.9–19.1% | 16.6–19.5% | 16.4–19.7% | 15.9–20.3% | | [20–24 July 2018](2018-07-24-YouGov.html) | YouGov <br> RedaktionsNetzwerk Deutschland | 17.0% | 15.8–18.3% | 15.5–18.6% | 15.2–18.9% | 14.6–19.6% | | [20–23 July 2018](2018-07-23-INSAandYouGov.html) | INSA and YouGov <br> Bild | 18.0% | 16.9–19.1% | 16.6–19.4% | 16.4–19.7% | 15.9–20.3% | | [16–20 July 2018](2018-07-20-Forsa.html) | Forsa <br> Stern and RTL | 18.0% | 16.9–19.2% | 16.6–19.5% | 16.3–19.8% | 15.8–20.4% | | [12–18 July 2018](2018-07-18-Emnid.html) | Emnid <br> Bild am Sonntag | 19.0% | 18.0–20.0% | 17.7–20.3% | 17.5–20.6% | 17.0–21.1% | | [13–16 July 2018](2018-07-16-INSAandYouGov.html) | INSA and YouGov <br> Bild | 17.0% | 16.0–18.1% | 15.7–18.4% | 15.4–18.7% | 15.0–19.2% | | [9–13 July 2018](2018-07-13-Forsa.html) | Forsa <br> Stern and RTL | 17.0% | 15.9–18.2% | 15.7–18.5% | 15.4–18.8% | 14.9–19.3% | | [9–12 July 2018](2018-07-12-ForschungsgruppeWahlen.html) | Forschungsgruppe Wahlen <br> ZDF | 18.0% | 16.7–19.4% | 16.3–19.8% | 16.0–20.1% | 15.4–20.8% | | [1–12 July 2018](2018-07-12-Allensbach.html) | Allensbach <br> Frankfurter Allgemeine Zeitung | 20.0% | 18.6–21.5% | 18.2–21.9% | 17.9–22.3% | 17.3–23.0% | | [5–11 July 2018](2018-07-11-GMS.html) | GMS | 17.0% | 15.5–18.6% | 15.2–19.1% | 14.8–19.4% | 14.1–20.2% | | [5–11 July 2018](2018-07-11-Emnid.html) | Emnid <br> Bild am Sonntag | 18.0% | 17.0–19.0% | 16.7–19.3% | 16.5–19.6% | 16.0–20.1% | | [6–9 July 2018](2018-07-09-INSAandYouGov.html) | INSA and YouGov <br> Bild | 17.0% | 16.0–18.1% | 15.7–18.4% | 15.4–18.7% | 14.9–19.2% | | [2–6 July 2018](2018-07-06-Forsa.html) | Forsa <br> Stern and RTL | 17.0% | 15.9–18.1% | 15.6–18.5% | 15.3–18.7% | 14.9–19.3% | | [3–4 July 2018](2018-07-04-Infratestdimap.html) | Infratest dimap <br> ARD | 18.0% | 16.8–19.3% | 16.4–19.7% | 16.1–20.0% | 15.6–20.7% | | [28 June–4 July 2018](2018-07-04-Emnid.html) | Emnid <br> Bild am Sonntag | 17.0% | 15.9–18.2% | 15.6–18.5% | 15.4–18.8% | 14.9–19.3% | | [29 June–2 July 2018](2018-07-02-INSAandYouGov.html) | INSA and YouGov <br> Bild | 19.0% | 17.9–20.1% | 17.6–20.5% | 17.4–20.8% | 16.9–21.3% | | [25–29 June 2018](2018-06-29-Forsa.html) | Forsa <br> Stern and RTL | 17.0% | 15.9–18.2% | 15.6–18.5% | 15.4–18.8% | 14.9–19.3% | | [25–28 June 2018](2018-06-28-ForschungsgruppeWahlen.html) | Forschungsgruppe Wahlen <br> ZDF | 18.0% | 16.7–19.4% | 16.3–19.8% | 16.0–20.2% | 15.4–20.9% | | [21–28 June 2018](2018-06-28-Emnid.html) | Emnid <br> Bild am Sonntag | 19.0% | 17.9–20.2% | 17.6–20.5% | 17.3–20.8% | 16.8–21.4% | | [22–26 June 2018](2018-06-26-YouGov.html) | YouGov <br> RedaktionsNetzwerk Deutschland | 17.0% | 15.8–18.3% | 15.5–18.6% | 15.2–19.0% | 14.6–19.6% | | [25–26 June 2018](2018-06-26-Infratestdimap.html) | Infratest dimap <br> ARD | 19.0% | 17.5–20.7% | 17.1–21.1% | 16.7–21.6% | 16.0–22.4% | | [22–25 June 2018](2018-06-25-INSAandYouGov.html) | INSA and YouGov <br> Bild | 19.5% | 18.4–20.7% | 18.1–21.0% | 17.8–21.3% | 17.3–21.9% | | [18–22 June 2018](2018-06-22-Forsa.html) | Forsa <br> Stern and RTL | 17.0% | 15.9–18.1% | 15.6–18.5% | 15.3–18.7% | 14.9–19.3% | | [14–20 June 2018](2018-06-20-Emnid.html) | Emnid <br> Bild am Sonntag | 18.0% | 17.0–19.0% | 16.7–19.3% | 16.5–19.6% | 16.0–20.1% | | [15–18 June 2018](2018-06-18-INSAandYouGov.html) | INSA and YouGov <br> Bild | 19.0% | 17.9–20.1% | 17.6–20.5% | 17.3–20.7% | 16.8–21.3% | | [14–15 June 2018](2018-06-15-Forsa.html) | Forsa <br> Stern and RTL | 16.1% | 14.4–17.9% | 14.0–18.4% | 13.6–18.9% | 12.8–19.8% | | [11–13 June 2018](2018-06-13-Infratestdimap.html) | Infratest dimap <br> ARD | 18.0% | 16.8–19.3% | 16.4–19.7% | 16.1–20.0% | 15.6–20.7% | | [11–13 June 2018](2018-06-13-Forsa.html) | Forsa <br> Stern and RTL | 18.0% | 16.6–19.5% | 16.2–20.0% | 15.9–20.3% | 15.2–21.1% | | [7–13 June 2018](2018-06-13-Emnid.html) | Emnid <br> Bild am Sonntag | 18.0% | 17.0–19.1% | 16.7–19.4% | 16.5–19.6% | 16.0–20.1% | | [1–13 June 2018](2018-06-13-Allensbach.html) | Allensbach <br> Frankfurter Allgemeine Zeitung | 21.0% | 19.6–22.6% | 19.2–23.0% | 18.9–23.4% | 18.2–24.1% | | [8–11 June 2018](2018-06-11-INSAandYouGov.html) | INSA and YouGov <br> Bild | 17.0% | 15.9–18.1% | 15.7–18.4% | 15.4–18.7% | 14.9–19.2% | | [4–8 June 2018](2018-06-08-Forsa.html) | Forsa <br> Stern and RTL | 18.0% | 16.9–19.2% | 16.6–19.5% | 16.3–19.8% | 15.8–20.3% | | [5–7 June 2018](2018-06-07-ForschungsgruppeWahlen.html) | Forschungsgruppe Wahlen <br> ZDF | 20.0% | 18.6–21.5% | 18.2–21.9% | 17.9–22.3% | 17.3–23.0% | | [30 May–6 June 2018](2018-06-06-Emnid.html) | Emnid <br> Bild am Sonntag | 19.0% | 17.9–20.2% | 17.6–20.5% | 17.3–20.8% | 16.8–21.4% | | [1–4 June 2018](2018-06-04-INSAandYouGov.html) | INSA and YouGov <br> Bild | 17.0% | 16.0–18.1% | 15.7–18.4% | 15.4–18.7% | 14.9–19.2% | | [28 May–1 June 2018](2018-06-01-Forsa.html) | Forsa <br> Stern and RTL | 18.0% | 16.9–19.2% | 16.6–19.5% | 16.3–19.8% | 15.8–20.4% | | [25–29 May 2018](2018-05-29-YouGov.html) | YouGov <br> RedaktionsNetzwerk Deutschland | 17.0% | 15.9–18.3% | 15.5–18.7% | 15.2–19.0% | 14.7–19.6% | | [24–29 May 2018](2018-05-29-Emnid.html) | Emnid <br> Bild am Sonntag | 18.0% | 16.7–19.3% | 16.3–19.7% | 16.0–20.1% | 15.5–20.7% | | [25–28 May 2018](2018-05-28-INSAandYouGov.html) | INSA and YouGov <br> Bild | 17.0% | 16.0–18.1% | 15.7–18.4% | 15.5–18.7% | 15.0–19.3% | | [22–25 May 2018](2018-05-25-Forsa.html) | Forsa <br> Stern and RTL | 18.0% | 16.8–19.3% | 16.4–19.7% | 16.1–20.0% | 15.6–20.7% | | [17–23 May 2018](2018-05-23-Emnid.html) | Emnid <br> Bild am Sonntag | 17.0% | 16.0–18.2% | 15.7–18.5% | 15.4–18.7% | 14.9–19.3% | | [18–22 May 2018](2018-05-22-INSAandYouGov.html) | INSA and YouGov <br> Bild | 16.5% | 15.5–17.6% | 15.2–17.9% | 14.9–18.2% | 14.5–18.7% | | [14–18 May 2018](2018-05-18-Forsa.html) | Forsa <br> Stern and RTL | 18.0% | 16.9–19.2% | 16.6–19.5% | 16.4–19.8% | 15.8–20.4% | | [15–17 May 2018](2018-05-17-ForschungsgruppeWahlen.html) | Forschungsgruppe Wahlen <br> ZDF | 20.0% | 18.6–21.6% | 18.2–22.0% | 17.8–22.4% | 17.2–23.1% | | [14–16 May 2018](2018-05-16-Infratestdimap.html) | Infratest dimap <br> ARD | 17.0% | 15.6–18.7% | 15.2–19.1% | 14.8–19.5% | 14.2–20.3% | | [11–16 May 2018](2018-05-16-GMS.html) | GMS | 16.0% | 14.5–17.5% | 14.1–18.0% | 13.8–18.4% | 13.2–19.1% | | [9–16 May 2018](2018-05-16-Emnid.html) | Emnid <br> Bild am Sonntag | 17.0% | 16.0–18.1% | 15.7–18.4% | 15.4–18.7% | 14.9–19.2% | | [11–14 May 2018](2018-05-14-INSAandYouGov.html) | INSA and YouGov <br> Bild | 17.0% | 16.0–18.1% | 15.7–18.4% | 15.5–18.7% | 15.0–19.2% | | [7–11 May 2018](2018-05-11-Forsa.html) | Forsa <br> Stern and RTL | 17.0% | 15.8–18.3% | 15.5–18.6% | 15.2–18.9% | 14.6–19.6% | | [7–8 May 2018](2018-05-08-Infratestdimap.html) | Infratest dimap <br> ARD | 18.0% | 16.8–19.3% | 16.4–19.7% | 16.1–20.0% | 15.5–20.7% | | [3–8 May 2018](2018-05-08-Emnid.html) | Emnid <br> Bild am Sonntag | 17.0% | 15.8–18.3% | 15.5–18.7% | 15.2–19.0% | 14.6–19.6% | | [24 April–8 May 2018](2018-05-08-Allensbach.html) | Allensbach <br> Frankfurter Allgemeine Zeitung | 20.0% | 18.6–21.6% | 18.2–22.0% | 17.9–22.3% | 17.3–23.1% | | [4–7 May 2018](2018-05-07-INSAandYouGov.html) | INSA and YouGov <br> Bild | 17.0% | 16.0–18.1% | 15.7–18.4% | 15.4–18.7% | 15.0–19.2% | | [30 April–4 May 2018](2018-05-04-Forsa.html) | Forsa <br> Stern and RTL | 18.0% | 16.8–19.3% | 16.5–19.7% | 16.2–20.0% | 15.6–20.6% | | [26 April–2 May 2018](2018-05-02-Emnid.html) | Emnid <br> Bild am Sonntag | 17.0% | 15.8–18.3% | 15.5–18.7% | 15.2–19.0% | 14.6–19.6% | | [27–30 April 2018](2018-04-30-INSAandYouGov.html) | INSA and YouGov <br> Bild | 17.0% | 16.0–18.1% | 15.7–18.4% | 15.4–18.7% | 15.0–19.2% | | [23–27 April 2018](2018-04-27-Forsa.html) | Forsa <br> Stern and RTL | 17.0% | 15.9–18.1% | 15.6–18.4% | 15.4–18.7% | 14.9–19.3% | | [20–26 April 2018](2018-04-26-GMS.html) | GMS | 17.0% | 15.6–18.6% | 15.2–19.1% | 14.8–19.5% | 14.1–20.3% | | [24–26 April 2018](2018-04-26-ForschungsgruppeWahlen.html) | Forschungsgruppe Wahlen <br> ZDF | 20.0% | 18.6–21.5% | 18.2–21.9% | 17.9–22.3% | 17.3–23.0% | | [19–25 April 2018](2018-04-25-Emnid.html) | Emnid <br> Bild am Sonntag | 18.0% | 17.0–19.1% | 16.7–19.4% | 16.5–19.6% | 16.0–20.1% | | [20–24 April 2018](2018-04-24-YouGov.html) | YouGov <br> RedaktionsNetzwerk Deutschland | 18.0% | 16.8–19.3% | 16.5–19.7% | 16.2–20.0% | 15.6–20.6% | | [20–23 April 2018](2018-04-23-INSAandYouGov.html) | INSA and YouGov <br> Bild | 18.0% | 16.9–19.1% | 16.6–19.4% | 16.4–19.7% | 15.9–20.2% | | [16–20 April 2018](2018-04-20-Forsa.html) | Forsa <br> Stern and RTL | 18.0% | 16.9–19.1% | 16.6–19.5% | 16.3–19.8% | 15.8–20.3% | | [16–18 April 2018](2018-04-18-Infratestdimap.html) | Infratest dimap <br> ARD | 17.0% | 15.6–18.6% | 15.2–19.1% | 14.9–19.4% | 14.2–20.2% | | [12–18 April 2018](2018-04-18-Emnid.html) | Emnid <br> Bild am Sonntag | 18.0% | 17.0–19.1% | 16.8–19.3% | 16.5–19.6% | 16.1–20.1% | | [3–17 April 2018](2018-04-17-Allensbach.html) | Allensbach <br> Frankfurter Allgemeine Zeitung | 20.5% | 19.1–22.0% | 18.7–22.4% | 18.4–22.8% | 17.7–23.5% | | [13–16 April 2018](2018-04-16-INSAandYouGov.html) | INSA and YouGov <br> Bild | 18.5% | 17.4–19.6% | 17.1–20.0% | 16.9–20.2% | 16.4–20.8% | | [9–13 April 2018](2018-04-13-Forsa.html) | Forsa <br> Stern and RTL | 19.0% | 17.9–20.2% | 17.6–20.5% | 17.3–20.8% | 16.8–21.4% | | [10–12 April 2018](2018-04-12-ForschungsgruppeWahlen.html) | Forschungsgruppe Wahlen <br> ZDF | 19.0% | 17.6–20.5% | 17.2–21.0% | 16.8–21.4% | 16.2–22.1% | | [5–11 April 2018](2018-04-11-Emnid.html) | Emnid <br> Bild am Sonntag | 18.0% | 16.8–19.2% | 16.5–19.5% | 16.2–19.8% | 15.7–20.4% | | [6–9 April 2018](2018-04-09-INSAandYouGov.html) | INSA and YouGov <br> Bild | 17.5% | 16.4–18.6% | 16.1–18.9% | 15.9–19.2% | 15.4–19.7% | | [3–6 April 2018](2018-04-06-Forsa.html) | Forsa <br> Stern and RTL | 20.0% | 18.7–21.4% | 18.4–21.7% | 18.1–22.1% | 17.5–22.8% | | [29 March–5 April 2018](2018-04-05-Emnid.html) | Emnid <br> Bild am Sonntag | 17.0% | 15.7–18.3% | 15.4–18.7% | 15.1–19.0% | 14.5–19.7% | | [23 March–4 April 2018](2018-04-04-pollytix.html) | pollytix | 19.0% | 17.7–20.4% | 17.3–20.8% | 17.0–21.1% | 16.4–21.8% | | [3–4 April 2018](2018-04-04-Infratestdimap.html) | Infratest dimap <br> ARD | 18.0% | 16.8–19.4% | 16.5–19.7% | 16.2–20.1% | 15.6–20.7% | | [29–31 March 2018](2018-03-31-INSAandYouGov.html) | INSA and YouGov <br> Bild | 18.0% | 16.5–19.6% | 16.1–20.0% | 15.8–20.4% | 15.1–21.2% | | [26–29 March 2018](2018-03-29-Forsa.html) | Forsa <br> Stern and RTL | 18.0% | 16.8–19.3% | 16.5–19.7% | 16.2–20.0% | 15.6–20.7% | | [22–28 March 2018](2018-03-28-Emnid.html) | Emnid <br> Bild am Sonntag | 18.0% | 16.9–19.2% | 16.6–19.5% | 16.4–19.8% | 15.9–20.3% | | [23–27 March 2018](2018-03-27-YouGov.html) | YouGov <br> RedaktionsNetzwerk Deutschland | 17.0% | 15.8–18.2% | 15.5–18.6% | 15.2–18.9% | 14.6–19.5% | | [23–26 March 2018](2018-03-26-INSAandYouGov.html) | INSA and YouGov <br> Bild | 17.0% | 16.0–18.1% | 15.7–18.4% | 15.4–18.7% | 15.0–19.3% | | [19–23 March 2018](2018-03-23-Forsa.html) | Forsa <br> Stern and RTL | 19.0% | 17.9–20.2% | 17.6–20.6% | 17.3–20.9% | 16.8–21.5% | | [20–21 March 2018](2018-03-21-Infratestdimap.html) | Infratest dimap <br> ARD | 19.0% | 17.5–20.6% | 17.1–21.1% | 16.7–21.5% | 16.0–22.3% | | [16–21 March 2018](2018-03-21-GMS.html) | GMS | 18.0% | 16.6–19.7% | 16.1–20.1% | 15.8–20.6% | 15.1–21.4% | | [15–21 March 2018](2018-03-21-Emnid.html) | Emnid <br> Bild am Sonntag | 18.0% | 16.9–19.2% | 16.6–19.5% | 16.4–19.8% | 15.9–20.3% | | [16–19 March 2018](2018-03-19-INSAandYouGov.html) | INSA and YouGov <br> Bild | 17.5% | 16.5–18.6% | 16.2–19.0% | 15.9–19.2% | 15.5–19.8% | | [12–16 March 2018](2018-03-16-Forsa.html) | Forsa <br> Stern and RTL | 19.0% | 17.9–20.2% | 17.6–20.6% | 17.3–20.9% | 16.8–21.5% | | [13–15 March 2018](2018-03-15-ForschungsgruppeWahlen.html) | Forschungsgruppe Wahlen <br> ZDF | 19.0% | 17.6–20.5% | 17.3–21.0% | 16.9–21.3% | 16.3–22.1% | | [2–15 March 2018](2018-03-15-Allensbach.html) | Allensbach <br> Frankfurter Allgemeine Zeitung | 19.0% | 17.7–20.5% | 17.3–20.9% | 16.9–21.3% | 16.3–22.0% | | [8–14 March 2018](2018-03-14-Emnid.html) | Emnid <br> Bild am Sonntag | 19.0% | 17.9–20.2% | 17.6–20.5% | 17.3–20.8% | 16.8–21.4% | | [9–12 March 2018](2018-03-12-INSAandYouGov.html) | INSA and YouGov <br> Bild | 17.5% | 16.5–18.6% | 16.2–19.0% | 15.9–19.2% | 15.4–19.8% | | [5–9 March 2018](2018-03-09-Forsa.html) | Forsa <br> Stern and RTL | 18.0% | 16.9–19.2% | 16.6–19.5% | 16.3–19.8% | 15.8–20.4% | | [1–7 March 2018](2018-03-07-Emnid.html) | Emnid <br> Bild am Sonntag | 19.0% | 17.9–20.2% | 17.5–20.5% | 17.3–20.9% | 16.8–21.4% | | [5 March 2018](2018-03-05-INSAandYouGov.html) | INSA and YouGov <br> Bild | 15.0% | 13.7–16.5% | 13.3–16.9% | 13.0–17.3% | 12.4–18.0% | | [4–5 March 2018](2018-03-05-Forsa.html) | Forsa <br> Stern and RTL | 19.0% | 17.5–20.6% | 17.1–21.0% | 16.8–21.4% | 16.1–22.2% | | [26 February–2 March 2018](2018-03-02-Forsa.html) | Forsa <br> Stern and RTL | 18.0% | 16.9–19.2% | 16.6–19.5% | 16.3–19.8% | 15.8–20.4% | | [26–28 February 2018](2018-02-28-YouGov.html) | YouGov <br> RedaktionsNetzwerk Deutschland | 16.0% | 14.9–17.3% | 14.6–17.6% | 14.3–17.9% | 13.8–18.5% | | [26–28 February 2018](2018-02-28-Infratestdimap.html) | Infratest dimap <br> ARD | 18.0% | 16.8–19.3% | 16.4–19.7% | 16.1–20.0% | 15.5–20.7% | | [22–28 February 2018](2018-02-28-Emnid.html) | Emnid <br> Bild am Sonntag | 16.0% | 14.9–17.1% | 14.6–17.4% | 14.4–17.7% | 13.9–18.3% | | [23–26 February 2018](2018-02-26-INSAandYouGov.html) | INSA and YouGov <br> Bild | 15.5% | 14.2–17.0% | 13.8–17.5% | 13.5–17.8% | 12.8–18.6% | | [19–23 February 2018](2018-02-23-Forsa.html) | Forsa <br> Stern and RTL | 18.0% | 16.9–19.2% | 16.6–19.5% | 16.3–19.8% | 15.8–20.4% | | [20–22 February 2018](2018-02-22-ForschungsgruppeWahlen.html) | Forschungsgruppe Wahlen <br> ZDF | 17.0% | 15.7–18.4% | 15.4–18.7% | 15.1–19.1% | 14.5–19.8% | | [20–21 February 2018](2018-02-21-Infratestdimap.html) | Infratest dimap <br> ARD | 17.0% | 15.6–18.6% | 15.2–19.0% | 14.9–19.4% | 14.2–20.2% | | [15–21 February 2018](2018-02-21-Emnid.html) | Emnid <br> Bild am Sonntag | 17.0% | 15.9–18.1% | 15.6–18.4% | 15.4–18.7% | 14.9–19.3% | | [16–19 February 2018](2018-02-19-INSAandYouGov.html) | INSA and YouGov <br> Bild | 15.5% | 14.5–16.6% | 14.2–16.9% | 14.0–17.1% | 13.5–17.7% | | [12–16 February 2018](2018-02-16-Forsa.html) | Forsa <br> Stern and RTL | 16.0% | 15.0–17.1% | 14.7–17.4% | 14.4–17.7% | 13.9–18.3% | | [13–15 February 2018](2018-02-15-Infratestdimap.html) | Infratest dimap <br> ARD | 16.0% | 14.6–17.6% | 14.2–18.0% | 13.8–18.4% | 13.2–19.2% | | [2–15 February 2018](2018-02-15-Allensbach.html) | Allensbach <br> Frankfurter Allgemeine Zeitung | 17.5% | 16.2–18.9% | 15.8–19.3% | 15.5–19.7% | 14.9–20.4% | | [8–14 February 2018](2018-02-14-Emnid.html) | Emnid <br> Bild am Sonntag | 19.0% | 17.7–20.4% | 17.4–20.8% | 17.1–21.1% | 16.5–21.8% | | [9–12 February 2018](2018-02-12-INSAandYouGov.html) | INSA and YouGov <br> Bild | 16.5% | 15.6–17.5% | 15.3–17.7% | 15.1–18.0% | 14.7–18.4% | | [7–8 February 2018](2018-02-08-Forsa.html) | Forsa <br> Stern and RTL | 18.0% | 16.6–19.7% | 16.1–20.1% | 15.8–20.6% | 15.1–21.4% | | [1–7 February 2018](2018-02-07-GMS.html) | GMS | 18.0% | 16.5–19.6% | 16.1–20.1% | 15.7–20.5% | 15.0–21.3% | | [1–7 February 2018](2018-02-07-Emnid.html) | Emnid <br> Bild am Sonntag | 20.0% | 18.6–21.5% | 18.2–21.9% | 17.8–22.3% | 17.2–23.1% | | [2–5 February 2018](2018-02-05-INSAandYouGov.html) | INSA and YouGov <br> Bild | 17.0% | 16.0–18.1% | 15.7–18.4% | 15.4–18.7% | 15.0–19.3% | | [27 December 2017–2 February 2018](2018-02-02-GMS.html) | GMS | 20.0% | 18.4–21.7% | 18.0–22.2% | 17.6–22.6% | 16.9–23.4% | | [29 January–2 February 2018](2018-02-02-Forsa.html) | Forsa <br> Stern and RTL | 18.0% | 16.9–19.2% | 16.6–19.5% | 16.3–19.8% | 15.8–20.4% | | [30 January–1 February 2018](2018-02-01-ForschungsgruppeWahlen.html) | Forschungsgruppe Wahlen <br> ZDF | 19.0% | 17.6–20.4% | 17.3–20.8% | 16.9–21.2% | 16.3–21.9% | | [29–31 January 2018](2018-01-31-Infratestdimap.html) | Infratest dimap <br> ARD | 18.0% | 16.8–19.3% | 16.4–19.7% | 16.1–20.0% | 15.5–20.7% | | [25–31 January 2018](2018-01-31-Emnid.html) | Emnid <br> Bild am Sonntag | 20.0% | 18.6–21.5% | 18.2–21.9% | 17.8–22.3% | 17.2–23.0% | | [26–29 January 2018](2018-01-29-INSAandYouGov.html) | INSA and YouGov <br> Bild | 17.7% | 16.6–18.8% | 16.3–19.1% | 16.1–19.4% | 15.6–19.9% | | [22–26 January 2018](2018-01-26-Forsa.html) | Forsa <br> Stern and RTL | 18.0% | 16.9–19.2% | 16.6–19.5% | 16.3–19.8% | 15.8–20.4% | | [22–24 January 2018](2018-01-24-Infratestdimap.html) | Infratest dimap <br> ARD | 19.0% | 17.5–20.6% | 17.1–21.1% | 16.7–21.5% | 16.0–22.3% | | [18–24 January 2018](2018-01-24-Emnid.html) | Emnid <br> Bild am Sonntag | 20.0% | 18.7–21.4% | 18.4–21.8% | 18.1–22.1% | 17.5–22.8% | | [19–23 January 2018](2018-01-23-YouGov.html) | YouGov <br> RedaktionsNetzwerk Deutschland | 19.0% | 17.8–20.4% | 17.5–20.7% | 17.2–21.1% | 16.6–21.7% | | [22 January 2018](2018-01-22-INSAandYouGov.html) | INSA and YouGov <br> Bild | 18.0% | 16.6–19.5% | 16.2–19.9% | 15.9–20.3% | 15.2–21.0% | | [22 January 2018](2018-01-22-Forsa.html) | Forsa <br> Stern and RTL | 17.0% | 15.7–18.4% | 15.3–18.8% | 15.0–19.2% | 14.4–19.9% | | [15–19 January 2018](2018-01-19-Forsa.html) | Forsa <br> Stern and RTL | 18.0% | 16.9–19.2% | 16.6–19.5% | 16.4–19.8% | 15.9–20.4% | | [16–18 January 2018](2018-01-18-ForschungsgruppeWahlen.html) | Forschungsgruppe Wahlen <br> ZDF | 20.0% | 18.6–21.4% | 18.2–21.9% | 17.9–22.2% | 17.3–22.9% | | [5–18 January 2018](2018-01-18-Allensbach.html) | Allensbach <br> Frankfurter Allgemeine Zeitung | 21.0% | 19.5–22.5% | 19.1–23.0% | 18.8–23.4% | 18.1–24.1% | | [15–17 January 2018](2018-01-17-Forsa.html) | Forsa <br> Stern and RTL | 18.0% | 16.8–19.3% | 16.4–19.7% | 16.2–20.1% | 15.6–20.7% | | [11–17 January 2018](2018-01-17-Emnid.html) | Emnid <br> Bild am Sonntag | 21.0% | 19.7–22.4% | 19.3–22.8% | 19.0–23.2% | 18.3–23.9% | | [12–15 January 2018](2018-01-15-INSAandYouGov.html) | INSA and YouGov <br> Bild | 18.5% | 17.4–19.7% | 17.1–20.0% | 16.9–20.3% | 16.4–20.8% | | [8–12 January 2018](2018-01-12-Forsa.html) | Forsa <br> Stern and RTL | 20.0% | 18.9–21.2% | 18.5–21.5% | 18.3–21.8% | 17.7–22.4% | | [4–10 January 2018](2018-01-10-Emnid.html) | Emnid <br> Bild am Sonntag | 21.0% | 19.8–22.3% | 19.5–22.6% | 19.2–22.9% | 18.7–23.5% | | [5–8 January 2018](2018-01-08-INSAandYouGov.html) | INSA and YouGov <br> Bild | 19.5% | 18.4–20.7% | 18.1–21.0% | 17.8–21.3% | 17.3–21.8% | | [2–5 January 2018](2018-01-05-Forsa.html) | Forsa <br> Stern and RTL | 20.0% | 18.9–21.2% | 18.5–21.5% | 18.3–21.8% | 17.7–22.4% | | [2–3 January 2018](2018-01-03-Infratestdimap.html) | Infratest dimap <br> ARD | 21.0% | 19.7–22.4% | 19.3–22.8% | 19.0–23.1% | 18.4–23.8% | | [21 December 2017–3 January 2018](2018-01-03-Emnid.html) | Emnid <br> Bild am Sonntag | 20.0% | 18.7–21.4% | 18.3–21.8% | 18.0–22.1% | 17.4–22.8% | | [29 December 2017–2 January 2018](2018-01-02-INSAandYouGov.html) | INSA and YouGov <br> Bild | 19.5% | 18.4–20.7% | 18.1–21.0% | 17.8–21.3% | 17.3–21.9% | ### Probability Mass Function The following table shows the probability mass function per percentage block of voting intentions for the [poll average](average.html) for SPD (S&D). | Voting Intentions | Probability | Accumulated | Special Marks | |:-----------------:|:-----------:|:-----------:|:-------------:| | 12.5–13.5% | 0% | 100% | | | 13.5–14.5% | 1.5% | 100% | | | 14.5–15.5% | 12% | 98% | | | 15.5–16.5% | 28% | 86% | | | 16.5–17.5% | 27% | 59% | Median | | 17.5–18.5% | 21% | 32% | | | 18.5–19.5% | 9% | 10% | | | 19.5–20.5% | 1.4% | 2% | | | 20.5–21.5% | 0.1% | 0.1% | | | 21.5–22.5% | 0% | 0% | | | 22.5–23.5% | 0% | 0% | | | 23.5–24.5% | 0% | 0% | | | 24.5–25.5% | 0% | 0% | | | 25.5–26.5% | 0% | 0% | | | 26.5–27.5% | 0% | 0% | Last Result | ## Seats Last result: **27** seats (General Election of 25 May 2014) ### Confidence Intervals | Period | Polling firm/Commissioner(s) | Median | 80% Confidence Interval | 90% Confidence Interval | 95% Confidence Interval | 99% Confidence Interval | |:----------:|:----------------:|:------:|:-----------------------:|:-----------------------:|:-----------------------:|:-----------------------:| | N/A | [Poll Average](average.html) | 16 | 15–18 | 14–18 | 14–18 | 14–19 | | [20–23 May 2019](2019-05-23-ForschungsgruppeWahlen.html) | Forschungsgruppe Wahlen <br> ZDF | 17 | 16–18 | 16–18 | 15–19 | 15–19 | | [17–20 May 2019](2019-05-20-INSA.html) | INSA | 17 | 16–18 | 16–18 | 16–19 | 15–19 | | [13–17 May 2019](2019-05-17-Forsa.html) | Forsa | 15 | 14–16 | 14–17 | 14–17 | 13–18 | | [14–16 May 2019](2019-05-16-ForschungsgruppeWahlen.html) | Forschungsgruppe Wahlen <br> ZDF | 16 | 15–17 | 15–18 | 14–18 | 14–19 | | [14–15 May 2019](2019-05-15-Infratestdimap.html) | Infratest dimap <br> ARD | 17 | 15–18 | 15–18 | 14–19 | 14–19 | | [10–13 May 2019](2019-05-13-INSAandYouGov.html) | INSA and YouGov <br> Bild | 16 | 15–16 | 14–17 | 14–17 | 13–17 | | [6–10 May 2019](2019-05-10-Forsa.html) | Forsa <br> Stern and RTL | 14 | 14–15 | 13–16 | 13–16 | 13–16 | | [7–9 May 2019](2019-05-09-ForschungsgruppeWahlen.html) | Forschungsgruppe Wahlen <br> ZDF | 15 | 14–17 | 14–17 | 13–17 | 13–18 | | [2–8 May 2019](2019-05-08-GMS.html) | GMS | 16 | 15–18 | 14–18 | 14–18 | 13–19 | | [2–8 May 2019](2019-05-08-Emnid.html) | Emnid <br> Bild am Sonntag | 15 | 15–16 | 14–17 | 14–17 | 14–17 | | [3 April–6 May 2019](2019-05-06-INSAandYouGov.html) | INSA and YouGov <br> Bild | 15 | 14–16 | 14–16 | 14–17 | 13–17 | | [29 April–3 May 2019](2019-05-03-Forsa.html) | Forsa <br> Stern and RTL | 14 | 13–15 | 13–16 | 13–16 | 12–17 | | [29–30 April 2019](2019-04-30-Infratestdimap.html) | Infratest dimap <br> ARD | 18 | 17–20 | 17–20 | 16–20 | 16–20 | | [25–30 April 2019](2019-04-30-Emnid.html) | Emnid <br> Bild am Sonntag | 16 | 15–17 | 15–18 | 15–18 | 14–18 | | [26–29 April 2019](2019-04-29-YouGov.html) | YouGov <br> RedaktionsNetzwerk Deutschland | 17 | 16–18 | 16–19 | 16–19 | 15–20 | | [26–29 April 2019](2019-04-29-INSAandYouGov.html) | INSA and YouGov <br> Bild | 16 | 14–16 | 14–16 | 14–17 | 14–17 | | [23–26 April 2019](2019-04-26-Forsa.html) | Forsa <br> Stern and RTL | 16 | 15–18 | 15–18 | 15–18 | 14–19 | | [18–24 April 2019](2019-04-24-Emnid.html) | Emnid <br> Bild am Sonntag | 16 | 15–18 | 15–18 | 15–18 | 14–19 | | [18–21 April 2019](2019-04-21-INSAandYouGov.html) | INSA and YouGov <br> Bild | 15 | 13–17 | 13–17 | 13–18 | 12–18 | | [15–18 April 2019](2019-04-18-Forsa.html) | Forsa <br> Stern and RTL | 16 | 15–17 | 15–18 | 14–18 | 14–19 | | [11–17 April 2019](2019-04-17-Emnid.html) | Emnid <br> Bild am Sonntag | 17 | 16–18 | 16–19 | 16–19 | 16–19 | | [12–15 April 2019](2019-04-15-INSAandYouGov.html) | INSA and YouGov <br> Bild | 15 | 14–16 | 14–16 | 13–16 | 13–17 | | [8–12 April 2019](2019-04-12-Forsa.html) | Forsa <br> Stern and RTL | 15 | 14–17 | 14–17 | 14–17 | 13–17 | | [1–12 April 2019](2019-04-12-Allensbach.html) | Allensbach <br> Frankfurter Allgemeine Zeitung | 18 | 17–19 | 16–19 | 16–19 | 15–20 | | [9–11 April 2019](2019-04-11-ForschungsgruppeWahlen.html) | Forschungsgruppe Wahlen <br> ZDF | 17 | 16–19 | 16–19 | 15–20 | 15–20 | | [10 April 2019](2019-04-10-Emnid.html) | Emnid <br> Bild am Sonntag | 16 | 16–17 | 15–18 | 15–18 | 14–18 | | [5–8 April 2019](2019-04-08-INSAandYouGov.html) | INSA and YouGov <br> Bild | 15 | 14–16 | 14–16 | 13–16 | 13–17 | | [1–5 April 2019](2019-04-05-Forsa.html) | Forsa <br> Stern and RTL | 15 | 14–16 | 14–17 | 14–17 | 13–17 | | [1–3 April 2019](2019-04-03-Infratestdimap.html) | Infratest dimap <br> ARD | 16 | 15–18 | 15–18 | 15–18 | 14–19 | | [28 March–3 April 2019](2019-04-03-GMS.html) | GMS | 14 | 13–16 | 13–16 | 12–17 | 12–17 | | [28 March–3 April 2019](2019-04-03-Emnid.html) | Emnid <br> Bild am Sonntag | 16 | 15–17 | 15–17 | 15–17 | 15–18 | | [28 March–1 April 2019](2019-04-01-INSAandYouGov.html) | INSA and YouGov <br> Bild | 16 | 15–17 | 15–17 | 15–17 | 14–17 | | [25–29 March 2019](2019-03-29-Forsa.html) | Forsa <br> Stern and RTL | 15 | 14–16 | 14–17 | 13–17 | 13–18 | | [25–27 March 2019](2019-03-27-ForschungsgruppeWahlen.html) | Forschungsgruppe Wahlen <br> ZDF | 17 | 16–19 | 16–19 | 15–19 | 15–20 | | [21–27 March 2019](2019-03-27-Emnid.html) | Emnid <br> Bild am Sonntag | 15 | 15–16 | 14–17 | 14–17 | 13–17 | | [22–26 March 2019](2019-03-26-YouGov.html) | YouGov <br> RedaktionsNetzwerk Deutschland | 17 | 17–18 | 16–18 | 15–19 | 15–20 | | [18–22 March 2019](2019-03-22-Forsa.html) | Forsa <br> Stern and RTL | 15 | 14–16 | 14–16 | 14–17 | 13–18 | | [7–21 March 2019](2019-03-21-Allensbach.html) | Allensbach <br> Frankfurter Allgemeine Zeitung | 17 | 16–19 | 16–19 | 15–20 | 15–20 | | [14–20 March 2019](2019-03-20-Emnid.html) | Emnid <br> Bild am Sonntag | 16 | 15–17 | 15–18 | 14–18 | 14–19 | | [11–15 March 2019](2019-03-15-Forsa.html) | Forsa <br> Stern and RTL | 14 | 13–15 | 13–15 | 13–16 | 12–16 | | [12–14 March 2019](2019-03-14-ForschungsgruppeWahlen.html) | Forschungsgruppe Wahlen <br> ZDF | 17 | 16–18 | 16–19 | 15–19 | 15–20 | | [11–13 March 2019](2019-03-13-Infratestdimap.html) | Infratest dimap <br> ARD | 18 | 17–19 | 17–20 | 16–20 | 16–21 | | [7–13 March 2019](2019-03-13-Emnid.html) | Emnid <br> Bild am Sonntag | 15 | 14–16 | 14–16 | 14–17 | 13–18 | | [4–8 March 2019](2019-03-08-Forsa.html) | Forsa <br> Stern and RTL | 14 | 14–15 | 14–15 | 13–16 | 13–16 | | [28 February–6 March 2019](2019-03-06-Emnid.html) | Emnid <br> Bild am Sonntag | 16 | 16–17 | 15–17 | 15–17 | 14–18 | | [27 February–1 March 2019](2019-03-01-INSAandYouGov.html) | INSA and YouGov <br> Bild | 16 | 16–17 | 15–17 | 15–17 | 15–17 | | [27 February–1 March 2019](2019-03-01-INSA.html) | INSA <br> SWG | 16 | 15–16 | 15–16 | 15–17 | 14–17 | | [25 February–1 March 2019](2019-03-01-Forsa.html) | Forsa <br> Stern and RTL | 15 | 15–17 | 14–17 | 14–17 | 13–17 | | [21–27 February 2019](2019-02-27-GMS.html) | GMS | 15 | 14–17 | 13–17 | 13–18 | 13–18 | | [21–27 February 2019](2019-02-27-Emnid.html) | Emnid <br> Bild am Sonntag | 17 | 16–18 | 16–19 | 15–19 | 15–20 | | [22–26 February 2019](2019-02-26-YouGov.html) | YouGov <br> RedaktionsNetzwerk Deutschland | 17 | 16–18 | 16–19 | 15–19 | 15–19 | | [22–25 February 2019](2019-02-25-INSAandYouGov.html) | INSA and YouGov <br> Bild | 17 | 16–18 | 16–18 | 16–19 | 15–19 | | [18–22 February 2019](2019-02-22-Forsa.html) | Forsa <br> Stern and RTL | 15 | 14–16 | 14–17 | 14–17 | 13–17 | | [19–21 February 2019](2019-02-21-ForschungsgruppeWahlen.html) | Forschungsgruppe Wahlen <br> ZDF | 17 | 16–18 | 15–19 | 15–19 | 15–20 | | [14–20 February 2019](2019-02-20-Emnid.html) | Emnid <br> Bild am Sonntag | 19 | 17–19 | 17–19 | 16–20 | 16–20 | | [15–18 February 2019](2019-02-18-INSAandYouGov.html) | INSA and YouGov <br> Bild | 17 | 16–19 | 16–19 | 16–19 | 15–20 | | [11–15 February 2019](2019-02-15-Forsa.html) | Forsa <br> Stern and RTL | 16 | 15–17 | 15–17 | 15–18 | 14–18 | | [11–13 February 2019](2019-02-13-Infratestdimap.html) | Infratest dimap <br> ARD | 17 | 16–19 | 16–19 | 16–19 | 15–20 | | [7–13 February 2019](2019-02-13-Emnid.html) | Emnid <br> Bild am Sonntag | 18 | 18–20 | 17–20 | 17–20 | 16–20 | | [1–13 February 2019](2019-02-13-Allensbach.html) | Allensbach <br> Frankfurter Allgemeine Zeitung | 17 | 16–18 | 16–19 | 15–19 | 15–20 | | [8–11 February 2019](2019-02-11-INSAandYouGov.html) | INSA and YouGov <br> Bild | 15 | 14–15 | 14–16 | 14–16 | 13–16 | | [4–8 February 2019](2019-02-08-Forsa.html) | Forsa <br> Stern and RTL | 14 | 13–15 | 13–15 | 13–15 | 13–16 | | [5–7 February 2019](2019-02-07-ForschungsgruppeWahlen.html) | Forschungsgruppe Wahlen <br> ZDF | 15 | 14–16 | 14–16 | 13–16 | 13–17 | | [31 January–6 February 2019](2019-02-06-Emnid.html) | Emnid <br> Bild am Sonntag | 17 | 16–17 | 15–17 | 15–18 | 15–18 | | [1–4 February 2019](2019-02-04-INSAandYouGov.html) | INSA and YouGov <br> Bild | 14 | 13–15 | 13–15 | 12–15 | 12–16 | | [28 January–1 February 2019](2019-02-01-Forsa.html) | Forsa <br> Stern and RTL | 14 | 13–15 | 13–15 | 13–16 | 12–16 | | [24–30 January 2019](2019-01-30-Emnid.html) | Emnid <br> Bild am Sonntag | 16 | 15–16 | 14–17 | 14–17 | 13–17 | | [25–29 January 2019](2019-01-29-YouGov.html) | YouGov <br> RedaktionsNetzwerk Deutschland | 15 | 14–15 | 13–16 | 13–16 | 12–16 | | [25–28 January 2019](2019-01-28-INSAandYouGov.html) | INSA and YouGov <br> Bild | 14 | 13–15 | 13–16 | 13–16 | 12–17 | | [21–25 January 2019](2019-01-25-Forsa.html) | Forsa <br> Stern and RTL | 13 | 13–14 | 12–15 | 12–15 | 12–15 | | [22–24 January 2019](2019-01-24-ForschungsgruppeWahlen.html) | Forschungsgruppe Wahlen <br> ZDF | 13 | 12–14 | 12–15 | 12–15 | 11–16 | | [22–23 January 2019](2019-01-23-Infratestdimap.html) | Infratest dimap <br> ARD | 14 | 13–16 | 13–16 | 12–16 | 12–17 | | [16–23 January 2019](2019-01-23-GMS.html) | GMS | 13 | 12–14 | 12–15 | 12–15 | 11–16 | | [17–23 January 2019](2019-01-23-Emnid.html) | Emnid <br> Bild am Sonntag | 15 | 14–16 | 14–16 | 14–17 | 13–17 | | [18–21 January 2019](2019-01-21-INSAandYouGov.html) | INSA and YouGov <br> Bild | 13 | 12–13 | 12–14 | 12–14 | 11–15 | | [14–18 January 2019](2019-01-18-Forsa.html) | Forsa <br> Stern and RTL | 14 | 13–15 | 13–15 | 13–15 | 13–16 | | [5–17 January 2019](2019-01-17-Allensbach.html) | Allensbach <br> Frankfurter Allgemeine Zeitung | 16 | 14–17 | 14–17 | 14–18 | 13–19 | | [10–16 January 2019](2019-01-16-Emnid.html) | Emnid <br> Bild am Sonntag | 15 | 13–16 | 13–16 | 13–16 | 12–17 | | [11–14 January 2019](2019-01-14-INSAandYouGov.html) | INSA and YouGov <br> Bild | 14 | 13–15 | 13–15 | 12–15 | 12–16 | | [9–11 January 2019](2019-01-11-Forsa.html) | Forsa <br> Stern and RTL | 15 | 13–16 | 13–16 | 13–16 | 12–16 | | [8–10 January 2019](2019-01-10-ForschungsgruppeWahlen.html) | Forschungsgruppe Wahlen <br> ZDF | 13 | 12–15 | 12–15 | 11–15 | 11–16 | | [7–9 January 2019](2019-01-09-Infratestdimap.html) | Infratest dimap <br> ARD | 14 | 13–15 | 13–15 | 13–16 | 12–17 | | [3–9 January 2019](2019-01-09-Emnid.html) | Emnid <br> Bild am Sonntag | 14 | 14–16 | 13–16 | 13–16 | 12–16 | | [5–7 January 2019](2019-01-07-INSAandYouGov.html) | INSA and YouGov <br> Bild | 14 | 13–15 | 12–15 | 12–15 | 12–15 | | [2–4 January 2019](2019-01-04-Forsa.html) | Forsa <br> Stern and RTL | 14 | 12–15 | 12–15 | 12–15 | 11–17 | | [2–3 January 2019](2019-01-03-INSAandYouGov.html) | INSA and YouGov <br> Bild | 14 | 13–15 | 13–16 | 12–16 | 12–17 | | [21–27 December 2018](2018-12-27-YouGov.html) | YouGov <br> RedaktionsNetzwerk Deutschland | 14 | 13–15 | 13–17 | 13–17 | 13–18 | | [20–21 December 2018](2018-12-21-INSAandYouGov.html) | INSA and YouGov <br> Bild | 13 | 12–15 | 12–15 | 11–15 | 11–16 | | [17–21 December 2018](2018-12-21-Forsa.html) | Forsa <br> Stern and RTL | 13 | 12–14 | 12–15 | 12–15 | 11–15 | | [13–19 December 2018](2018-12-19-Emnid.html) | Emnid <br> Bild am Sonntag | 14 | 13–15 | 13–15 | 13–16 | 12–16 | | [14–17 December 2018](2018-12-17-INSAandYouGov.html) | INSA and YouGov <br> Bild | 15 | 14–15 | 14–16 | 13–16 | 13–16 | | [10–14 December 2018](2018-12-14-Forsa.html) | Forsa <br> Stern and RTL | 14 | 13–16 | 13–16 | 13–16 | 12–17 | | [11–13 December 2018](2018-12-13-ForschungsgruppeWahlen.html) | Forschungsgruppe Wahlen <br> ZDF | 14 | 13–15 | 13–16 | 12–16 | 12–17 | | [11–12 December 2018](2018-12-12-Infratestdimap.html) | Infratest dimap <br> ARD | 14 | 13–15 | 13–16 | 12–16 | 12–17 | | [6–12 December 2018](2018-12-12-GMS.html) | GMS | 13 | 12–15 | 12–16 | 11–16 | 11–16 | | [6–12 December 2018](2018-12-12-Emnid.html) | Emnid <br> Bild am Sonntag | 15 | 14–15 | 13–16 | 13–16 | 12–16 | | [1–12 December 2018](2018-12-12-Allensbach.html) | Allensbach <br> Frankfurter Allgemeine Zeitung | 16 | 15–17 | 14–17 | 14–18 | 13–18 | | [8–10 December 2018](2018-12-10-INSAandYouGov.html) | INSA and YouGov <br> Bild | 16 | 15–17 | 14–17 | 14–18 | 14–18 | | [7–9 December 2018](2018-12-09-Forsa.html) | Forsa <br> Stern and RTL | 13 | 12–15 | 12–15 | 11–16 | 11–16 | | [3–6 December 2018](2018-12-06-Forsa.html) | Forsa <br> Stern and RTL | 13 | 13–14 | 13–15 | 12–15 | 12–16 | | [3–5 December 2018](2018-12-05-Infratestdimap.html) | Infratest dimap <br> ARD | 13 | 12–15 | 12–15 | 12–15 | 11–16 | | [29 November–5 December 2018](2018-12-05-Emnid.html) | Emnid <br> Bild am Sonntag | 14 | 14–15 | 13–15 | 13–15 | 13–16 | | [30 November–3 December 2018](2018-12-03-INSAandYouGov.html) | INSA and YouGov <br> Bild | 12 | 11–14 | 11–14 | 11–14 | 11–15 | | [26–30 November 2018](2018-11-30-Forsa.html) | Forsa <br> Stern and RTL | 13 | 13–15 | 12–15 | 12–15 | 12–16 | | [27–28 November 2018](2018-11-28-Infratestdimap.html) | Infratest dimap <br> ARD | 13 | 12–15 | 12–15 | 11–15 | 11–16 | | [22–28 November 2018](2018-11-28-Emnid.html) | Emnid <br> Bild am Sonntag | 14 | 13–16 | 13–16 | 13–16 | 12–17 | | [23–27 November 2018](2018-11-27-YouGov.html) | YouGov <br> RedaktionsNetzwerk Deutschland | 14 | 13–15 | 13–15 | 13–16 | 12–16 | | [23–26 November 2018](2018-11-26-INSAandYouGov.html) | INSA and YouGov <br> Bild | 14 | 12–15 | 12–15 | 12–15 | 11–15 | | [19–23 November 2018](2018-11-23-Forsa.html) | Forsa <br> Stern and RTL | 13 | 12–14 | 12–15 | 12–15 | 12–15 | | [20–22 November 2018](2018-11-22-ForschungsgruppeWahlen.html) | Forschungsgruppe Wahlen <br> ZDF | 13 | 12–14 | 12–15 | 12–15 | 11–16 | | [15–21 November 2018](2018-11-21-Emnid.html) | Emnid <br> Bild am Sonntag | 15 | 13–15 | 13–15 | 13–15 | 13–16 | | [16–19 November 2018](2018-11-19-INSAandYouGov.html) | INSA and YouGov <br> Bild | 14 | 13–15 | 13–15 | 13–15 | 12–16 | | [12–16 November 2018](2018-11-16-Forsa.html) | Forsa <br> Stern and RTL | 13 | 12–14 | 12–15 | 12–15 | 12–16 | | [12–14 November 2018](2018-11-14-Infratestdimap.html) | Infratest dimap <br> ARD | 14 | 12–14 | 12–15 | 12–15 | 11–16 | | [8–14 November 2018](2018-11-14-Emnid.html) | Emnid <br> Bild am Sonntag | 14 | 13–15 | 13–16 | 13–16 | 12–16 | | [9–12 November 2018](2018-11-12-INSAandYouGov.html) | INSA and YouGov <br> Bild | 13 | 13–15 | 12–15 | 12–15 | 12–15 | | [5–9 November 2018](2018-11-09-Forsa.html) | Forsa <br> Stern and RTL | 13 | 13–14 | 12–14 | 12–15 | 12–15 | | [6–8 November 2018](2018-11-08-ForschungsgruppeWahlen.html) | Forschungsgruppe Wahlen <br> ZDF | 13 | 12–15 | 12–15 | 12–16 | 11–16 | | [5–7 November 2018](2018-11-07-Emnid.html) | Emnid <br> Bild am Sonntag | 14 | 13–16 | 13–16 | 13–16 | 12–17 | | [2–5 November 2018](2018-11-05-INSAandYouGov.html) | INSA and YouGov <br> Bild | 13 | 12–14 | 12–14 | 12–14 | 12–15 | | [28 October–4 November 2018](2018-11-04-YouGov.html) | YouGov <br> RedaktionsNetzwerk Deutschland | 13 | 13–14 | 12–15 | 12–15 | 11–16 | | [29 October–2 November 2018](2018-11-02-Forsa.html) | Forsa <br> Stern and RTL | 13 | 12–13 | 11–14 | 11–14 | 10–14 | | [25–31 October 2018](2018-10-31-Emnid.html) | Emnid <br> Bild am Sonntag | 13 | 12–15 | 12–15 | 12–15 | 11–16 | | [26–29 October 2018](2018-10-29-INSAandYouGov.html) | INSA and YouGov <br> Bild | 14 | 12–15 | 12–15 | 12–15 | 12–16 | | [22–26 October 2018](2018-10-26-Forsa.html) | Forsa <br> Stern and RTL | 13 | 13–14 | 12–14 | 12–15 | 12–15 | | [18–24 October 2018](2018-10-24-Emnid.html) | Emnid <br> Bild am Sonntag | 14 | 13–15 | 13–16 | 13–16 | 13–17 | | [19–22 October 2018](2018-10-22-INSAandYouGov.html) | INSA and YouGov <br> Bild | 15 | 14–16 | 14–16 | 14–17 | 13–17 | | [15–19 October 2018](2018-10-19-Forsa.html) | Forsa <br> Stern and RTL | 13 | 13–14 | 12–14 | 12–15 | 12–15 | | [16–18 October 2018](2018-10-18-ForschungsgruppeWahlen.html) | Forschungsgruppe Wahlen <br> ZDF | 14 | 12–15 | 12–15 | 12–15 | 11–16 | | [16–17 October 2018](2018-10-17-Infratestdimap.html) | Infratest dimap <br> ARD | 13 | 13–15 | 12–15 | 12–15 | 11–16 | | [11–17 October 2018](2018-10-17-Emnid.html) | Emnid <br> Bild am Sonntag | 14 | 13–15 | 12–16 | 12–16 | 12–17 | | [12–15 October 2018](2018-10-15-INSAandYouGov.html) | INSA and YouGov <br> Bild | 15 | 13–15 | 13–15 | 13–16 | 12–16 | | [8–12 October 2018](2018-10-12-Forsa.html) | Forsa <br> Stern and RTL | 15 | 14–16 | 14–17 | 14–17 | 13–18 | | [28 September–11 October 2018](2018-10-11-Allensbach.html) | Allensbach <br> Frankfurter Allgemeine Zeitung | 18 | 17–19 | 17–20 | 16–20 | 16–21 | | [8–10 October 2018](2018-10-10-Infratestdimap.html) | Infratest dimap <br> ARD | 14 | 13–15 | 13–15 | 13–16 | 12–17 | | [4–10 October 2018](2018-10-10-GMS.html) | GMS | 14 | 13–16 | 13–16 | 12–16 | 12–17 | | [4–10 October 2018](2018-10-10-Emnid.html) | Emnid <br> Bild am Sonntag | 16 | 15–17 | 15–17 | 15–18 | 14–18 | | [5–8 October 2018](2018-10-08-INSAandYouGov.html) | INSA and YouGov <br> Bild | 16 | 14–16 | 14–17 | 14–17 | 13–17 | | [1–5 October 2018](2018-10-05-Forsa.html) | Forsa <br> Stern and RTL | 15 | 14–16 | 14–17 | 13–17 | 13–17 | | [27 September–2 October 2018](2018-10-02-Emnid.html) | Emnid <br> Bild am Sonntag | 16 | 15–18 | 15–18 | 14–18 | 14–19 | | [28 September–1 October 2018](2018-10-01-INSAandYouGov.html) | INSA and YouGov <br> Bild | 15 | 14–16 | 14–17 | 14–17 | 13–17 | | [24–28 September 2018](2018-09-28-Forsa.html) | Forsa <br> Stern and RTL | 16 | 14–16 | 14–16 | 14–17 | 13–17 | | [25–27 September 2018](2018-09-27-ForschungsgruppeWahlen.html) | Forschungsgruppe Wahlen <br> ZDF | 16 | 15–17 | 15–18 | 14–18 | 13–19 | | [20–26 September 2018](2018-09-26-GMS.html) | GMS | 15 | 14–17 | 13–17 | 13–18 | 12–18 | | [20–26 September 2018](2018-09-26-Emnid.html) | Emnid <br> Bild am Sonntag | 15 | 14–16 | 14–16 | 13–17 | 13–17 | | [21–25 September 2018](2018-09-25-YouGov.html) | YouGov <br> RedaktionsNetzwerk Deutschland | 16 | 15–17 | 15–17 | 15–18 | 14–19 | | [21–24 September 2018](2018-09-24-INSAandYouGov.html) | INSA and YouGov <br> Bild | 15 | 14–16 | 14–17 | 14–17 | 13–17 | | [17–21 September 2018](2018-09-21-Forsa.html) | Forsa <br> Stern and RTL | 16 | 15–17 | 15–18 | 15–18 | 14–18 | | [17–19 September 2018](2018-09-19-Infratestdimap.html) | Infratest dimap <br> ARD | 16 | 15–17 | 15–18 | 14–18 | 13–19 | | [19 September 2018](2018-09-19-INSA.html) | INSA <br> Focus | 16 | 14–17 | 14–18 | 14–18 | 13–19 | | [13–19 September 2018](2018-09-19-Emnid.html) | Emnid <br> Bild am Sonntag | 16 | 15–17 | 15–18 | 15–18 | 14–18 | | [14–17 September 2018](2018-09-17-INSAandYouGov.html) | INSA and YouGov <br> Bild | 16 | 16–17 | 15–18 | 15–18 | 14–18 | | [10–14 September 2018](2018-09-14-Forsa.html) | Forsa <br> Stern and RTL | 17 | 16–18 | 16–19 | 16–19 | 15–20 | | [11–13 September 2018](2018-09-13-ForschungsgruppeWahlen.html) | Forschungsgruppe Wahlen <br> ZDF | 19 | 18–20 | 18–21 | 17–21 | 17–22 | | [1–13 September 2018](2018-09-13-Allensbach.html) | Allensbach <br> Frankfurter Allgemeine Zeitung | 19 | 17–20 | 17–20 | 16–21 | 16–21 | | [6–12 September 2018](2018-09-12-Emnid.html) | Emnid <br> Bild am Sonntag | 17 | 16–18 | 15–18 | 15–19 | 15–19 | | [7–10 September 2018](2018-09-10-INSAandYouGov.html) | INSA and YouGov <br> Bild | 16 | 15–17 | 15–17 | 15–18 | 14–18 | | [4–10 September 2018](2018-09-10-GMS.html) | GMS | 16 | 15–17 | 15–18 | 14–18 | 14–19 | | [3–7 September 2018](2018-09-07-Forsa.html) | Forsa <br> Stern and RTL | 15 | 14–16 | 14–17 | 14–17 | 13–17 | | [3–5 September 2018](2018-09-05-Infratestdimap.html) | Infratest dimap <br> ARD | 17 | 16–18 | 16–19 | 16–19 | 15–19 | | [30 August–5 September 2018](2018-09-05-Emnid.html) | Emnid <br> Bild am Sonntag | 16 | 15–17 | 15–17 | 15–18 | 14–18 | | [31 August–3 September 2018](2018-09-03-INSAandYouGov.html) | INSA and YouGov <br> Bild | 15 | 14–16 | 14–16 | 14–17 | 13–17 | | [27–31 August 2018](2018-08-31-Forsa.html) | Forsa <br> Stern and RTL | 16 | 15–17 | 15–18 | 15–18 | 14–18 | | [28–30 August 2018](2018-08-30-ForschungsgruppeWahlen.html) | Forschungsgruppe Wahlen <br> ZDF | 18 | 16–19 | 15–19 | 15–20 | 14–20 | | [23–29 August 2018](2018-08-29-Emnid.html) | Emnid <br> Bild am Sonntag | 18 | 17–19 | 17–19 | 17–20 | 16–20 | | [24–28 August 2018](2018-08-28-YouGov.html) | YouGov <br> RedaktionsNetzwerk Deutschland | 16 | 15–18 | 15–18 | 14–18 | 14–19 | | [24–27 August 2018](2018-08-27-INSAandYouGov.html) | INSA and YouGov <br> Bild | 16 | 15–17 | 15–17 | 15–17 | 14–18 | | [20–24 August 2018](2018-08-24-Forsa.html) | Forsa <br> Stern and RTL | 17 | 16–18 | 16–18 | 16–19 | 15–20 | | [20–22 August 2018](2018-08-22-Infratestdimap.html) | Infratest dimap <br> ARD | 17 | 16–19 | 15–19 | 15–19 | 14–20 | | [16–22 August 2018](2018-08-22-Emnid.html) | Emnid <br> Bild am Sonntag | 17 | 16–18 | 16–19 | 16–19 | 15–19 | | [16–20 August 2018](2018-08-20-INSAandYouGov.html) | INSA and YouGov <br> Bild | 15 | 15–16 | 15–16 | 15–17 | 14–17 | | [13–17 August 2018](2018-08-17-Forsa.html) | Forsa <br> Stern and RTL | 17 | 16–19 | 16–19 | 15–19 | 15–19 | | [9–15 August 2018](2018-08-15-Emnid.html) | Emnid <br> Bild am Sonntag | 17 | 16–17 | 16–17 | 15–17 | 15–18 | | [10–13 August 2018](2018-08-13-INSAandYouGov.html) | INSA and YouGov <br> Bild | 17 | 15–18 | 15–18 | 15–18 | 14–19 | | [6–10 August 2018](2018-08-10-Forsa.html) | Forsa <br> Stern and RTL | 17 | 16–18 | 16–19 | 16–19 | 15–19 | | [7–9 August 2018](2018-08-09-ForschungsgruppeWahlen.html) | Forschungsgruppe Wahlen <br> ZDF | 17 | 16–18 | 16–19 | 15–19 | 15–20 | | [27 July–9 August 2018](2018-08-09-Allensbach.html) | Allensbach <br> Frankfurter Allgemeine Zeitung | 19 | 18–21 | 18–21 | 17–21 | 17–22 | | [2–8 August 2018](2018-08-08-Emnid.html) | Emnid <br> Bild am Sonntag | 16 | 15–17 | 15–17 | 15–18 | 14–18 | | [3–6 August 2018](2018-08-06-INSAandYouGov.html) | INSA and YouGov <br> Bild | 16 | 15–17 | 15–18 | 14–18 | 14–18 | | [30 July–3 August 2018](2018-08-03-Forsa.html) | Forsa <br> Stern and RTL | 17 | 16–18 | 16–19 | 16–19 | 15–19 | | [30 July–1 August 2018](2018-08-01-Infratestdimap.html) | Infratest dimap <br> ARD | 17 | 16–18 | 16–19 | 15–19 | 15–20 | | [26 July–1 August 2018](2018-08-01-Emnid.html) | Emnid <br> Bild am Sonntag | 17 | 16–18 | 16–18 | 16–18 | 15–19 | | [25–31 July 2018](2018-07-31-GMS.html) | GMS | 16 | 15–18 | 14–19 | 14–19 | 13–19 | | [27–30 July 2018](2018-07-30-INSAandYouGov.html) | INSA and YouGov <br> Bild | 17 | 16–18 | 16–18 | 16–19 | 15–19 | | [23–27 July 2018](2018-07-27-Forsa.html) | Forsa <br> Stern and RTL | 17 | 16–18 | 16–19 | 16–19 | 15–19 | | [24–25 July 2018](2018-07-25-Infratestdimap.html) | Infratest dimap <br> ARD | 17 | 15–19 | 15–19 | 15–19 | 14–20 | | [19–25 July 2018](2018-07-25-Emnid.html) | Emnid <br> Bild am Sonntag | 17 | 16–18 | 16–18 | 16–19 | 15–19 | | [20–24 July 2018](2018-07-24-YouGov.html) | YouGov <br> RedaktionsNetzwerk Deutschland | 16 | 15–17 | 15–17 | 14–18 | 14–19 | | [20–23 July 2018](2018-07-23-INSAandYouGov.html) | INSA and YouGov <br> Bild | 17 | 16–18 | 16–18 | 16–19 | 15–19 | | [16–20 July 2018](2018-07-20-Forsa.html) | Forsa <br> Stern and RTL | 17 | 16–18 | 16–18 | 15–19 | 15–19 | | [12–18 July 2018](2018-07-18-Emnid.html) | Emnid <br> Bild am Sonntag | 18 | 17–19 | 17–19 | 17–20 | 16–20 | | [13–16 July 2018](2018-07-16-INSAandYouGov.html) | INSA and YouGov <br> Bild | 16 | 15–17 | 15–17 | 15–18 | 14–18 | | [9–13 July 2018](2018-07-13-Forsa.html) | Forsa <br> Stern and RTL | 16 | 15–17 | 15–17 | 15–18 | 14–18 | | [9–12 July 2018](2018-07-12-ForschungsgruppeWahlen.html) | Forschungsgruppe Wahlen <br> ZDF | 17 | 16–19 | 16–19 | 15–19 | 15–20 | | [1–12 July 2018](2018-07-12-Allensbach.html) | Allensbach <br> Frankfurter Allgemeine Zeitung | 19 | 18–20 | 17–21 | 17–21 | 16–22 | | [5–11 July 2018](2018-07-11-GMS.html) | GMS | 16 | 15–17 | 15–18 | 14–18 | 14–19 | | [5–11 July 2018](2018-07-11-Emnid.html) | Emnid <br> Bild am Sonntag | 17 | 16–18 | 16–18 | 16–19 | 15–19 | | [6–9 July 2018](2018-07-09-INSAandYouGov.html) | INSA and YouGov <br> Bild | 16 | 15–17 | 14–17 | 14–18 | 14–19 | | [2–6 July 2018](2018-07-06-Forsa.html) | Forsa <br> Stern and RTL | 16 | 15–17 | 15–17 | 15–18 | 14–18 | | [3–4 July 2018](2018-07-04-Infratestdimap.html) | Infratest dimap <br> ARD | 17 | 16–18 | 15–19 | 15–19 | 15–20 | | [28 June–4 July 2018](2018-07-04-Emnid.html) | Emnid <br> Bild am Sonntag | 16 | 15–17 | 15–17 | 14–18 | 14–18 | | [29 June–2 July 2018](2018-07-02-INSAandYouGov.html) | INSA and YouGov <br> Bild | 18 | 17–19 | 17–19 | 17–20 | 16–20 | | [25–29 June 2018](2018-06-29-Forsa.html) | Forsa <br> Stern and RTL | 16 | 15–17 | 15–18 | 15–18 | 14–18 | | [25–28 June 2018](2018-06-28-ForschungsgruppeWahlen.html) | Forschungsgruppe Wahlen <br> ZDF | 17 | 16–19 | 15–19 | 14–19 | 14–20 | | [21–28 June 2018](2018-06-28-Emnid.html) | Emnid <br> Bild am Sonntag | 18 | 17–19 | 17–19 | 17–20 | 16–20 | | [22–26 June 2018](2018-06-26-YouGov.html) | YouGov <br> RedaktionsNetzwerk Deutschland | 16 | 15–17 | 15–18 | 14–18 | 14–18 | | [25–26 June 2018](2018-06-26-Infratestdimap.html) | Infratest dimap <br> ARD | 18 | 17–20 | 16–20 | 16–20 | 16–21 | | [22–25 June 2018](2018-06-25-INSAandYouGov.html) | INSA and YouGov <br> Bild | 18 | 17–19 | 17–20 | 17–20 | 17–21 | | [18–22 June 2018](2018-06-22-Forsa.html) | Forsa <br> Stern and RTL | 16 | 15–17 | 15–17 | 15–18 | 14–18 | | [14–20 June 2018](2018-06-20-Emnid.html) | Emnid <br> Bild am Sonntag | 17 | 16–18 | 16–18 | 16–18 | 15–19 | | [15–18 June 2018](2018-06-18-INSAandYouGov.html) | INSA and YouGov <br> Bild | 18 | 17–19 | 17–19 | 16–20 | 16–21 | | [14–15 June 2018](2018-06-15-Forsa.html) | Forsa <br> Stern and RTL | 15 | 13–17 | 13–17 | 13–18 | 12–19 | | [11–13 June 2018](2018-06-13-Infratestdimap.html) | Infratest dimap <br> ARD | 17 | 16–18 | 16–19 | 15–19 | 15–20 | | [11–13 June 2018](2018-06-13-Forsa.html) | Forsa <br> Stern and RTL | 18 | 16–19 | 15–19 | 15–19 | 15–20 | | [7–13 June 2018](2018-06-13-Emnid.html) | Emnid <br> Bild am Sonntag | 17 | 16–18 | 16–18 | 16–19 | 15–19 | | [1–13 June 2018](2018-06-13-Allensbach.html) | Allensbach <br> Frankfurter Allgemeine Zeitung | 20 | 19–22 | 18–22 | 18–22 | 17–23 | | [8–11 June 2018](2018-06-11-INSAandYouGov.html) | INSA and YouGov <br> Bild | 16 | 15–17 | 15–17 | 15–18 | 14–18 | | [4–8 June 2018](2018-06-08-Forsa.html) | Forsa <br> Stern and RTL | 17 | 16–18 | 16–19 | 16–19 | 15–19 | | [5–7 June 2018](2018-06-07-ForschungsgruppeWahlen.html) | Forschungsgruppe Wahlen <br> ZDF | 19 | 18–21 | 17–21 | 17–21 | 17–22 | | [30 May–6 June 2018](2018-06-06-Emnid.html) | Emnid <br> Bild am Sonntag | 18 | 17–19 | 17–20 | 16–20 | 16–21 | | [1–4 June 2018](2018-06-04-INSAandYouGov.html) | INSA and YouGov <br> Bild | 16 | 15–17 | 15–17 | 15–18 | 14–18 | | [28 May–1 June 2018](2018-06-01-Forsa.html) | Forsa <br> Stern and RTL | 17 | 16–18 | 16–19 | 16–19 | 15–19 | | [25–29 May 2018](2018-05-29-YouGov.html) | YouGov <br> RedaktionsNetzwerk Deutschland | 17 | 15–17 | 15–18 | 15–18 | 14–19 | | [24–29 May 2018](2018-05-29-Emnid.html) | Emnid <br> Bild am Sonntag | 17 | 16–18 | 16–19 | 15–19 | 15–20 | | [25–28 May 2018](2018-05-28-INSAandYouGov.html) | INSA and YouGov <br> Bild | 16 | 15–17 | 15–18 | 15–18 | 14–18 | | [22–25 May 2018](2018-05-25-Forsa.html) | Forsa <br> Stern and RTL | 17 | 16–19 | 16–19 | 15–19 | 15–20 | | [17–23 May 2018](2018-05-23-Emnid.html) | Emnid <br> Bild am Sonntag | 16 | 15–17 | 14–18 | 14–18 | 14–19 | | [18–22 May 2018](2018-05-22-INSAandYouGov.html) | INSA and YouGov <br> Bild | 16 | 15–17 | 14–17 | 14–17 | 14–18 | | [14–18 May 2018](2018-05-18-Forsa.html) | Forsa <br> Stern and RTL | 17 | 16–18 | 16–19 | 16–19 | 15–19 | | [15–17 May 2018](2018-05-17-ForschungsgruppeWahlen.html) | Forschungsgruppe Wahlen <br> ZDF | 19 | 18–20 | 17–21 | 17–21 | 16–22 | | [14–16 May 2018](2018-05-16-Infratestdimap.html) | Infratest dimap <br> ARD | 16 | 15–18 | 14–18 | 14–18 | 13–19 | | [11–16 May 2018](2018-05-16-GMS.html) | GMS | 15 | 14–17 | 13–17 | 13–18 | 12–19 | | [9–16 May 2018](2018-05-16-Emnid.html) | Emnid <br> Bild am Sonntag | 16 | 15–17 | 15–17 | 15–18 | 14–18 | | [11–14 May 2018](2018-05-14-INSAandYouGov.html) | INSA and YouGov <br> Bild | 16 | 15–17 | 15–17 | 15–18 | 14–18 | | [7–11 May 2018](2018-05-11-Forsa.html) | Forsa <br> Stern and RTL | 16 | 15–17 | 15–18 | 15–18 | 14–19 | | [7–8 May 2018](2018-05-08-Infratestdimap.html) | Infratest dimap <br> ARD | 18 | 16–19 | 16–19 | 15–19 | 15–20 | | [3–8 May 2018](2018-05-08-Emnid.html) | Emnid <br> Bild am Sonntag | 16 | 15–17 | 14–17 | 14–18 | 14–19 | | [24 April–8 May 2018](2018-05-08-Allensbach.html) | Allensbach <br> Frankfurter Allgemeine Zeitung | 19 | 17–20 | 17–21 | 17–21 | 16–22 | | [4–7 May 2018](2018-05-07-INSAandYouGov.html) | INSA and YouGov <br> Bild | 16 | 15–17 | 15–17 | 15–18 | 14–18 | | [30 April–4 May 2018](2018-05-04-Forsa.html) | Forsa <br> Stern and RTL | 17 | 16–18 | 16–18 | 15–19 | 15–20 | | [26 April–2 May 2018](2018-05-02-Emnid.html) | Emnid <br> Bild am Sonntag | 16 | 15–18 | 15–18 | 15–18 | 14–19 | | [27–30 April 2018](2018-04-30-INSAandYouGov.html) | INSA and YouGov <br> Bild | 16 | 15–17 | 15–18 | 14–18 | 14–18 | | [23–27 April 2018](2018-04-27-Forsa.html) | Forsa <br> Stern and RTL | 16 | 15–17 | 15–18 | 14–18 | 14–18 | | [20–26 April 2018](2018-04-26-GMS.html) | GMS | 16 | 15–18 | 15–18 | 14–19 | 13–19 | | [24–26 April 2018](2018-04-26-ForschungsgruppeWahlen.html) | Forschungsgruppe Wahlen <br> ZDF | 19 | 18–21 | 17–21 | 17–21 | 17–22 | | [19–25 April 2018](2018-04-25-Emnid.html) | Emnid <br> Bild am Sonntag | 17 | 16–18 | 16–18 | 16–19 | 15–19 | | [20–24 April 2018](2018-04-24-YouGov.html) | YouGov <br> RedaktionsNetzwerk Deutschland | 17 | 16–18 | 16–19 | 15–19 | 15–20 | | [20–23 April 2018](2018-04-23-INSAandYouGov.html) | INSA and YouGov <br> Bild | 17 | 16–18 | 16–18 | 15–19 | 15–19 | | [16–20 April 2018](2018-04-20-Forsa.html) | Forsa <br> Stern and RTL | 17 | 16–18 | 16–19 | 16–19 | 15–19 | | [16–18 April 2018](2018-04-18-Infratestdimap.html) | Infratest dimap <br> ARD | 17 | 15–18 | 15–18 | 14–18 | 13–19 | | [12–18 April 2018](2018-04-18-Emnid.html) | Emnid <br> Bild am Sonntag | 17 | 16–18 | 16–18 | 16–19 | 15–19 | | [3–17 April 2018](2018-04-17-Allensbach.html) | Allensbach <br> Frankfurter Allgemeine Zeitung | 20 | 18–21 | 18–22 | 18–22 | 17–22 | | [13–16 April 2018](2018-04-16-INSAandYouGov.html) | INSA and YouGov <br> Bild | 18 | 17–19 | 16–19 | 16–19 | 16–20 | | [9–13 April 2018](2018-04-13-Forsa.html) | Forsa <br> Stern and RTL | 18 | 17–19 | 17–19 | 16–20 | 16–20 | | [10–12 April 2018](2018-04-12-ForschungsgruppeWahlen.html) | Forschungsgruppe Wahlen <br> ZDF | 18 | 17–20 | 16–20 | 16–21 | 15–21 | | [5–11 April 2018](2018-04-11-Emnid.html) | Emnid <br> Bild am Sonntag | 17 | 16–18 | 16–19 | 16–19 | 15–19 | | [6–9 April 2018](2018-04-09-INSAandYouGov.html) | INSA and YouGov <br> Bild | 17 | 16–18 | 15–18 | 15–18 | 15–19 | | [3–6 April 2018](2018-04-06-Forsa.html) | Forsa <br> Stern and RTL | 19 | 18–20 | 17–21 | 17–21 | 17–22 | | [29 March–5 April 2018](2018-04-05-Emnid.html) | Emnid <br> Bild am Sonntag | 16 | 15–18 | 15–18 | 14–18 | 14–19 | | [23 March–4 April 2018](2018-04-04-pollytix.html) | pollytix | 18 | 16–19 | 16–20 | 16–20 | 15–21 | | [3–4 April 2018](2018-04-04-Infratestdimap.html) | Infratest dimap <br> ARD | 17 | 16–18 | 16–18 | 15–19 | 15–20 | | [29–31 March 2018](2018-03-31-INSAandYouGov.html) | INSA and YouGov <br> Bild | 17 | 16–19 | 15–19 | 15–20 | 14–21 | | [26–29 March 2018](2018-03-29-Forsa.html) | Forsa <br> Stern and RTL | 17 | 16–18 | 16–19 | 16–19 | 15–20 | | [22–28 March 2018](2018-03-28-Emnid.html) | Emnid <br> Bild am Sonntag | 17 | 16–18 | 16–18 | 16–19 | 15–19 | | [23–27 March 2018](2018-03-27-YouGov.html) | YouGov <br> RedaktionsNetzwerk Deutschland | 16 | 15–17 | 15–18 | 14–18 | 14–19 | | [23–26 March 2018](2018-03-26-INSAandYouGov.html) | INSA and YouGov <br> Bild | 16 | 15–17 | 15–18 | 15–18 | 14–18 | | [19–23 March 2018](2018-03-23-Forsa.html) | Forsa <br> Stern and RTL | 18 | 17–19 | 17–20 | 16–20 | 16–20 | | [20–21 March 2018](2018-03-21-Infratestdimap.html) | Infratest dimap <br> ARD | 18 | 17–20 | 16–20 | 16–20 | 15–21 | | [16–21 March 2018](2018-03-21-GMS.html) | GMS | 17 | 16–18 | 16–19 | 15–19 | 14–20 | | [15–21 March 2018](2018-03-21-Emnid.html) | Emnid <br> Bild am Sonntag | 17 | 16–18 | 16–19 | 15–19 | 15–20 | | [16–19 March 2018](2018-03-19-INSAandYouGov.html) | INSA and YouGov <br> Bild | 17 | 15–18 | 15–18 | 15–18 | 15–19 | | [12–16 March 2018](2018-03-16-Forsa.html) | Forsa <br> Stern and RTL | 18 | 17–19 | 17–19 | 17–20 | 16–20 | | [13–15 March 2018](2018-03-15-ForschungsgruppeWahlen.html) | Forschungsgruppe Wahlen <br> ZDF | 18 | 17–20 | 17–20 | 16–20 | 16–21 | | [2–15 March 2018](2018-03-15-Allensbach.html) | Allensbach <br> Frankfurter Allgemeine Zeitung | 18 | 17–20 | 16–20 | 16–21 | 15–21 | | [8–14 March 2018](2018-03-14-Emnid.html) | Emnid <br> Bild am Sonntag | 18 | 17–19 | 17–20 | 16–20 | 16–20 | | [9–12 March 2018](2018-03-12-INSAandYouGov.html) | INSA and YouGov <br> Bild | 17 | 15–18 | 15–18 | 15–18 | 15–19 | | [5–9 March 2018](2018-03-09-Forsa.html) | Forsa <br> Stern and RTL | 17 | 16–18 | 16–19 | 16–19 | 15–19 | | [1–7 March 2018](2018-03-07-Emnid.html) | Emnid <br> Bild am Sonntag | 18 | 17–19 | 17–19 | 17–20 | 16–21 | | [5 March 2018](2018-03-05-INSAandYouGov.html) | INSA and YouGov <br> Bild | 14 | 13–16 | 12–16 | 12–17 | 12–17 | | [4–5 March 2018](2018-03-05-Forsa.html) | Forsa <br> Stern and RTL | 18 | 16–20 | 16–20 | 16–20 | 15–21 | | [26 February–2 March 2018](2018-03-02-Forsa.html) | Forsa <br> Stern and RTL | 17 | 16–18 | 16–19 | 15–19 | 15–19 | | [26–28 February 2018](2018-02-28-YouGov.html) | YouGov <br> RedaktionsNetzwerk Deutschland | 15 | 14–16 | 14–17 | 14–17 | 13–18 | | [26–28 February 2018](2018-02-28-Infratestdimap.html) | Infratest dimap <br> ARD | 17 | 16–18 | 16–19 | 15–19 | 15–20 | | [22–28 February 2018](2018-02-28-Emnid.html) | Emnid <br> Bild am Sonntag | 15 | 14–16 | 14–17 | 14–17 | 13–18 | | [23–26 February 2018](2018-02-26-INSAandYouGov.html) | INSA and YouGov <br> Bild | 15 | 13–16 | 13–17 | 13–17 | 12–18 | | [19–23 February 2018](2018-02-23-Forsa.html) | Forsa <br> Stern and RTL | 17 | 16–18 | 16–19 | 16–19 | 15–20 | | [20–22 February 2018](2018-02-22-ForschungsgruppeWahlen.html) | Forschungsgruppe Wahlen <br> ZDF | 16 | 15–18 | 15–18 | 14–18 | 14–19 | | [20–21 February 2018](2018-02-21-Infratestdimap.html) | Infratest dimap <br> ARD | 16 | 15–18 | 15–18 | 14–19 | 14–19 | | [15–21 February 2018](2018-02-21-Emnid.html) | Emnid <br> Bild am Sonntag | 16 | 15–17 | 15–18 | 15–18 | 14–18 | | [16–19 February 2018](2018-02-19-INSAandYouGov.html) | INSA and YouGov <br> Bild | 15 | 14–16 | 14–16 | 13–16 | 13–17 | | [12–16 February 2018](2018-02-16-Forsa.html) | Forsa <br> Stern and RTL | 15 | 14–16 | 14–17 | 14–17 | 13–18 | | [13–15 February 2018](2018-02-15-Infratestdimap.html) | Infratest dimap <br> ARD | 15 | 14–17 | 14–17 | 13–18 | 13–18 | | [2–15 February 2018](2018-02-15-Allensbach.html) | Allensbach <br> Frankfurter Allgemeine Zeitung | 17 | 15–18 | 15–18 | 15–19 | 14–19 | | [8–14 February 2018](2018-02-14-Emnid.html) | Emnid <br> Bild am Sonntag | 18 | 17–19 | 17–20 | 16–20 | 16–21 | | [9–12 February 2018](2018-02-12-INSAandYouGov.html) | INSA and YouGov <br> Bild | 16 | 15–17 | 15–17 | 14–17 | 14–18 | | [7–8 February 2018](2018-02-08-Forsa.html) | Forsa <br> Stern and RTL | 17 | 16–19 | 15–19 | 15–20 | 14–20 | | [1–7 February 2018](2018-02-07-GMS.html) | GMS | 17 | 16–19 | 15–19 | 15–20 | 14–20 | | [1–7 February 2018](2018-02-07-Emnid.html) | Emnid <br> Bild am Sonntag | 19 | 18–21 | 17–21 | 17–21 | 16–22 | | [2–5 February 2018](2018-02-05-INSAandYouGov.html) | INSA and YouGov <br> Bild | 16 | 15–17 | 15–18 | 15–18 | 14–18 | | [27 December 2017–2 February 2018](2018-02-02-GMS.html) | GMS | 19 | 17–20 | 17–21 | 17–22 | 16–22 | | [29 January–2 February 2018](2018-02-02-Forsa.html) | Forsa <br> Stern and RTL | 17 | 16–18 | 16–19 | 16–19 | 15–19 | | [30 January–1 February 2018](2018-02-01-ForschungsgruppeWahlen.html) | Forschungsgruppe Wahlen <br> ZDF | 18 | 17–19 | 17–20 | 16–20 | 16–21 | | [29–31 January 2018](2018-01-31-Infratestdimap.html) | Infratest dimap <br> ARD | 17 | 16–18 | 16–19 | 15–19 | 15–20 | | [25–31 January 2018](2018-01-31-Emnid.html) | Emnid <br> Bild am Sonntag | 19 | 18–20 | 17–21 | 17–21 | 16–22 | | [26–29 January 2018](2018-01-29-INSAandYouGov.html) | INSA and YouGov <br> Bild | 17 | 16–18 | 16–18 | 15–19 | 15–19 | | [22–26 January 2018](2018-01-26-Forsa.html) | Forsa <br> Stern and RTL | 17 | 16–18 | 16–18 | 16–19 | 15–19 | | [22–24 January 2018](2018-01-24-Infratestdimap.html) | Infratest dimap <br> ARD | 18 | 17–19 | 16–20 | 16–20 | 15–21 | | [18–24 January 2018](2018-01-24-Emnid.html) | Emnid <br> Bild am Sonntag | 19 | 18–21 | 17–21 | 17–21 | 17–22 | | [19–23 January 2018](2018-01-23-YouGov.html) | YouGov <br> RedaktionsNetzwerk Deutschland | 18 | 17–19 | 17–20 | 16–20 | 16–21 | | [22 January 2018](2018-01-22-INSAandYouGov.html) | INSA and YouGov <br> Bild | 17 | 16–19 | 15–19 | 15–19 | 14–20 | | [22 January 2018](2018-01-22-Forsa.html) | Forsa <br> Stern and RTL | 16 | 15–17 | 15–18 | 15–18 | 14–19 | | [15–19 January 2018](2018-01-19-Forsa.html) | Forsa <br> Stern and RTL | 17 | 16–18 | 16–19 | 15–19 | 15–19 | | [16–18 January 2018](2018-01-18-ForschungsgruppeWahlen.html) | Forschungsgruppe Wahlen <br> ZDF | 19 | 18–20 | 17–21 | 17–21 | 16–22 | | [5–18 January 2018](2018-01-18-Allensbach.html) | Allensbach <br> Frankfurter Allgemeine Zeitung | 20 | 19–21 | 18–22 | 18–22 | 17–23 | | [15–17 January 2018](2018-01-17-Forsa.html) | Forsa <br> Stern and RTL | 17 | 16–19 | 16–19 | 15–19 | 15–20 | | [11–17 January 2018](2018-01-17-Emnid.html) | Emnid <br> Bild am Sonntag | 20 | 19–21 | 18–22 | 18–22 | 17–23 | | [12–15 January 2018](2018-01-15-INSAandYouGov.html) | INSA and YouGov <br> Bild | 18 | 17–19 | 16–19 | 16–19 | 16–20 | | [8–12 January 2018](2018-01-12-Forsa.html) | Forsa <br> Stern and RTL | 19 | 18–20 | 18–20 | 18–21 | 17–21 | | [4–10 January 2018](2018-01-10-Emnid.html) | Emnid <br> Bild am Sonntag | 20 | 19–21 | 18–21 | 18–22 | 18–23 | | [5–8 January 2018](2018-01-08-INSAandYouGov.html) | INSA and YouGov <br> Bild | 18 | 17–20 | 17–20 | 17–21 | 16–21 | | [2–5 January 2018](2018-01-05-Forsa.html) | Forsa <br> Stern and RTL | 19 | 18–20 | 18–20 | 17–21 | 17–21 | | [2–3 January 2018](2018-01-03-Infratestdimap.html) | Infratest dimap <br> ARD | 20 | 19–21 | 19–21 | 18–22 | 18–23 | | [21 December 2017–3 January 2018](2018-01-03-Emnid.html) | Emnid <br> Bild am Sonntag | 19 | 18–20 | 17–21 | 17–21 | 17–22 | | [29 December 2017–2 January 2018](2018-01-02-INSAandYouGov.html) | INSA and YouGov <br> Bild | 18 | 17–20 | 17–20 | 17–20 | 16–21 | ### Probability Mass Function ![Graph with seats probability mass function not yet produced](average-seats-pmf-spdsd.png "Seats Probability Mass Function") The following table shows the probability mass function per seat for the [poll average](average.html) for SPD (S&D). | Number of Seats | Probability | Accumulated | Special Marks | |:---------------:|:-----------:|:-----------:|:-------------:| | 13 | 0.4% | 100% | | | 14 | 7% | 99.6% | | | 15 | 25% | 93% | | | 16 | 29% | 68% | Median | | 17 | 25% | 39% | | | 18 | 12% | 14% | | | 19 | 2% | 2% | | | 20 | 0.1% | 0.1% | | | 21 | 0% | 0% | | | 22 | 0% | 0% | | | 23 | 0% | 0% | | | 24 | 0% | 0% | | | 25 | 0% | 0% | | | 26 | 0% | 0% | | | 27 | 0% | 0% | Last Result |
Java
UTF-8
2,330
2.265625
2
[]
no_license
package com.zyy.mowa.mapper; import com.zyy.mowa.dao.WorkGroup; import org.apache.ibatis.jdbc.SQL; public class WorkGroupSqlProvider { public String insertSelective(WorkGroup record) { SQL sql = new SQL(); sql.INSERT_INTO("ma_workgroup"); if (record.getId() != null) { sql.VALUES("Id", "#{id,jdbcType=INTEGER}"); } if (record.getWorkgroupname() != null) { sql.VALUES("WorkGroupName", "#{workgroupname,jdbcType=VARCHAR}"); } if (record.getInvitecode() != null) { sql.VALUES("InviteCode", "#{invitecode,jdbcType=VARCHAR}"); } if (record.getCreateuserid() != null) { sql.VALUES("CreateUserId", "#{createuserid,jdbcType=INTEGER}"); } if (record.getCreattime() != null) { sql.VALUES("CreatTime", "#{creattime,jdbcType=TIMESTAMP}"); } if (record.getWrokgroupdesc() != null) { sql.VALUES("WrokGroupDesc", "#{wrokgroupdesc,jdbcType=VARCHAR}"); } if (record.getIspublic() != null) { sql.VALUES("IsPublic", "#{ispublic,jdbcType=BIT}"); } return sql.toString(); } public String updateByPrimaryKeySelective(WorkGroup record) { SQL sql = new SQL(); sql.UPDATE("ma_workgroup"); if (record.getWorkgroupname() != null) { sql.SET("WorkGroupName = #{workgroupname,jdbcType=VARCHAR}"); } if (record.getInvitecode() != null) { sql.SET("InviteCode = #{invitecode,jdbcType=VARCHAR}"); } if (record.getCreateuserid() != null) { sql.SET("CreateUserId = #{createuserid,jdbcType=INTEGER}"); } if (record.getCreattime() != null) { sql.SET("CreatTime = #{creattime,jdbcType=TIMESTAMP}"); } if (record.getWrokgroupdesc() != null) { sql.SET("WrokGroupDesc = #{wrokgroupdesc,jdbcType=VARCHAR}"); } if (record.getIspublic() != null) { sql.SET("IsPublic = #{ispublic,jdbcType=BIT}"); } sql.WHERE("Id = #{id,jdbcType=INTEGER}"); return sql.toString(); } }
C++
UTF-8
2,079
2.984375
3
[]
no_license
# include "Squad.hpp" Squad::Squad(void) : _squad(NULL), _count(0) { return ; } Squad::~Squad( void ) { t_list *current; t_list *tmp; current = this->_squad; if (current) { while (current) { tmp = current->next; delete current->marine; delete current; current = tmp; } } this->_squad = NULL; return ; } Squad::Squad( Squad const & squad ) { *this = squad; return ; } Squad &Squad::operator=(Squad const & squad) { t_list *current; t_list *tmp; if (this->_squad) { current = this->_squad; while (current) { tmp = current->next; delete current->marine; delete current; current = tmp; } } if (!squad._squad) this->_squad = NULL; else { current = squad._squad; while (current) { this->push(current->marine); current = current->next; } } this->setCount(squad.getCount()); return *this; } int Squad::getCount(void) const { return this->_count; } void Squad::setCount(int count) { this->_count = count; return ; } ISpaceMarine *Squad::getUnit(int N) const { t_list *current; int i = -1; int total = this->getCount(); if (N >= total) return NULL; current = this->_squad; while (current && ++i < N) current = current->next; return current->marine; } int Squad::push(ISpaceMarine * marine) { t_list *newUnit = new t_list; newUnit->marine = marine; newUnit->next = NULL; if (this->_squad) { t_list *current; current = this->_squad; while (current->next) current = current->next; current->next = newUnit; } else this->_squad = newUnit; this->setCount(this->getCount() + 1); return this->getCount(); }
JavaScript
UTF-8
687
2.5625
3
[]
no_license
/* Hahn Ch3 p.40 */ const express = require('express'); const path = require('path'); const http = require('http'); const app = express(); const publicPath = path.resolve(__dirname, "public"); app.use(express.static(publicPath)); app.get("/", (req, res)=>{ res.end("Welcome to the Dharma Bums."); } ); app.get("/about", (req, res)=> { res.end("'The DB's were a band.' -- Maximum RnR"); } ); app.get("/store", (req, res)=>{ res.end("Consider exiting through our gift shop."); } ); // Let's grab some data from the route. app.get("/players/:name1", (req, res)=>{ res.end(`It's a fact that ${req.params.name1} is not a great player.`); } ) http.createServer(app).listen(8000);
C++
GB18030
13,476
3.171875
3
[ "MIT" ]
permissive
#include "stdafx.h" #include "kstring.h" #include <string.h> #include <stdio.h> #include <stdarg.h> #include <algorithm> #ifdef _WIN32 #define vsnprintf _vsnprintf_s #endif kstring::kstring(void) { m_sString = NULL; m_iLength = 0; m_iBufLen = 0; } kstring::kstring(const char* lpszStr) { m_sString = NULL; m_iLength = 0; m_iBufLen = 0; if (lpszStr != NULL) { assign(lpszStr, strlen(lpszStr)); } } kstring::kstring(const char* lpszStr, size_t nlen) { m_sString = NULL; m_iLength = 0; m_iBufLen = 0; assign(lpszStr, nlen); } kstring::kstring(const kstring &sStr) { m_sString = NULL; m_iLength = 0; m_iBufLen = 0; assign(sStr.m_sString, sStr.m_iLength); } kstring::~kstring(void) { if (m_sString) free(m_sString); m_sString = NULL; m_iBufLen = 0; m_iLength = 0; } kstring& kstring::operator=(const kstring &sStr) { assign(sStr.m_sString, sStr.m_iLength); return *this; } kstring& kstring::operator=(const char* lpszStr) { assign(lpszStr, strlen(lpszStr)); return *this; } // - Operator + overloading for : kstring + kstring kstring kstring::operator +(const kstring &sStr) { kstring sTemp; sTemp.reserve(m_iLength + sStr.m_iLength);//ֹmalloc sTemp.append(m_sString, m_iLength); sTemp.append(sStr.m_sString, sStr.m_iLength); return sTemp; } // - Operator + overloading for : kstring + const char* kstring kstring::operator +(const char* lpszStr) { kstring sTemp; size_t alen = strlen(lpszStr); sTemp.reserve(m_iLength + alen + 1); sTemp.append(m_sString, m_iLength); sTemp.append(lpszStr, alen); return sTemp; } // - Operator +=overloading for kstring kstring& kstring::operator +=(const kstring &sStr) { append(sStr.m_sString, sStr.m_iLength); return *this; } // - Operator +=overloading for const char* kstring& kstring::operator +=(const char* lpszStr) { if (lpszStr != NULL) { size_t alen = strlen(lpszStr); append(lpszStr, alen); } return *this; } // - Operator < overloading : return true if specified kstring's length is less than // this class string's length , otherwise false bool kstring::operator <(const kstring &sStr) { if (empty() && sStr.empty()) { return false; } if (empty()) { return true; } else if (sStr.empty()) { return false; } else { size_t usize = min(m_iLength, sStr.m_iLength) + 1; if (memcmp(m_sString, sStr.m_sString, usize)<0) { return true; } } return false; } // - Operator <=overloading : return true if specified kstring's length is less than // or equal to this class string's length , otherwise false bool kstring::operator <=(const kstring &sStr) { if (empty() && sStr.empty()) { return true; } if (empty()) { return true; } else if (sStr.empty()) { return false; } else { size_t usize = min(m_iLength, sStr.m_iLength) + 1; if (memcmp(m_sString, sStr.m_sString, usize) <= 0) { return true; } } return false; } // - Operator > overloading : return true if specified kstring's length is greater than // this class string's length , otherwise false bool kstring::operator >(const kstring &sStr) { if (empty() && sStr.empty()) { return false; } if (empty()) { return false; } else if (sStr.empty()) { return true; } else { size_t usize = min(m_iLength, sStr.m_iLength) + 1; if (memcmp(m_sString, sStr.m_sString, usize)>0) { return true; } } return false; } // - Operator >=overloading : return true if specified kstring's length is greater than // or equal to this class string's length , otherwise false bool kstring::operator >=(const kstring &sStr) { if (empty() && sStr.empty()) { return true; } if (empty()) { return false; } else if (sStr.empty()) { return true; } else { size_t usize = min(m_iLength, sStr.m_iLength) + 1; if (memcmp(m_sString, sStr.m_sString, usize) >= 0) { return true; } } return false; } // - Operator==overloading : return true if specified kstring length is equal to // this class string's length , otherwise return false bool kstring::operator==(const kstring &sStr) { if (empty() && sStr.empty()) { return true; } if (!empty() && !sStr.empty()) { size_t usize = min(m_iLength, sStr.m_iLength) + 1; if (memcmp(m_sString, sStr.m_sString, usize) == 0) { return true; } } return false; } // - Operator==overloading : return true if specified const char* length is equal to // this class string's length , otherwise return false bool kstring::operator==(const char* lpszStr) { if (empty() && !lpszStr) { return true; } if (!empty() && lpszStr != NULL&&lpszStr[0] != 0) { size_t usize = min(m_iLength, strlen(lpszStr)) + 1; if (memcmp(m_sString, lpszStr, usize) == 0) { return true; } } return false; } // - Operator !=overloading : return true if specified kstring length is equal to // this class string's length , otherwise return false bool kstring::operator !=(const kstring &sStr) { if (*this == sStr) { return false; } return true; } bool kstring::operator !=(const char* lpszStr) { if (*this == lpszStr) { return false; } return true; } char& kstring::operator[](size_t index) { if (index >= m_iLength) { throw 0; } return m_sString[index]; } const char& kstring::operator[](size_t index) const { if (index >= m_iLength) { throw 0; } return m_sString[index]; } bool kstring::reserve(size_t nlen) { size_t tlen = m_iLength + nlen + 1; if (m_iBufLen<tlen) { char *pt = (char*)realloc(m_sString, tlen); if (pt == NULL) { return false; } m_iBufLen = tlen; m_sString = pt; } return true; } void kstring::assign(const char* lpszStr, size_t nlen) { if (lpszStr != NULL&&nlen>0) { if (m_iBufLen<nlen + 1) { m_iBufLen = nlen + 1; if (m_sString != NULL) { free(m_sString); } m_sString = (char*)malloc(m_iBufLen); } m_iLength = nlen; memcpy(m_sString, lpszStr, m_iLength); m_sString[m_iLength] = 0; } } void kstring::append(const char* lpszStr, size_t nlen) { if (lpszStr != NULL&&nlen>0) { reserve(nlen); memcpy(m_sString + m_iLength, lpszStr, nlen); m_iLength += nlen; m_sString[m_iLength] = 0; } } void kstring::clear() { m_iLength = 0; if (m_sString != NULL) m_sString[0] = 0; } // - Returns char in specified position char kstring::getat(size_t iPos) const { if (iPos >= 0 && iPos < m_iLength) return m_sString[iPos]; return 0; } // - Finds position of first specified char , if did not found return -1 int kstring::find(char ch) { if (empty()) { return -1; } char *c = (char*)memchr(m_sString, ch, m_iLength); if (c != NULL) { return (int)(c - m_sString); } return -1; } // - Finds first position of specified kstring , if did not found return -1 int kstring::find(const kstring &sStr) { if (empty()) { return -1; } if (sStr.empty()) { return 0; } char *c = memmem(m_sString, m_iLength, sStr.m_sString, sStr.m_iLength); if (c != NULL) { return (int)(c - m_sString); } return -1; } // - Finds first position of specified string , if did not found return -1 int kstring::find(const char* lpszStr) { if (empty()) { return -1; } if (!lpszStr || !lpszStr[0]) { return 0; } char *c = memmem(m_sString, m_iLength, lpszStr, strlen(lpszStr)); if (c != NULL) { return (int)(c - m_sString); } return -1; } // - replace an old char with a new char size_t kstring::replace(char cOld, char cNew) { size_t i, iTotal = 0; for (i = 0; i <= m_iLength; ++i) { if (m_sString[i] == cOld) { m_sString[i] = cNew; ++iTotal; } } return iTotal; } // - replace an old string with a new string size_t kstring::replace(const char* sOld, const char* sNew) { if (!sNew || !sOld) { return 0; } return replace(sOld, strlen(sOld), sNew, strlen(sNew)); } size_t kstring::replace(const kstring &sOld, const kstring &sNew) { return replace(sOld.m_sString, sNew.m_sString); } size_t kstring::replace(const char *polddata, size_t oldlen, const char *pnewdata, size_t newlen) { if (empty()) { return 0; } size_t nnum(0); kstring sTemp; char *pbuf = m_sString; size_t buflen = m_iLength; while (buflen>0) { char *pc = memmem(pbuf, buflen, polddata, oldlen); if (pc == NULL) { if (sTemp.empty()) { return 0; } sTemp.append(pbuf, buflen); break; } else { ++nnum; size_t cplen = pc - pbuf; sTemp.append(pbuf, cplen); sTemp.append(pnewdata, newlen); pbuf = pc + oldlen; buflen = buflen - cplen - oldlen; } } *this = sTemp; return nnum; } // - Returns iCount chars from iStart kstring kstring::mid(size_t iStart, size_t iCount) { kstring sTemp; if (iStart > m_iLength) return sTemp; if (iStart + iCount > m_iLength) return mid(iStart); sTemp.append(m_sString + iStart, iCount); return sTemp; } // - Returns chars from nStart till the end kstring kstring::mid(size_t iStart) { kstring sTemp; if (iStart > m_iLength) return sTemp; sTemp.append(m_sString + iStart, m_iLength - iStart); return sTemp; } // - Returns iCount left chars kstring kstring::left(size_t iCount) { if (iCount > m_iLength) iCount = m_iLength; return mid(0, (int)iCount); } // - Returns iCount right chars kstring kstring::right(size_t iCount) { if (iCount > m_iLength) iCount = m_iLength; return mid(m_iLength - iCount, iCount); } // - Removes a char in specified position bool kstring::erase(size_t iPos) { return erase(iPos, iPos) == 1; } // - Removes chars from iStart to iEnd size_t kstring::erase(size_t iStart, size_t iEnd) { if (iStart >= m_iLength) { return 0; } if (iEnd >= m_iLength) iEnd = m_iLength - 1; size_t iDelCount = iEnd - iStart + 1; memcpy(m_sString + iStart, m_sString + iEnd + 1, m_iLength - iEnd - 1); m_iLength -= iDelCount; m_sString[m_iLength] = 0; return iDelCount; } // - Trims left specified char kstring& kstring::trimleft(const char *targets) { if (targets == NULL) { targets = " \t\n\r"; } if (!empty()) { size_t npos; for (npos = 0; npos<m_iLength; ++npos) { if (strchr(targets, m_sString[npos]) == NULL) { --npos; break; } } if (npos>0) { erase(0, npos); } } return *this; } // - Trims right specified char kstring& kstring::trimright(const char *targets) { if (targets == NULL) { targets = " \t\n\r"; } if (!empty()) { for (size_t i = m_iLength - 1; i >= 0; --i) { if (strchr(targets, m_sString[i]) == NULL) { m_iLength = i + 1; break; } } m_sString[m_iLength] = 0; } return *this; } // - Trims left and right specified char kstring& kstring::trim(const char *targets) { //trimrightɼڴ濽 trimright(targets); trimleft(targets); return *this; } // - Inserts a string in specified position kstring& kstring::insert(const kstring &sStr, size_t iPos) { if (!sStr.empty()) { if (iPos >= m_iLength) { append(sStr); } else { reserve(sStr.m_iLength); kstring sTemp = mid(iPos); erase(iPos, -1); append(sStr); append(sTemp); } } return *this; } // - Converts to upper case kstring& kstring::makeupper() { if (!empty()) { for (size_t i = 0; i<m_iLength; ++i) { if (m_sString[i] >= 'a'&&m_sString[i] <= 'z') { m_sString[i] -= 32; } } } return *this; } // - Converts to lower case kstring& kstring::makelower() { if (!empty()) { for (size_t i = 0; i<m_iLength; ++i) { if (m_sString[i] >= 'A'&&m_sString[i] <= 'Z') { m_sString[i] += 32; } } } return *this; } // - Clears the string bool kstring::empty() const { if (!m_sString || !m_iLength) { return true; } return false; } const char* kstring::c_str() const { static const char* szempstr = ""; if (empty()) { return szempstr; } m_sString[m_iLength] = 0; return m_sString; } void kstring::Format(const char* pszCharSet, ...) { char* pszTemp = NULL; int nRetVal = -1; va_list vl; va_start(vl, pszCharSet); for (int nBufferSize = 1024; nRetVal < 0; nBufferSize *= 2) { if (pszTemp != NULL) { free(pszTemp); } pszTemp = (char*)malloc(nBufferSize + 1); nRetVal = vsnprintf(pszTemp, nBufferSize, _TRUNCATE, pszCharSet, vl); } va_end(vl); assign(pszTemp, nRetVal); free(pszTemp); } // memmem() // // Purpose: Find a byte sequence within a memory buffer // // Parameters: buf - pointer to buffer // buf_len - size of buffer in bytes // byte_sequence - byte sequence to look for // byte_sequence_len - size of byte sequence in bytes // // Returns: void * - if successful, returns a pointer to the first // occurrence of byte_sequence in buf; otherwise, // returns NULL // // Notes; Characters in byte_sequence and characters in buf will be // compared "as is", with no case conversion. char *kstring::memmem(const char *buf, size_t buf_len, const char *byte_sequence, size_t byte_sequence_len) { char *bf = (char *)buf; char *bs = (char *)byte_sequence; char *p = bf; while (byte_sequence_len <= (buf_len - (p - bf))) { unsigned int b = *bs & 0xFF; if ((p = (char *)memchr(p, b, buf_len - (p - bf))) != NULL) { if ((memcmp(p, byte_sequence, byte_sequence_len)) == 0) return p; else ++p; } else { break; } } return NULL; } std::ostream& operator<<(std::ostream &temp, const kstring& sStr) { temp.rdbuf()->sputn(sStr.c_str(), (std::streamsize)sStr.size()); return temp; }
C#
UTF-8
3,778
2.53125
3
[ "MIT" ]
permissive
using System.Collections.Generic; using System.Linq; using U8Xml; namespace KyoshinEewViewer.JmaXmlParser.Data.Earthquake; public struct HypocenterArea { private XmlNode Node { get; set; } public HypocenterArea(XmlNode node) { Node = node; } private string? _name = null; /// <summary> /// 震央地名 /// </summary> public string Name => _name ??= (Node.TryFindStringNode(Literals.Name(), out var n) ? n : throw new JmaXmlParseException("Area ノードが存在しません")); private string? _code = null; /// <summary> /// 震央地名コード /// </summary> public string Code => _code ??= (Node.TryFindStringNode(Literals.Code(), out var n) ? n : throw new JmaXmlParseException("Code ノードが存在しません")); private Coordinate? _coordinate = null; /// <summary> /// 震源要素(複数ある場合は1件目のみ) /// </summary> public Coordinate Coordinate => _coordinate ??= (Node.TryFindChild(Literals.JmxEbCoordinate(), out var n) ? new(n) : throw new JmaXmlParseException("Coordinate ノードが存在しません")); /// <summary> /// 震源要素<br/> /// 顕著な地震の震源要素更新のお知らせ の場合は1件以上となる /// </summary> public IEnumerable<Coordinate> Coordinates => Node.Children.Where(c => c.Name == Literals.JmxEbCoordinate()).Select(c => new Coordinate(c)); private string? _reduceName = null; /// <summary> /// 短縮用震央地名<br/> /// EEW以外は null /// </summary> public string? ReduceName => _reduceName ??= (Node.TryFindStringNode(Literals.ReduceName(), out var n) ? n : null); private string? _reduceCode = null; /// <summary> /// 短縮用震央地名コード<br/> /// EEW以外は null /// </summary> public string? ReduceCode => _reduceCode ??= (Node.TryFindStringNode(Literals.ReduceCode(), out var n) ? n : null); private string? _landOrSea = null; /// <summary> /// 内陸判定<br/> /// 例: 内陸、海域<br/> /// 以下の場合は null /// <list type="bullet"> /// <item>EEW以外</item> /// <item>「緊急地震速報(地震動予報)」、および「緊急地震速報(予報)」において、非常に強い揺れを検知・最大予測震度のみの場合</item> /// <item>「仮定震源要素」の場合</item> /// </list> /// は null /// </summary> public string? LandOrSea => _landOrSea ??= (Node.TryFindStringNode(Literals.LandOrSea(), out var n) ? n : null); private string? _detailedName = null; /// <summary> /// 詳細震央地名<br/> /// 国外で発生した地震について、震源地の詳細な位置 /// </summary> public string? DetailedName => _detailedName ??= (Node.TryFindStringNode(Literals.DetailedName(), out var n) ? n : null); private string? _detailedCode = null; /// <summary> /// 詳細震央地名コード<br/> /// コード種別 は 詳細震央地名 /// </summary> public string? DetailedCode => _detailedCode ??= (Node.TryFindStringNode(Literals.DetailedCode(), out var n) ? n : null); private string? _nameFromMark = null; /// <summary> /// 震央補助表現<br/> /// 日本近海で発生し、津波警報・注意報を発表した地震について、震源地の詳細な位置を示すための目印となる地名 /// </summary> public string? NameFromMark => _nameFromMark ??= (Node.TryFindStringNode(Literals.NameFromMark(), out var n) ? n : null); private string? _source = null; /// <summary> /// 震源決定機関<br/> /// 国外で発生した地震について、気象庁以外の機関で決定された震源要素を採用して情報発表した場合<br/> /// 例: PTWC、WCATWC、USGS /// </summary> public string? Source => _source ??= (Node.TryFindStringNode(Literals.Source(), out var n) ? n : null); }
Python
UTF-8
4,631
2.90625
3
[ "MIT", "X11" ]
permissive
import logging import sys import re from privex.helpers import empty, empty_if, T, K from typing import List, Optional, Union log = logging.getLogger(__name__) __all__ = [ 'read_stdin', 're_markers', '_re_markers', 'replace_markers', 'automark_str', 'automark', '_dedup', 'dedup', 'dedup_dict', 'clean_dict', 'literal' ] def read_stdin(auto_strip=True) -> List[str]: """Read STDIN into a list of :class:`.str`'s and then returns that list.""" lines = [] for ln in sys.stdin: lines.append(ln.strip() if auto_strip else ln) return lines _re_markers = r'{{([a-zA-Z0-9._-]+)}}' re_markers = re.compile(r'{{([a-zA-Z0-9._-]+)}}') def replace_markers(data: str, groupsrc: dict, *markers) -> str: """ Replace the markers ``markers`` in the form of ``{{marker}}`` which are present in the string ``data``, by looking up the marker names against ``groupsrc``, and recursively replacing any markers found in the replacement from ``groupsrc``. :param str data: The data to replace markers within :param dict groupsrc: A dictionary containing marker names mapped to their value, to be used for replacing markers in ``data`` :param str markers: One or more markers to search for within ``data`` and replace. :return str new_data: The ``data`` after replacing all passed markers. """ data = str(data) for m in markers: mk = '{{' + str(m) + '}}' if mk not in data: continue repd = '' if m in groupsrc: repd = groupsrc[m] log.debug(f"Found marker replacement: {m!r} = {repd!r}") repmks = re.compile(_re_markers).findall(repd) if len(repmks) > 0: log.debug(f"Marker replacement contains {len(repmks)} markers too! Replacing sub-markers...") repd = groupsrc[m] = replace_markers(repd, groupsrc, *repmks) data = data.replace(mk, repd) log.debug(f"Replaced data marker: {m!r} = {repd!r}") return data def automark_str(data: str, groupsrc: dict): """Replace markers in the form of ``{{marker}}`` in ``data``, by looking up the marker name against ``groupsrc``""" log.debug(f" >>> Checking value for markers: {data!r}") gmarks = re.compile(_re_markers).findall(data) if len(gmarks) > 0: data = replace_markers(data, groupsrc, *gmarks) return data def automark(data: dict, groupsrc: dict, inplace=False): """Replace markers in the form of ``{{marker}}`` in the values of ``data``, by looking up the marker name against ``groupsrc``""" data = data if inplace else {k: v for k, v in data.items()} for k, v in data.items(): data[k] = automark_str(v, groupsrc) return data def _dedup(data: Union[list, tuple]) -> list: """Remove duplicates from a list/tuple, then return a new clean list""" ndata = [] for d in data: if d in ndata: continue ndata.append(d) return ndata def dedup(data: Union[list, tuple, str, T], sep=None) -> T: """Remove duplicate entries from a list/tuple, or a string (split into a list using ``sep`` (default: any whitespace))""" if isinstance(data, str): sdt = data.split(sep) ndata = _dedup(sdt) sep = ' ' if sep is None else sep return sep.join(ndata) ndata = _dedup(data) return list(ndata) if isinstance(data, list) else tuple(ndata) def dedup_dict(data: dict, sep=None, inplace=False) -> dict: """Same as :func:`.dedup` but de-duplicates the values in :class:`.dict`'s instead of list/tuple/str's """ ndict = data if inplace else {} for k, v in data.items(): ndict[k] = dedup(v, sep=sep) return ndict def clean_dict(data: dict, groupsec: dict = None, inplace=False, do_automark=True, do_dedup=True, **kwargs) -> dict: """ Extracts the contents of a dict-like object using ``dict(list(data.items()))``, replaces any markers present inside of the dict's values using :func:`.automark` (if do_automark is True), and then removes any duplicate entries within it's values, using :func:`.dedup` (if do_dedup is True). """ ndata = dict(list(data.items())) groupsec = ndata if empty(groupsec) else groupsec if do_automark: ndata = automark(ndata, groupsec, inplace) if do_dedup: ndata = dedup_dict(ndata, inplace=inplace) return ndata def literal(data: str) -> str: """Replaces ``\\n``, ``\\r`` and ``\\t`` in a string, with the real literal newline, carraige return, and tab characters.""" return str(data).replace("\\n", "\n").replace("\\r", "\r").replace("\\t", "\t")
Markdown
UTF-8
1,127
2.953125
3
[ "Apache-2.0" ]
permissive
# Appium Images Plugin This is an official Appium plugin designed to facilitate image comparison, visual testing, and image-based functional testing. ## Features 1. **Image Comparison** ([docs](./docs/image-comparison.md)) - A new Appium command and route that allows sending in two different images and comparing them in various ways. 2. **Finding Elements by Image** ([docs](./docs/find-by-image.md)) - Using a template image, find a matching screen region of an app and interact with it via standard Appium element semantics. ## Prerequisites * Appium Server 2.0+ ## Installation - Server Install the plugin using Appium's plugin CLI: ``` appium plugin install images ``` ## Installation - Client No special action is needed to make the features available in the various Appium clients, as this plugin used to be a core Appium feature and its commands are already supported in the official clients. ## Activation The plugin will not be active unless turned on when invoking the Appium server: ``` appium --use-plugins=images ``` ## Usage Check the docs links above for usage for each of the features provided.
Rust
UTF-8
2,973
2.71875
3
[]
no_license
use async_trait::async_trait; use crate::domain::hero::{Hero, HeroDto, repository::HeroRepository, HeroOptionResult}; use deadpool_postgres::{Pool, Client}; use crate::domain::Result; use tokio_postgres::error::SqlState; use serde::export::Formatter; #[derive(Debug)] pub struct NoRowError; impl std::fmt::Display for NoRowError { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { write!(f, "No rows returned") } } impl std::error::Error for NoRowError {} impl NoRowError { pub fn boxed() -> Box<dyn std::error::Error> { Box::new(NoRowError) } } pub struct PostgresHeroRepository { pg_pool: Pool } impl PostgresHeroRepository { pub fn new(db_client: Pool) -> impl HeroRepository { PostgresHeroRepository { pg_pool: db_client } } fn get_pool(&self) -> &Pool { &self.pg_pool } async fn get_client(&self) -> crate::domain::Result<Client> { let pool = self.get_pool(); let result: Client = pool.get().await?; Ok(result) } } #[async_trait] impl HeroRepository for PostgresHeroRepository { async fn get_hero<'a>(&self, id: i32) -> HeroOptionResult<'a> { let client = self.get_client().await?; let q = " select h.hero_id, h.name, hc.name as class from hero h join hero_class hc on h.hero_class_id = hc.hero_class_id where h.hero_id = $1"; let params = &[&id]; let result = client .query_one(q, params) .await .map_or_else(|e| { if format!("{}", e) == "query returned an unexpected number of rows" { Ok(None) } else { Err(Box::new(e)) } }, |v| Ok(Some(v)))?; match result { Some(row) => { let class: String = row.get(2); let dto = HeroDto::new_data(row.get(0), row.get(1), class.into()); Ok(Some(Hero::new(dto))) } None => Ok(None) } } async fn save_hero<'a>(&self, hero: &'a Hero<'a>) -> Result<i32> { let client = self.get_client().await?; let class: String = hero.class().into(); let class_id: i32 = client.query_one("select hero_class_id from hero_class where name = $1", &[&class]) .await? .get(0); let q = " insert into hero(name, hero_class_id) values ($1, $2) on conflict (name) do nothing returning hero_id"; // let class: String = hero.class().into(); let result = client.query_one(q, &[ &hero.name(), &class_id ]).await?; let id: i32 = result.try_get(0)?; Ok(id) } }
Java
UTF-8
2,519
2.15625
2
[]
no_license
package com.wulianwang.lsp.activity; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.ListView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.wulianwang.lsp.R; import com.wulianwang.lsp.bean.MyList; import com.wulianwang.lsp.adapter.MyListAdapter; import java.util.ArrayList; import java.util.List; /** * 成员:刘长恩 曹彬 * 3.5 企业服务 */ public class CompanyServiceActivity extends AppCompatActivity { private ListView mLv1; private List<MyList> mylist; private MyListAdapter gridadapter; private ImageView IB; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_company_service); IB =(ImageView)this.findViewById(R.id.imageB1); mLv1 =(ListView)findViewById(R.id.list1); try { mylist =new ArrayList<MyList>(); gridadapter=new MyListAdapter(this); mylist.add(0,new MyList("修路")); mylist.add(1,new MyList("架桥")); mylist.add(2,new MyList("家变电站")); mylist.add(3,new MyList("装变压器")); mylist.add(4,new MyList("修水电站")); mylist.add(5,new MyList("装发动机")); mylist.add(6,new MyList("维修发动机")); gridadapter.setList(mylist); mLv1.setAdapter(gridadapter); } catch (Exception e) { Toast.makeText(this,e.toString(),Toast.LENGTH_LONG).show(); } finally { } mLv1.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent intent = new Intent(CompanyServiceActivity.this, CompanyServiceDetailActivity.class); startActivity(intent); } }); IB.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View vAll) { Intent intent = new Intent(CompanyServiceActivity.this,AllServiceActivity.class); startActivity(intent); } }); } }
C#
UTF-8
3,189
2.625
3
[ "MIT" ]
permissive
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Kernel { public int ID; public Vector3Int size; public string name; public Kernel(ComputeShader shader, string name) { this.name = name; ID = shader.FindKernel(name); uint x, y, z; shader.GetKernelThreadGroupSizes(ID, out x, out y, out z); size.x = (int)x; size.y = (int)y; size.z = (int)z; } public override string ToString() { return name + " groupSize=" + size.ToString(); } } public static class ComputeProgramUtils { public static void InitializeBuffer(ref ComputeBuffer buffer, int newCount, int stride) { if (buffer == null) buffer = new ComputeBuffer(newCount, stride); else if (buffer.count < newCount) { buffer.Release(); buffer = new ComputeBuffer(newCount, stride); } } public static void DispatchGrid(this ComputeShader shader, Kernel kernel, int gridSizeX, int gridSizeY, int gridSizeZ) { /*if (gridSizeX / kernel.size.x < 1 || gridSizeY / kernel.size.y < 1 || gridSizeZ / kernel.size.z < 1) throw new ArgumentOutOfRangeException(String.Format("Grid size less than work group size: gridSize=({0}, {1}, {2}) {3}", gridSizeX, gridSizeY, gridSizeZ, kernel)); if (gridSizeX % kernel.size.x > 0 || gridSizeY % kernel.size.y > 0 || gridSizeZ % kernel.size.z > 0) throw new ArgumentException(String.Format("Grid size don't divides by work group size: gridSize=({0}, {1}, {2}) {3}", gridSizeX, gridSizeY, gridSizeZ, kernel)); shader.Dispatch(kernel.ID, gridSizeX / kernel.size.x, gridSizeY / kernel.size.y, gridSizeZ / kernel.size.z); */ int X = (gridSizeX - 1) / kernel.size.x + 1; int Y = (gridSizeY - 1) / kernel.size.y + 1; int Z = (gridSizeZ - 1) / kernel.size.z + 1; //if (X != gridSizeX * kernel.size.x || // Y != gridSizeY * kernel.size.y || // Z != gridSizeZ * kernel.size.z) // Debug.LogWarningFormat("Grid size donesn't alligned by work group size: gridSize=({0}, {1}, {2}) {3}", gridSizeX, gridSizeY, gridSizeZ, kernel); shader.Dispatch(kernel.ID, X, Y, Z); } public static void DispatchGrid(this ComputeShader shader, Kernel kernel, int gridSizeX, int gridSizeY) { int X = (gridSizeX - 1) / kernel.size.x + 1; int Y = (gridSizeY - 1) / kernel.size.y + 1; //if (X != gridSizeX * kernel.size.x || // Y != gridSizeY * kernel.size.y) // Debug.LogWarningFormat("Grid size donesn't alligned by work group size: gridSize=({0}, {1}, 1) {2}", gridSizeX, gridSizeY, kernel); shader.Dispatch(kernel.ID, X, Y, 1); } public static void DispatchGrid(this ComputeShader shader, Kernel kernel, int gridSizeX) { int X = (gridSizeX - 1) / kernel.size.x + 1; //if (X != gridSizeX * kernel.size.x) // Debug.LogWarningFormat("Grid size donesn't alligned by work group size: gridSize=({0}, 1, 1) {1}", gridSizeX, kernel); shader.Dispatch(kernel.ID, X, 1, 1); } }
JavaScript
UTF-8
1,502
2.546875
3
[]
no_license
import Immutable from 'seamless-immutable'; import endpoints from 'core/endpoints'; const types = { ADD_HISTORY_ENTRY: 'ADD_HISTORY_ENTRY', }; function getOrdersHistoryFromLocalStorage() { const orders = window.localStorage.getItem('orderHistory'); try { const parsed = JSON.parse(orders); if (parsed instanceof Array) { return parsed; } } catch (e) { console.log(e) } return [] } const initialState = Immutable({ orders: getOrdersHistoryFromLocalStorage(), }); export default function (state = initialState, action) { switch (action.type) { case types.ADD_HISTORY_ENTRY: return Immutable.update(state, 'orders', order => [ ...order.filter(v => v.id !== action.payload.id), action.payload, ] ); default: return state; } }; function addHistoryEntry(json) { return { type: types.ADD_HISTORY_ENTRY, payload: json, } } function fetchOrderByHashid(hashid) { return dispatch => { fetch(`${endpoints.orders}${hashid}`).then( response => response.json() ).then( json => { if (json.id) { dispatch(addHistoryEntry(json)); } else { console.log(json) } } ); } } export const actions = { fetchOrderByHashid, };
JavaScript
UTF-8
3,860
2.640625
3
[]
no_license
'use strict' const boton_registrar = document.querySelector('#btn-registrar-autor'); const input_nombre = document.querySelector('#txt-nombre-autor'); const input_nombre_artistico = document.querySelector('#txt-nombre-artistico-autor'); const input_fecha_nacimiento = document.querySelector('#txt-nacimiento-autor'); const input_fecha_muerte = document.querySelector('#txt-muerte-autor'); const input_nacionalidad = document.querySelector('#txt-nacionalidad-autor'); const input_biografia = document.querySelector('#txt-biografia-autor'); const input_premios = document.querySelector('#txt-premios-autor'); const foto_perfil = document.querySelector('#autor_foto_preview'); let validar = (pnombre, pnombre_artistico, pfecha_nacimiento, pfecha_muerte, pnacionalidad, pbiografia, ppremios, pfotoPerfil) => { let error = false; if (pnombre == '') { error = true; input_nombre.classList.add('input_error'); } else { input_nombre.classList.remove('input_error'); } if (pnombre_artistico == '') { error = true; input_nombre_artistico.classList.add('input_error'); } else { input_nombre_artistico.classList.remove('input_error'); } if (pfecha_nacimiento == '') { error = true; input_fecha_nacimiento.classList.add('input_error'); } else { input_fecha_nacimiento.classList.remove('input_error'); } if (pfecha_muerte == '') { error = true; input_fecha_muerte.classList.add('input_error'); } else { input_fecha_muerte.classList.remove('input_error'); } if (pnacionalidad =='') { error = true; input_nacionalidad.classList.add('input_error'); } else { input_nacionalidad.classList.remove('input_error'); } if (pbiografia == '') { error = true; input_biografia.classList.add('input_error'); } else { input_biografia.classList.remove('input_error'); } if (ppremios == '') { error = true; input_premios.classList.add('input_error'); } else { input_premios.classList.remove('input_error'); } if (pfotoPerfil == '#autor_foto_preview') { error = true; foto_perfil.classList.add('input_error'); } else { foto_perfil.classList.remove('input_error'); } return error; }; let saludar = () => { let nombre = input_nombre.value; let nombre_artistico = input_nombre_artistico.value; let fecha_nacimiento = input_fecha_nacimiento.value; let fecha_muerte = input_fecha_muerte.value; let nacionalidad = input_nacionalidad.value; let biografia = input_biografia.value; let premios = input_premios.value; let foto_autor = foto_perfil.src; let error = validar(nombre, nombre_artistico, fecha_nacimiento, fecha_muerte, nacionalidad, biografia, premios, foto_autor); if (error == false) { registrarAutor(nombre, nombre_artistico, fecha_nacimiento, fecha_muerte, nacionalidad, biografia, premios, foto_autor); Swal.fire({ //formato json title: 'Se ha registrado exitosamente', type: 'success', text: 'El autor estará disponible a la hora de registrar un libro' }) } else { Swal.fire({ //formato json title: 'No se ha podido registrar', type: 'warning', text: 'Revise los campos resaltados e inténtelo de nuevo' }) } }; boton_registrar.addEventListener('click', saludar); function readURL(input) { if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function (e) { $('#imagen') .attr('src', e.target.result) .width(150) .height(200); }; reader.readAsDataURL(input.files[0]); } }
C#
UTF-8
5,936
2.8125
3
[]
no_license
//EXCEPCIONES try { // Código } catch (OverflowException e) { Console.WriteLine(e.Message); } catch (DivideByZeroException e) { Console.WriteLine(e.Message); } finally { Console.WriteLine("Pulse una tecla para continuar..."); } //crear excepcion using System; public class EmployeeListNotFoundException : Exception { public EmployeeListNotFoundException() { } public EmployeeListNotFoundException(string message) : base(message) { } public EmployeeListNotFoundException(string message, Exception inner) : base(message, inner) { } } //GENERICS public class Mensajero<T, U> { private T miAtr1; private U miAtr2; private Dictionary<T, U> miDiccionario; } Mensaje<string, int> tipoTexto = new Mensaje<string, int>(); Mensaje<char, MiClase> tipoMio = new Mensaje<char, MiClase>(); public class Mensajero<T> where T : Mensaje { } class EjemploComplejo<K, V, U> // Implemente interfaz where U : System.IComparable<U> // V tenga constructor por defecto where V : new() { } class Prueba { public static void OpTest<T>(T s, T t) where T : class { System.Console.WriteLine(s == t); } public void OpTest2<T>(T s, T t) where T : class { System.Console.WriteLine(s == t); } } //INTERFACES public interface MIInterfaz { public string MiMetodo(); //solo se declara la firma, en donde se use la interfaz se implementa } //SERIALIZACION XML //ESCRITURA using System.Xml; using System.Xml.Serialization; //... Dato p = new Dato(); //Objeto a serializar. XmlTextWriter writer; //Objeto que escribirá en XML. XmlSerializer ser; //Objeto que serializará. //Se indica ubicación del archivo XML y su codificación. writer = new XmlTextWriter(ArchivoXml, Codificación); //Se indica el tipo de objeto ha serializar. ser = new XmlSerializer(typeof(Dato)); //Serializa el objeto p en el archivo contenido en writer. ser.Serialize(writer, p); //Se cierra la conexión al archivo writer.Close(); //LECTURA using System.Xml; using System.Xml.Serialization; //... //Objeto que alojará los datos contenidos en el archivo XML. Dato aux = new Dato(); XmlTextReader reader; //Objeto que leerá XML. XmlSerializer ser; //Objeto que Deserializará. //Se indica ubicación del archivo XML. reader = new XmlTextReader(ArchivoXml); //Se indica el tipo de objeto ha serializar. ser = new XmlSerializer(typeof(Dato)); //Deserializa el archivo contenido en reader, lo guarda en aux. aux = (Dato) ser.Deserialize(reader); //Se cierra el objeto reader. reader.Close(); //SERIALIZACION BINARIA Para poder hacer una serialización binaria se debe agregar el marcador[Serializable] [Serializable] class MiClase { } //ESCRITURA using System.IO; using System.Runtime.Serialization.Formatters.Binary; //... Dato aux = new Dato(); // Objeto a serializar. FileStream fs; //Objeto que escribirá en binario. BinaryFormatter ser; //Objeto que serializará. //Se indica ubicación del archivo binario y el modo. fs = new FileStream(ArchivoBinario, FileMode.Create); //Se crea el objeto serializador. ser = new BinaryFormatter(); //Serializa el objeto p en el archivo contenido en fs. ser.Serialize(fs, p); //Se cierra el objeto fs fs.Close(); //LECTURA using System.IO; using System.Runtime.Serialization.Formatters.Binary; //... //Objeto que alojará los datos contenidos en el archivo binario. Dato aux = new Dato(); FileStream fs; //Objeto que leerá en binario. BinaryFormatter ser; //Objeto que Deserializará. //Se indica ubicación del archivo binario y el modo. fs = new FileStream(pathBinario, FileMode.Open); //Se crea el objeto deserializador. ser = new BinaryFormatter(); //Deserializa el archivo contenido en fs, lo guarda en aux. aux = (Dato) ser.Deserialize(fs); //Se cierra el objeto fs. fs.Close(); //SQL String connectionStr = "Data Source=[Instancia Del Servidor]; Initial Catalog =[Nombre de la Base de Datos]; Integrated Security = True"; using System.Data.SqlClient; SqlConnection conexion; conexion = new SqlConnection(connectionStr); //ejemplo de command SqlCommand comando; comando = new SqlCommand(); comando.CommandType = System.Data.CommandType.Text; comando.Connection = conexion; //ejemplo de consulta SELECT comando.CommandText = "SELECT nombre FROM Personas"; conexion.Open(); SqlDataReader oDr = comando.ExecuteReader(); while (oDr.Read()) { string aux = oDr["nombre"].ToString(); } //Ejemplo Insert, Update y Delete String consulta; consulta = "UPDATE Personas SET nombre = 'Fer' WHERE id = 1"; consulta = "INSERT INTO Personas (nombre) VALUES('Pedro')"; consulta = "DELETE FROM Personas WHERE id = 1"; comando.CommandText = consulta; conexion.Open(); comando.ExecuteNonQuery(); //THREAD // Agrego la biblioteca using System.Threading; // Creo el hilo Thread t = new Thread(UnMetodo); // Inicio el Hilo t.Start(); //EJEMPLO CON PARAMETROS // Creo el hilo Thread t = new Thread(new ParameterizedThreadStart(Metodo)); // Inicio el Hilo, indicando el parámetro t.Start(1000); private void Metodo(object o) { Console.WriteLine((int)o); } //EJEMPLO EN FORMS private void Metodo(object o) { if (this.label.InvokeRequired) { this.label.BeginInvoke((MethodInvoker)delegate () { this.label.Text = (int)o; } ); } else { this.label.Text = (int)o; } } //DELEGADOS public delegate void MiDelegado(object sender, EventArgs e); public event MiDelegado ElEvento; objEmisor.evento += MetodoManejador; //METODOS DE EXTENCION namespace MetodoDeExtension { public static class MiExtension { public static int Metodo(this [tipo][nombre]) { return 0; } } }
Java
UTF-8
2,849
1.726563
2
[]
no_license
package org.iplantc.de.client.services; import org.iplantc.de.client.models.analysis.Analysis; import org.iplantc.de.client.models.analysis.AnalysisParameter; import org.iplantc.de.client.models.analysis.AnalysisStepsInfo; import org.iplantc.de.client.models.analysis.sharing.AnalysisSharingRequest; import org.iplantc.de.client.models.analysis.sharing.AnalysisSharingRequestList; import org.iplantc.de.client.models.analysis.sharing.AnalysisUnsharingRequest; import org.iplantc.de.client.models.analysis.sharing.AnalysisUnsharingRequestList; import org.iplantc.de.client.models.apps.App; import org.iplantc.de.client.models.apps.sharing.AppSharingRequestList; import org.iplantc.de.client.models.apps.sharing.AppUnSharingRequestList; import com.google.gwt.user.client.rpc.AsyncCallback; import com.sencha.gxt.data.shared.loader.FilterPagingLoadConfig; import com.sencha.gxt.data.shared.loader.PagingLoadResultBean; import java.util.List; public interface AnalysisServiceFacade { /** * Get all the analyses for the current user's workspace * * @param loadConfig optional remote paging and sorting configs. * @param callback executed when RPC call completes. */ void getAnalyses(FilterPagingLoadConfig loadConfig, AsyncCallback<PagingLoadResultBean<Analysis>> callback); /** * Delete an analysis execution * * @param analysesToDelete the analyses to be deleted. * @param callback executed when RPC call completes. */ void deleteAnalyses(List<Analysis> analysesToDelete, AsyncCallback<String> callback); /** * Renames an analysis. * * @param analysis the analysis which will be renamed * @param newName the new analysis name * @param callback executed when RPC call completes. */ void renameAnalysis(Analysis analysis, String newName, AsyncCallback<Void> callback); /** * Stop a currently running analysis * * @param analysisId the analysis to be stopped. * @param callback executed when RPC call completes. */ void stopAnalysis(Analysis analysis, AsyncCallback<String> callback); void getAnalysisParams(Analysis analysis, AsyncCallback<List<AnalysisParameter>> callback); void updateAnalysisComments(Analysis analysis, String newComment, AsyncCallback<Void> callback); /** * * @sriram: the URL path for the new service will be `/analyses/:analysis-id/steps` * @param analysis * @param callback */ void getAnalysisSteps(Analysis analysis, AsyncCallback<AnalysisStepsInfo> callback); void shareAnalyses(AnalysisSharingRequestList request, AsyncCallback<String> callback); void unshareAnalyses(AnalysisUnsharingRequestList request, AsyncCallback<String> callback); void getPermissions(List<Analysis> analyses, AsyncCallback<String> callback); }
PHP
UTF-8
310
2.59375
3
[]
no_license
<?php class COrder { public $id; public $cdate; public $total; public $status; public $custid; function __construct($id, $cdate, $total, $status, $custid) { $this->id = $id; $this->cdate = $cdate; $this->total = $total; $this->status = $status; $this->custid = $custid; } } ?>
Python
UTF-8
1,541
3.703125
4
[]
no_license
""" multiScrolls.py Demonstrate three scroll bars add to 100 change top scroll, bottom two change proportionately """ from Tkinter import * class App(Tk): def __init__(self): Tk.__init__(self) self.scrA = Scale(self, from_ = 0, to = 100, orient = HORIZONTAL) self.scrA.grid() self.scrA.set(0) self.scrA["command"] = self.adjustScrollers self.scrB = Scale(self, from_ = 0, to = 100, orient = HORIZONTAL) self.scrB.grid() self.scrB.set(50) self.scrC = Scale(self, from_ = 0, to = 100, orient = HORIZONTAL) self.scrC.grid() self.scrC.set(50) self.mainloop() def adjustScrollers(self, aVal): aVal = int(aVal) amountToSpend = 100 - aVal #read in as ints currentB = int(self.scrB.get()) currentC = int(self.scrC.get()) #now convert those ints to floats #can't read directly as floats! currentB = float(currentB) currentC = float(currentC) print "Before: currentB: %.2f, currentC: %.2f" % (currentB, currentC) bcTotal = currentB+currentC bPerc = currentB / bcTotal cPerc = currentC / bcTotal newB = 100 - (currentB + (bPerc * amountToSpend)) newC = 100 - (currentC + (cPerc * amountToSpend)) total = aVal + newB + newC print "bPerc: %.2f, cPerc: %.2f, Total: %d" % (bPerc, cPerc, total) print "amountToSpend: %d, newB: %.2f, newC: %.2f" % (amountToSpend, newB, newC) print self.scrB.set(newB) self.scrC.set(newC) def main(): app = App() if __name__ == "__main__": main()
Java
UTF-8
6,447
1.828125
2
[]
no_license
package com.quickblox.sample.chat.ui.adapter; import android.content.Context; import android.net.Uri; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.quickblox.chat.model.QBChatDialog; import com.quickblox.chat.model.QBDialogType; import com.quickblox.content.QBContent; import com.quickblox.content.model.QBFile; import com.quickblox.core.QBEntityCallback; import com.quickblox.core.QBProgressCallback; import com.quickblox.core.exception.QBResponseException; import com.quickblox.core.request.QBPagedRequestBuilder; import com.quickblox.sample.chat.R; import com.quickblox.sample.chat.interfaces.ImageIdDownloadView; import com.quickblox.sample.chat.network.AppImageIdPresenter; import com.quickblox.sample.chat.utils.Constant; import com.quickblox.sample.chat.utils.FolderCreator; import com.quickblox.sample.chat.utils.qb.QbDialogUtils; import com.quickblox.sample.chat.utils.qb.QbUsersHolder; import com.quickblox.sample.core.ui.adapter.BaseSelectableListAdapter; import com.quickblox.sample.core.utils.ResourceUtils; import com.quickblox.sample.core.utils.UiUtils; import com.quickblox.users.QBUsers; import com.quickblox.users.model.QBUser; import org.jivesoftware.smack.SmackException; import org.jivesoftware.smack.XMPPException; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collection; import java.util.List; public class DialogsAdapter extends BaseSelectableListAdapter<QBChatDialog> { QBChatDialog dialog; List<QBUser> user; long currentTime; long userLastRequestAtTime; public DialogsAdapter(Context context, List<QBChatDialog> dialogs) { super(context, dialogs); } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; try { if (convertView == null) { convertView = inflater.inflate(R.layout.list_item_dialog, parent, false); holder = new ViewHolder(); holder.rootLayout = (ViewGroup) convertView.findViewById(R.id.root); holder.nameTextView = (TextView) convertView.findViewById(R.id.text_dialog_name); holder.lastMessageTextView = (TextView) convertView.findViewById(R.id.text_dialog_last_message); holder.dialogImageView = (ImageView) convertView.findViewById(R.id.image_dialog_icon); holder.userStatus = (ImageView) convertView.findViewById(R.id.image_dialog_userStatus); holder.unreadCounterTextView = (TextView) convertView.findViewById(R.id.text_dialog_unread_count); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } dialog = getItem(position); Uri imageUri = Uri.fromFile(FolderCreator.getImageFileFromSdCard(String.valueOf(dialog.getRecipientId()))); Glide.with(context) .load(imageUri) .placeholder(R.drawable.ic_chat_face) .into(holder.dialogImageView); if (dialog.getType().equals(QBDialogType.GROUP)) { holder.dialogImageView.setBackgroundDrawable(UiUtils.getColoredCircleDrawable(ResourceUtils.getColor(R.color.colorPrimary))); // holder.dialogImageView.setImageResource(R.drawable.ic_chat_groups); } else { holder.dialogImageView.setBackgroundDrawable(UiUtils.getColoredCircleDrawable(ResourceUtils.getColor(R.color.colorPrimary))); // holder.dialogImageView.setImageResource(R.drawable.ic_chat_face); // holder.dialogImageView.setImageResource(R.drawable.n1); } // getQbUsers(dialog); holder.nameTextView.setText(QbDialogUtils.getDialogName(dialog)); holder.nameTextView.setTextColor(ResourceUtils.getColor(R.color.colorPrimary)); holder.lastMessageTextView.setText(prepareTextLastMessage(dialog)); holder.lastMessageTextView.setTextColor(ResourceUtils.getColor(R.color.colorPrimary)); int unreadMessagesCount = dialog.getUnreadMessageCount(); if (unreadMessagesCount == 0) { holder.unreadCounterTextView.setVisibility(View.GONE); } else { holder.unreadCounterTextView.setVisibility(View.VISIBLE); holder.unreadCounterTextView.setText(String.valueOf(unreadMessagesCount > 99 ? 99 : unreadMessagesCount)); } holder.rootLayout.setBackgroundColor(isItemSelected(position) ? ResourceUtils.getColor(R.color.selected_list_item_color) : ResourceUtils.getColor(android.R.color.transparent)); } catch (Exception e) { e.getMessage(); } getOpponents(dialog); return convertView; } private int getUnreadMsgCount(QBChatDialog chatDialog) { Integer unreadMessageCount = chatDialog.getUnreadMessageCount(); if (unreadMessageCount == null) { return 0; } else { return unreadMessageCount; } } private boolean isLastMessageAttachment(QBChatDialog dialog) { String lastMessage = dialog.getLastMessage(); Integer lastMessageSenderId = dialog.getLastMessageUserId(); return TextUtils.isEmpty(lastMessage) && lastMessageSenderId != null; } public void getOpponents(QBChatDialog dialog) { if (dialog.getOccupants().size() < 3) { List<Integer> users = dialog.getOccupants(); user = QbUsersHolder.getInstance().getUsersByIds(users); } else { } } private String prepareTextLastMessage(QBChatDialog chatDialog) { if (isLastMessageAttachment(chatDialog)) { return context.getString(R.string.chat_attachment); } else { return chatDialog.getLastMessage(); } } private static class ViewHolder { ViewGroup rootLayout; ImageView dialogImageView; TextView nameTextView; TextView lastMessageTextView; TextView unreadCounterTextView; ImageView userStatus; } }
C++
UTF-8
4,089
3.296875
3
[]
no_license
/* Nama : Nadia Nur Halimah NIM : 3411151017 Kelas : SIE-A */ #include <stdio.h> #include <conio.h> #include <windows.h> #include <math.h> void menu(){ //algoritma printf("\n--------------- MENU ---------------\n"); printf("\n1. Hitung x+y"); printf("\n2. Hitung x-y"); printf("\n3. Hitung x*y"); printf("\n4. Hitung x^y"); printf("\n5. Hitung f(x)=2x^2-3x+1"); printf("\n6. Exit\n"); } int tambah (int x, int y){ //kamus int jumlah; //algoritma jumlah = x + y; return (jumlah); } int kurang (int x, int y){ //kamus int jumlah; //algoritma jumlah = x - y; return (jumlah); } int kali (int x, int y){ //kamus int jumlah; //algoritma jumlah = x * y; return (jumlah); } int pangkat (int x, int y){ //kamus int jumlah; //algoritma jumlah=pow(x,y); printf("%d ^ %d= %d", x, y,jumlah); } //int fx(int x){ //kamus // int hasil; //algoritma // printf ("Maka x = %d \n", x); // printf ("Berapa hasilnya jika f(x) = 2x^2 - 3x + 1 ? \n"); // hasil=((2 * (pow(x,2)) - ( 3 * x) + 1)); // printf ("\n-----------------------------------\n"); // printf("\nf(%d)=2(%d)^2 - 3(%d) + 1= %d", x, x, x, hasil); //} //main driver int main () { //kamus data int a, b, i, hasil; int pil; //algoritma menu: menu(); printf("\nPilihan = "); scanf("%d", &pil); system("cls"); switch(pil){ case 1 : printf("=====PENJUMLAHAN=====\n\n"); printf("Masukan x : "); scanf("%d",&a); printf("Masukan y : "); scanf("%d",&b); hasil=tambah (a,b); printf("\n %d + %d = %d",a,b,hasil); getch(); system("cls"); goto menu; case 2 : printf("======PENGURANGAN=====\n\n"); printf("Masukan x : "); scanf("%d",&a); printf("Masukan y : "); scanf("%d",&b); hasil=kurang (a,b); printf("\n %d - %d = %d",a,b,hasil); getch(); system("cls"); goto menu; case 3 : printf("=====PERKALIAN=====\n\n"); printf("Masukan x : "); scanf("%d",&a); printf("Masukan y : "); scanf("%d",&b); hasil=kali (a,b); printf("\n %d * %d = %d",a,b,hasil); getch(); system("cls"); goto menu; case 4 : printf("======PERPANGKATAN======\n\n"); printf("Masukan Bilangan : "); scanf("%d",&a); printf("Masukan Nilai Pangkat : "); scanf("%d",&b); printf("\n"); hasil=pangkat (a,b); getch(); system("cls"); goto menu; case 5 : printf("=====HITUNG F(X)======\n\n"); printf("Masukan x : "); scanf("%d",&a); printf("Masukan y : "); scanf("%d",&b); printf("\n\nSyarat %d >= %d <= %d \n", a, a, b); printf ("Hasil jika f(x) = 2x^2 - 3x + 1 \n"); for (i=a;i<=b;i++){ printf ("\nJika x = %d \n", i); hasil=((2 * (pow(i,2)) - ( 3 * i) + 1)); printf("\nf(%d)=2(%d)^2 - 3(%d) + 1= %d", i, i, i, hasil); } getch(); system("cls"); goto menu; case 6 : printf("Byeeeee....."); getch(); return 0; break; } }
Java
UTF-8
290
1.960938
2
[]
no_license
package com.zzt.populateBean.cycle; /** 描述:<br> </> @author 周志通 @version 1.0.0 @date 2020/12/15 20:53 **/ public class A { private B b; public A() { } public B getB() { return b; } public void setB(B b) { this.b = b; } }
Python
UTF-8
6,890
3.484375
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Thu Jan 25 09:06:46 2018 @author: 593787 Robert Piazza - Booz Allen Hamilton """ ##Predict-Multivariable Linear Regression: Model Section 4.2.3 #We need to expand our single variable to multi-variate regression to make it #more robust #Objective: Create a model with multiple predictor variables to predict #nautical miles per gallon (NMPG) #Besides weight, based on R^2 and p-values, we should be using cylinder, #horsepower, and displacement #For this mission, we are using a library for OLS from SciPy Cookbook. It #handles a lot of testing for us. However, the documentation for it is not that #extensive. If you get stuck, you can use print dir(modelname) to see what #properties and methods are available. #%%Model Interpretation Basics #x1 is defined by combining the weight and cylinders feature arrays. Use the #ols method to create our first regression model: #ols(nmpg,x1,'nmpg',['weight','cylinders']) #After executing the command, look at the output. It is an array of p-values, #where the first entry corresponds to the constant (b in y=mx+b). The other #entries are ordered identical to x1. #What is the p-value associated with the "cylinders" variable? from ols import ols #ols.py file held in this project's directory import numpy as np # header: 'mpg', 'cyl', 'disp', 'hp', 'wt', 'accel', 'yr', 'origin','name' data = np.genfromtxt('4-2-3 ships.csv', delimiter=",",names=True, dtype="f8,i8,f8,f8,f8,f8,i8,i8,S5") wt = data['wt'] cyl = data['cyl'] nmpg = data['nmpg'].transpose() hp = data['hp'] disp = data['disp'] x1 = np.array([wt,cyl]).transpose() # OLS Models model1 = ols(nmpg,x1,'nmpg',['weight','cylinders']) print(model1.p) #p values for variables. print(model1.R2) #R2 value for model print(model1.R2adj) #R2 value adjusted for complexity of the model #model summary print(model1.summary()) #SSE is the sum of squares error. #SSTO is the total sum of squares. #SSR is the sum of squares regression. #Adjusted R2 is always less than R2 because R2 always increases with added #features. Also, the total sum of squares is fixed #%%Assumptions #All the previous linear assumptions still apply. With multi-variate regresstion, #we also must assume: #No Predictor Multicollinearity #It is assumed for multivariable linear regression that there is no exact #linear relationship among any of the independent variables in the model # Another way to say this is that there should be no column of predictors that #can be written as a scaled version of any other predictor column (e.g., 1st #column = 2 * 2nd column) or the sum of any combination of scaled predictor #columns (e.g., 1st column = 3 * 2nd column + 2 * 3rd column). #If this assumption is violated-Ridge regression variation may be a better model #for data with multicollinearity. #%%Feature and Model Selection #task: explore the effects of adding additional features to the regression model. from ols import ols import scipy as sp from scipy import stats import numpy as np ##header: 'mpg', 'cyl', 'disp', 'hp', 'wt', 'accel', 'yr', 'origin','name' data = np.genfromtxt('4-2-3 ships.csv', delimiter=",",names=True, dtype="f8,i8,f8,f8,f8,f8,i8,i8,S25") wt = data['wt'] cyl = data['cyl'] nmpg = data['nmpg'].transpose() hp = data['hp'] disp = data['disp'] x1 = np.array([wt,cyl]).transpose() # OLS Models model1 = ols(nmpg,x1,'nmpg',['weight','cylinders']) x2 = np.array([wt,cyl,hp,disp]).transpose() print(model1.summary()) model2 = ols(nmpg,x2,'nmpg',['wt','cyl','hp','disp']) print(model2.summary() ) #note: The durbin watson statistic is the likelihood that the errors are #autocorrelated either positively or negatively which is a common problem in #time-series analysis. In financial data, this can be handled by converting #prices to percentage-price change. #Akaike Information Criterion (AIC) and Bayesian Information Criterion (BIC) #are criterions of model fit. Given multiple different models, you may want to #select the model with smallest AIC or BIC. x3 = np.array([wt,cyl,hp]).transpose() model3 = ols(nmpg,x3,'nmpg',['wt','cyl','hp']) print(model3.summary()) print(model3.b) #When comparing models, you are looking for a high F and low p-value, #indicating that the regression is significant. #If you compare the F statistic and its associated p-value "Prob (F statistic)" #across all three models, you see all three are statistically significant. It #is important to note that the resolution for displaying the p-values may not #be able to differentiate the significance of some terms. In this case, you #should look at the F statistics; again, higher F- tatistics imply more #statistical significance. #We'll stick with model 3 import pylab as pl #load the data in #Calculating the linear dependence between mpg and [intercept, swt, scyl, shp] = model3.b Y = swt*wt +scyl*cyl+shp*hp +intercept resid = nmpg-Y fig, (ax1,ax2) = pl.subplots(2) ax1.scatter(Y,resid, color='black') ax1.set_xlabel('Predicted NMPG') ax1.set_ylabel('Residual') ax2.hist(resid, 40, color='#5D5166') ax2.set_xlabel('Residuals') ax2.set_ylabel('Frequency') ax1.set_title('Weight Model') pl.show() #We can see the residual plot has some shape to it- it's biased and heteroscedastic #%% Using model 3 to predict NMPG from ols import ols import numpy as np import pylab as pl # read in the CSV data as a structured array # names=True will assign column names using the file header # header: 'nmpg', 'cyl', 'disp', 'hp', 'wt', 'accel', 'yr', 'origin','name' data = np.genfromtxt('4-2-3 ships.csv', delimiter=",",names=True, dtype="f8,i8,f8,f8,f8,f8,i8,i8,U25") newdata = np.genfromtxt('4-2-3 FarrisShips.csv', delimiter=",", names=True, dtype="f8,i8,f8,U25") # structured arrays can be conveniently indexed by their column names wt = data['wt'] cyl = data['cyl'] hp = data['hp'] nmpg = data['nmpg'].transpose() # create an input matrix with wt, cyl, and hp as inputs # and train a multivariate model of NMPG with those inputs x = np.array([wt,cyl,hp]).transpose() model = ols(nmpg,x,'nmpg',['wt','cyl','hp']) newwt = newdata['wt'] newcyl = newdata['cyl'] newhp = newdata['hp'] newconstant = np.ones([3]) # build a new input matrix from the newdata array # see above to access data from a structured array # and use it to build an input matrix newx = np.array([newconstant, newwt, newcyl, newhp]).transpose() # taking the dot product of the input matrix and the # model parameters will yield predictions for new ships prediction = np.dot(newx,model.b) # print the model predictions print(newdata['name']) print(prediction) pl.figure() pl.scatter(wt,nmpg,color='#FF971C') pl.scatter(newdata['wt'],prediction,color='#5D5166') pl.title('Weight vs NMPG') pl.show() pl.figure() pl.scatter(hp,nmpg,color='#FF971C') pl.scatter(newdata['hp'],prediction,color='#5D5166') pl.title('Horsepower vs NMPG') pl.show() #neither of these shows outliers
Python
UTF-8
1,119
2.84375
3
[]
no_license
import collections from python_vlookup import python_vlookup array = python_vlookup.get_csv_data('shareasale_lookup.csv') print array #Return a dictionary def get_credentials(): host = 'hostname' un = 'username' pw = 'password' credentials = {'hostname':host,'username':un,'password':pw} return credentials credentials = get_credentials() print credentials['password'] #Return a named tuple def get_credentials(): host = 'hostname' un = 'username' pw = 'password' credentials = collections.namedtuple('credentials', ['host', 'un', 'pw']) return credentials(host,un,pw) credentials = get_credentials() print credentials.host #Return a regular tuple def get_credentials(): host = 'hostname' un = 'username' pw = 'password' return host,un,pw host,un,pw = get_credentials() print un #Return a single value def get_credentials(field): if field == 'host': return 'hostname' if field == 'un': return 'username' if field == 'pw': return 'password' host = get_credentials('host') print host
C#
UTF-8
916
2.578125
3
[]
no_license
namespace QuizProjectMvc.Services.Data.Protocols { using System.Collections.Generic; using System.Linq; using System.Web.Mvc; using QuizProjectMvc.Data.Models; public interface ICategoriesService { IQueryable<QuizCategory> GetAll(); /// <summary> /// Returns the top <see cref="count"/> of solutions ordered by solutions count descending /// </summary> /// <param name="count">The number of solutions to return</param> /// <returns>Returns a queryable that can be additionally filtered before materializing</returns> IQueryable<QuizCategory> GetTop(int count); IQueryable<QuizCategory> FilterByPattern(string pattern); QuizCategory GetById(int id); void Save(); bool Delete(int id); void Create(QuizCategory category); IEnumerable<SelectListItem> GetCategoryOptions(); } }
PHP
UTF-8
1,535
2.75
3
[]
no_license
<?php /** * Copyright (c) 2016 Kiboko SAS. * * @author Grégory Planchat <gregory@kiboko.fr> */ namespace Kiboko\Component\MagentoORM\Model; class AttributeOptionValue implements AttributeOptionValueInterface { use LocalizedMappableTrait; use IdentifiableTrait; /** * @var int */ private $optionId; /** * @var int */ private $storeId; /** * @var string */ private $value; /** * @param int $optionId * @param int $storeId * @param string $value */ public function __construct($optionId, $storeId, $value) { $this->optionId = $optionId; $this->storeId = $storeId; $this->value = $value; } /** * @return int */ public function getOptionId() { return $this->optionId; } /** * @return int */ public function getStoreId() { return $this->storeId; } /** * @return string */ public function getValue() { return $this->value; } /** * @param int $attributeOptionValueId * @param int $optionId * @param int $storeId * @param string $value * * @return AttributeOptionValueInterface */ public static function buildNewWith( $attributeOptionValueId, $optionId, $storeId, $value = null ) { $object = new static($optionId, $storeId, $value); $object->persistedToId($attributeOptionValueId); return $object; } }
Java
UTF-8
649
3.09375
3
[]
no_license
package collections.List; import java.util.*; @SuppressWarnings("serial") class MyArrayList<E> extends ArrayList<E> { public boolean add(E e) { if (e instanceof Integer || e instanceof Double || e instanceof Float) { super.add(e); return true; } throw new ClassCastException ("Only Integer, Float, Double are supported"); } } public class assignment4 { public static void main(String[] args) { List<Object> list = new MyArrayList<>(); try { list.add(1234); list.add(12.4F); list.add(123.094D); // list.add("Krishna"); } catch (Exception e) { e.printStackTrace(); } System.out.println(list); } }
JavaScript
UTF-8
1,816
2.625
3
[]
no_license
export default class PaginateModel { lastPage = 1; pageNum = 0; pageSize = 0; size = 0; total = 0; startRow = 0; perPageShow = 0; /** * 构造器 * 可直接传入页面参数变更回调函数 * @param changeCallBack * @param pageSize */ constructor(changeCallBack = null, pageSize = 14) { if (changeCallBack) { this.changeCallBack = () => { changeCallBack(); }; } this.pageSize = pageSize; this.perPageShow = pageSize; } /** * 设置当前页为下一页 * @param page */ next(page = null) { this.jump(page || this.pageNum + 1); } /** * 跳转到某一页 * @param page */ jump(page) { this.pageNum = page > this.lastPage ? this.lastPage : page; } /** * 跳转到最后一页 */ jumpToLast() { this.pageNum = this.lastPage; } /** * 将 ajax 获取到的分页信息注入 模型中 * @param resp */ setPaginate(resp) { this.lastPage = resp.lastPage; this.pageNum = resp.pageNum; this.pageSize = resp.pageSize; this.size = resp.size; this.startRow = resp.startRow; this.total = resp.total; } /** * 转换成 JSON 格式提交 * @returns {{pageSize: number, pageNum: number}} */ getJSON() { return { pageNum: this.pageNum, pageSize: this.pageSize } } /** * 改变当前页触发函数 */ changePageCallBack() { } /** * 改变显示数量出发函数 */ changeSizeCallBack() { } /** * 改变当前页 和 改变显示数量均会执行 */ changeCallBack() { } }
JavaScript
UTF-8
2,312
2.515625
3
[ "MIT" ]
permissive
// This script licensed under the MIT. // http://orgachem.mit-license.org /** * @fileoverview A class for list publishers for HTML. * @author orga.chem.job@gmail.com (OrgaChem) */ var basePath = '../lib'; var HtmlElement = require(basePath + '/html/HtmlElement'); var tsumekusa = require('tsumekusa'); var util = tsumekusa.util; var DefinitionPublisher = tsumekusa.DefaultPublishers.DEFINITION.constructor; /** * A class for list item publisher for HTML. * @constructor * @extends {module:tsumekusa/lib/publishing/IElementPublisher} * @exports lib/HtmlDefinitionPublisher */ var HtmlDefinitionPublisher = function() { DefinitionPublisher.call(this); this.setDisplayWidth(Number.MAX_VALUE); }; util.inherits(HtmlDefinitionPublisher, DefinitionPublisher); util.addSingletonGetter(HtmlDefinitionPublisher); /** @override */ HtmlDefinitionPublisher.prototype.publish = function(element) { var def = this.createDefinitionDoms(element); return def.join(''); }; /** * Creates a HTML definition elements. * @param {module:tsumekusa/Definition} element Tsumekusa element. * @return {Array.<module:lib/html/HtmlElement>} HTML elements. */ HtmlDefinitionPublisher.prototype.createDefinitionDoms = function(element) { var arr = [ this.createDefinitionTermDom(element), this.createDefinitionDescriptionsDom(element) ]; return arr; }; /** * Creates a HTML definition term element. * @param {module:tsumekusa/Definition} element Tsumekusa element. * @return {module:lib/html/HtmlElement} HTML element. */ HtmlDefinitionPublisher.prototype.createDefinitionTermDom = function( element) { var term = element.getTerm().getInlineElements().join(''); var dt = new HtmlElement('dt', false, term); var ref = element.getReference(), refID; if (refId = ref.getReferenceId()) { dt.setAttribute('id', refId); } return dt; } /** * Creates a HTML definition descriptions element. * @param {module:tsumekusa/Definition} element Tsumekusa element. * @return {module:lib/html/HtmlElement} HTML element. */ HtmlDefinitionPublisher.prototype.createDefinitionDescriptionsDom = function(element) { var descriptions = element.getDescriptions().publish(); return new HtmlElement('dd', false, descriptions); } // Export the constructor module.exports = HtmlDefinitionPublisher;
Java
UTF-8
1,007
1.921875
2
[]
no_license
package com.cnfantasia.server.api.access.codec.ake.bean.request; import com.cnfantasia.server.api.access.codec.ake.bean.base.DataDetailObj; import java.math.BigDecimal; public class UseTraderCoupon implements DataDetailObj { private static final long serialVersionUID = -6848035346462902727L; private String traderCouponGrantSn; private BigDecimal traderCouponValue; public String getTraderCouponGrantSn() { return this.traderCouponGrantSn; } public void setTraderCouponGrantSn(String traderCouponGrantSn) { this.traderCouponGrantSn = traderCouponGrantSn; } public BigDecimal getTraderCouponValue() { return this.traderCouponValue; } public void setTraderCouponValue(BigDecimal traderCouponValue) { this.traderCouponValue = traderCouponValue; } public String toString() { return "UseTraderCoupon [traderCouponGrantSn=" + this.traderCouponGrantSn + ", traderCouponValue=" + this.traderCouponValue + "]"; } }
C++
UTF-8
1,934
3.21875
3
[]
no_license
#include "Item.h" #include <vector> #include <string> #include <iostream> #include <fstream> using namespace std; struct EmptyPriorityQueue { }; //exceptionclass template<typename ElemType> class PQueueVector { protected: typedef Item<ElemType> Item; typedef PQComp<ElemType> PQComp; private: vector<Item>V; static const int DEF_SIZE = 8; public: PQueueVector() : V(0) { } bool isEmpty() const { return V.empty(); } int size() {return V.size();} int* insert(const int k, const ElemType& e) { int* loc = new int[1]; *loc = V.size(); V.push_back(Item(k,e,loc)); return loc; } int* min() throw(EmptyPriorityQueue) { if (V.empty()) throw EmptyPriorityQueue(); int keyIndex = 0; for(int i = 0; i < V.size()-1; i++){ if (V[i].getKey() < V[keyIndex].getKey()) keyIndex = i; } return V[keyIndex].loco; } void removeMin() throw(EmptyPriorityQueue) { int compare = 0; cout << "Removing min element..." << endl; if (V.empty()) throw EmptyPriorityQueue(); int index = 0; int min = INT_MAX; for(int i = 0; i < V.size()-1; i++){ if(V[i].getKey() < min) { min = V[i].getKey(); index = i; } compare++; } V.erase(V.begin()+index); for(int i = index; i < V.size(); i++) *V[i].loco = i; cout << compare << " Comparisons made" << endl; } void decreaseKey(int* location, int k) { V[*location].setKey(k); } void remove(int* location) throw (EmptyPriorityQueue) { if (V.isEmpty()) throw EmptyPriorityQueue(); V.erase(location); } void createPQueueVector(PQueueVector<ElemType>& pq, string fileName) { ifstream ist(fileName.c_str()); int key; string elem; while(ist>>key>>elem) { pq.insert(key,elem); } } void printQueue() { if (V.empty()) cout << "Empty Queue (." << endl; for(int i = 0; i < V.size(); i++){ cout << "value: " << V[i].getElem() << " // " << "key: " << V[i].getKey() << endl; } cout << endl; } };
C#
UTF-8
1,802
2.609375
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using PureCM.Server; namespace External_Items { /// <summary> /// Abstract class for a user /// </summary> internal abstract class ExUser : ExItem { internal ExUser(ExFactory oFactory, ExFactory.TPluginType tType, UInt32 nExID) : base(oFactory, tType, nExID) { } /// <summary> /// Get the synchronized user. If the user does not already exist then this will /// optionally create a new one. /// </summary> internal ExUser GetSyncUser(bool bCreateIfNotExist) { if (m_oSyncUser == null) { m_oSyncUser = Factory.SyncFactory.GetUser(this); if ((m_oSyncUser == null) && bCreateIfNotExist) { m_oSyncUser = Factory.SyncFactory.CreateUser(this); if (m_oSyncUser != null && m_oSyncUser.ID == UInt32.MaxValue) { m_oSyncUser = null; } if (m_oSyncUser == null) { Factory.Plugin.LogWarning("Failed to create " + Factory.SyncFactory.PluginName + " user for " + Factory.PluginName + " user '" + Name + "'."); } } } return m_oSyncUser; } /// <summary> /// What is the email address for this user? /// </summary> internal String EmailAddress { get { return GetEmailAddress(); } } private ExUser m_oSyncUser; /// <summary> /// What is the email address for this user? /// </summary> internal abstract String GetEmailAddress(); } }
Java
UTF-8
623
3.25
3
[]
no_license
class Solution { public boolean isPalindrome(int x) { int flag = 0; String a = Integer.toString(x); for(int i = 0; i<a.length()/2; i++){ System.out.println("first loop"); for(int j = (a.length()-1)-i; j>=a.length()/2; j--){ System.out.println("second loop"); if(a.charAt(j) != a.charAt(i)){ flag = 1; break; }else{ break; } } if(flag == 1){ return false; } } return true; } }
JavaScript
UTF-8
3,994
2.890625
3
[]
no_license
let rootUrl = '' let jsList = {} let cssList = {} let jsLoadStatus = {} let cssLoadStatus = {} function create(createType) { function createScript(path, loadCb, readyCb, errorCb) { if(!document.getElementById(path)) { var scr = document.createElement('script'); scr.type = 'text/javascript'; scr.onload = loadCb; scr.onreadystatechange = function() { readyCb(scr) }; scr.onerror = errorCb; scr.src = `${rootUrl}${path}`; scr.id = path; document.body.appendChild(scr); } } function createStyle(src, loadCb, readyCb, errorCb) { if(!document.getElementById(src)) { let file = document.createElement('link'); file.rel = 'stylesheet'; file.href = `${rootUrl}${src}` file.id = `${src}` file.onload = loadCb file.onreadystatechange = function() { readyCb(file) }; file.onerror = errorCb document.head.appendChild(file) } } if(createType === 'script') return createScript else if(createType === 'style') return createStyle else return null } function loadScript(path, createFn, callback) { var done = false; function handleLoad() { if (!done) { done = true; // logger.info('loaded:', path) callback(path, "ok"); } } function handleReadyStateChange(scr) { var state; if (!done) { state = scr.readyState; if (state === "complete") { // logger.info('Completed', scr.src); handleLoad(); } } } function handleError() { if (!done) { done = true; callback(path, "error"); } } // call the create function with the appropriate callbacks createFn(path, handleLoad, handleReadyStateChange, handleError) } function loadList(srcName, listType, i, callback) { { let list = [] if(listType === 'script') { if(!jsLoadStatus[srcName]) return callback() list = jsList[srcName] } else if(listType === 'style') { if(!cssLoadStatus[srcName]) return callback() list = cssList[srcName] } loadScript(list[i], create(listType), function(src, status) { if(status === 'error') console.error('Failed to load:', src) if(i < list.length-1) { loadList(srcName, listType, i+1, callback); } else { if(listType === 'script') jsLoadStatus[srcName] = false else if(listType === 'style') cssLoadStatus[srcName] = false callback(); } }) } } function load(listType, srcName, callback){ if(listType === 'script') { if(!srcName || !jsList[srcName]) return; jsLoadStatus[srcName] = true; } else if (listType === 'style') { if(!srcName || !cssList[srcName]) return; cssLoadStatus[srcName] = true; } loadList(srcName, listType, 0, callback); // 0 is the beginning index } function unload(listType, srcName) { if(listType === 'script') { if(!srcName || !jsList[srcName]) return; for(let src of jsList[srcName]) { let js = document.getElementById(`${src}`); if(js) { js.remove() } } jsLoadStatus[srcName] = false; } else if(listType === 'style') { if(!srcName || !cssList[srcName]) return; // logger.info(`******* Removing CSS Group ${srcName} *******`) for(let src of cssList[srcName]) { let css = document.getElementById(`${src}`); if(css) { css.remove() // logger.info(`Unloaded css: ${src}`) } } cssLoadStatus[srcName] = false; } else return } function init(styleList, scriptList, baseUrl) { cssList = styleList; jsList = scriptList; rootUrl = baseUrl } export default { load, unload, init }
Java
UTF-8
4,498
2.671875
3
[]
no_license
package UIComponents; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import javax.imageio.ImageIO; import javax.swing.Timer; import GameAssets.DefaultRiskMode.DefaultRiskMode; import HelperTools.PixelString; import ModelClasses.Card; import ModelClasses.Card.CARD_TYPES; public abstract class VisualCard implements Serializable { public static final int width = 160; public static final int height = 220; public static enum COLOR_MATCHES { YELLOW(CARD_TYPES.EXTREME_UNIT), VIOLET(CARD_TYPES.HARD_UNIT), BLUE(CARD_TYPES.MODERATE_UNIT) , GREEN(CARD_TYPES.EASY_UNIT); private Color color; private CARD_TYPES cardType; private COLOR_MATCHES(CARD_TYPES cardType) { this.cardType = cardType; if(cardType == CARD_TYPES.EASY_UNIT) color = Color.GREEN; else if(cardType == CARD_TYPES.MODERATE_UNIT) color = Color.BLUE; else if(cardType == CARD_TYPES.HARD_UNIT) color = new Color(148, 0, 211); else color = Color.YELLOW; } } public CARD_TYPES cardType; private COLOR_MATCHES drawColor; public VisualCard(CARD_TYPES cardType) { this.cardType = cardType; if(cardType == CARD_TYPES.EASY_UNIT) drawColor = COLOR_MATCHES.GREEN; else if(cardType == CARD_TYPES.MODERATE_UNIT) drawColor = COLOR_MATCHES.BLUE; else if(cardType == CARD_TYPES.HARD_UNIT) drawColor = COLOR_MATCHES.VIOLET; else drawColor = COLOR_MATCHES.YELLOW; } public void paint(Graphics painter, Coordinate drawCoordinate) { final int level = 2; Graphics2D g2d = (Graphics2D)painter; g2d.setStroke(new BasicStroke(level * 2)); g2d.setColor(Color.DARK_GRAY); g2d.fillRect(drawCoordinate.xCoord, drawCoordinate.yCoord, width, height); g2d.setColor(drawColor.color); g2d.drawRect(drawCoordinate.xCoord, drawCoordinate.yCoord, width, height); g2d.setColor(Color.LIGHT_GRAY); painter.setFont(new Font("pixel", Font.BOLD, 20)); String cardTag = getCardTag().substring(0); int underscroreIndex = cardTag.indexOf("_"); if(underscroreIndex == -1) painter.drawString(cardTag, drawCoordinate.xCoord + level*4, (int)(drawCoordinate.yCoord + (1.0/10.0) * height)); else { String upperLine = cardTag.substring(0, underscroreIndex); painter.drawString(upperLine, drawCoordinate.xCoord + level*4, (int)(drawCoordinate.yCoord + (1.0/10.0) * height)); String downLine = cardTag.substring(underscroreIndex + 1); underscroreIndex = downLine.indexOf("_"); if(underscroreIndex == -1) painter.drawString(downLine, drawCoordinate.xCoord + level*4, (int)(drawCoordinate.yCoord + (2.0/10.0) * height)); else { upperLine = downLine.substring(0, underscroreIndex); painter.drawString(upperLine, drawCoordinate.xCoord + level*4, (int)(drawCoordinate.yCoord + (2.0/10.0) * height)); downLine = downLine.substring(underscroreIndex + 1); painter.drawString(downLine, drawCoordinate.xCoord + level*4, (int)(drawCoordinate.yCoord + (3.0/10.0) * height)); } } ArrayList<Coordinate> characteristicData = getCharacteristicVisualData(); for(Coordinate coord : characteristicData) painter.fillRect((int)(drawCoordinate.xCoord + (1.0/5.0)*width +level*4) + coord.xCoord , (int)(drawCoordinate.yCoord + (2.0/6.0) * height) + coord.yCoord, VisualTerritory.DEFAULT_DRAW_SIZE , VisualTerritory.DEFAULT_DRAW_SIZE); painter.setFont(new Font("pixel", Font.BOLD, 40)); painter.drawString(Integer.toString(CARD_TYPES.getUnitBuff(cardType)) , drawCoordinate.xCoord + 7 * width / 8 - level*4, drawCoordinate.yCoord + height - level*4); painter.drawImage(getSymbolicData(), drawCoordinate.xCoord + level*4, (int)(drawCoordinate.yCoord + (5.0/6.0) * height) - level*4 , drawCoordinate.xCoord + width/4 + level*4, drawCoordinate.yCoord + height - level*4, 0, 0 , getSymbolicData().getWidth(), getSymbolicData().getHeight(), null); } protected abstract String getCardTag(); protected abstract ArrayList<Coordinate> getCharacteristicVisualData(); protected abstract BufferedImage getSymbolicData(); public abstract VisualCard copy(); public abstract boolean checkItsCorresponding(String checkTag); public abstract String getCorrespondingTag(); public abstract void print(); }
TypeScript
UTF-8
958
2.84375
3
[ "MIT" ]
permissive
import { Injectable } from '@angular/core'; export enum LogLevel { Disabled = 0, Error, Warn, Info, Debug, } @Injectable() export class LogService { public logLevel = LogLevel.Info; public writer = console; public messagePrefix = () => 'ChatService:'; public error(...messages: any[]) { if (this.logLevel >= LogLevel.Error) { this.writer.error(this.messagePrefix(), ...messages); } } public warn(...messages: any[]) { if (this.logLevel >= LogLevel.Warn) { this.writer.warn(this.messagePrefix(), ...messages); } } public info(...messages: any[]) { if (this.logLevel >= LogLevel.Info) { this.writer.info(this.messagePrefix(), ...messages); } } public debug(...messages: any[]) { if (this.logLevel >= LogLevel.Debug) { this.writer.log(this.messagePrefix(), ...messages); } } }
Java
UTF-8
681
1.671875
2
[]
no_license
package io.cloud.api.documents; import lombok.Data; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; import java.text.DateFormat; import java.util.Calendar; import java.util.Date; import java.util.List; @Data @Document(collection="faturas") public class Fatura { public enum Status {PAGA, NAOPAGA} @Id private String faturaId; private ClientePessoaFisica cliente; private List<Plano> planosContratados; private Double valorTotalFatura; private Calendar dataReferenciaFatura; private Calendar dataVencimentoFatura; private Status status; }
Java
UTF-8
19,833
1.828125
2
[]
no_license
package com.thinkfaster.manager; import android.graphics.Color; import android.util.Log; import com.thinkfaster.asynctask.SoundLoaderAsyncTask; import com.thinkfaster.util.ContextConstants; import org.andengine.audio.sound.Sound; import org.andengine.audio.sound.SoundFactory; import org.andengine.engine.Engine; import org.andengine.engine.camera.Camera; import org.andengine.opengl.font.Font; import org.andengine.opengl.font.FontFactory; import org.andengine.opengl.texture.TextureOptions; import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.andengine.opengl.texture.atlas.bitmap.BuildableBitmapTextureAtlas; import org.andengine.opengl.texture.atlas.bitmap.source.IBitmapTextureAtlasSource; import org.andengine.opengl.texture.atlas.buildable.builder.BlackPawnTextureAtlasBuilder; import org.andengine.opengl.texture.atlas.buildable.builder.ITextureAtlasBuilder; import org.andengine.opengl.texture.region.ITextureRegion; import org.andengine.opengl.texture.region.ITiledTextureRegion; import org.andengine.opengl.texture.region.TextureRegion; import org.andengine.opengl.vbo.VertexBufferObjectManager; import org.andengine.ui.activity.BaseGameActivity; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * User: Breku * Date: 21.09.13 */ public class ResourcesManager { private static final ResourcesManager INSTANCE = new ResourcesManager(); private static final String TAG = "ResourcesManager"; private BaseGameActivity activity; private Engine engine; private Camera camera; private VertexBufferObjectManager vertexBufferObjectManager; private BitmapTextureAtlas splashTextureAtlas, menuFontTextureAtlas, gameFontTextureAtlas, greenFontTextureAtlas, chalkFontTextureAtlas, loadingTextureAtlas; private BuildableBitmapTextureAtlas menuTextureAtlas, aboutTextureAtlas, endGameTextureAtlas, recordTextureAtlas, gameTypeTextureAtlas, gameTextureAtlas; // Game private List<ITiledTextureRegion> animalTiledTextureRegionList; private List<BuildableBitmapTextureAtlas> gameTextureAtlasList; private TextureRegion questionMarkGameTextureRegion; // Splash private ITextureRegion splashTextureRegion; // Menu private ITextureRegion menuBackgroundTextureRegion, playButtonTextureRegion, hexagonTextureRegion, highscoresButtonTextureRegion; private ITiledTextureRegion soundButtonsTiledTextureRegion; // Help private ITextureRegion aboutBackgroundTextureRegion; // EndGame private ITextureRegion endGameBackgroundTextureRegion; // HighScore private ITextureRegion recordBackgroundTextureRegion, buttonHighScoreTextureRegion, highscoreSmallGameTypeTextureRegion, highscoreMediumGameTypeTextureRegion, highscoreBigGameTypeTextureRegion; ; //Loading private ITextureRegion loadingTextureRegion; // Game Type private ITextureRegion backgroundGameTypeTextureRegion, smallGameTypeTextureRegion, mediumGameTypeTextureRegion, bigGameTypeTextureRegion; private List<Sound> animalSoundList = new ArrayList<>(); private Sound startGameSound; private Font whiteFont, blackFont, greenFont, chalkFont; private SoundLoaderAsyncTask soundLoaderAsyncTask; public SoundLoaderAsyncTask getSoundLoaderAsyncTask() { return soundLoaderAsyncTask; } public static void prepareManager(Engine engine, BaseGameActivity activity, Camera camera, VertexBufferObjectManager vertexBufferObjectManager) { getInstance().engine = engine; getInstance().activity = activity; getInstance().camera = camera; getInstance().vertexBufferObjectManager = vertexBufferObjectManager; } public static ResourcesManager getInstance() { return INSTANCE; } public List<Sound> getAnimalSoundList() { return animalSoundList; } public TextureRegion getQuestionMarkGameTextureRegion() { return questionMarkGameTextureRegion; } public ITextureRegion getHexagonTextureRegion() { return hexagonTextureRegion; } public void loadAboutResources() { loadAboutGraphics(); } public void loadMainMenuResources() { loadMainMenuGraphics(); loadMainMenuSounds(); loadWhiteFont(); loadBlackFont(); loadGreenFont(); loadChalkFont(); } public void loadGameResources() { loadGameGraphics(); loadEndGameResources(); } public void loadEndGameResources() { loadEndGameGraphics(); } public Engine getEngine() { return engine; } public void loadRecordResources() { loadHighScoreGraphics(); } public void loadGameTypeResources() { loadGameTypeGraphics(); } public void loadSplashScreen() { BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); splashTextureAtlas = new BitmapTextureAtlas(activity.getTextureManager(), 1024, 1024, TextureOptions.BILINEAR); splashTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(splashTextureAtlas, activity, "splash.jpg", 0, 0); splashTextureAtlas.load(); } public void loadMenuTextures() { menuTextureAtlas.load(); } public void unloadSplashScreen() { splashTextureAtlas.unload(); splashTextureRegion = null; } public void unloadAboutTextures() { aboutTextureAtlas.unload(); } public void unloadEndGameTextures() { endGameTextureAtlas.unload(); } public void unloadRecordsTextures() { recordTextureAtlas.unload(); } public void unloadGameTypeTextures() { gameTypeTextureAtlas.unload(); } public void unloadGameTextures() { gameTextureAtlas.unload(); for (BuildableBitmapTextureAtlas atlas : gameTextureAtlasList) { atlas.unload(); } } public List<ITiledTextureRegion> getAnimalTiledTextureRegionList() { return animalTiledTextureRegionList; } public void unloadMenuTextures() { menuTextureAtlas.unload(); } public BaseGameActivity getActivity() { return activity; } public Camera getCamera() { return camera; } public VertexBufferObjectManager getVertexBufferObjectManager() { return vertexBufferObjectManager; } public ITextureRegion getSplashTextureRegion() { return splashTextureRegion; } public ITextureRegion getMenuBackgroundTextureRegion() { return menuBackgroundTextureRegion; } public ITextureRegion getAboutBackgroundTextureRegion() { return aboutBackgroundTextureRegion; } public Font getWhiteFont() { return whiteFont; } public Font getBlackFont() { return blackFont; } public ITextureRegion getHighscoreBigGameTypeTextureRegion() { return highscoreBigGameTypeTextureRegion; } public ITextureRegion getHighscoreMediumGameTypeTextureRegion() { return highscoreMediumGameTypeTextureRegion; } public ITextureRegion getHighscoreSmallGameTypeTextureRegion() { return highscoreSmallGameTypeTextureRegion; } public Font getGreenFont() { return greenFont; } public Font getChalkFont() { return chalkFont; } public ITextureRegion getEndGameBackgroundTextureRegion() { return endGameBackgroundTextureRegion; } public ITextureRegion getRecordBackgroundTextureRegion() { return recordBackgroundTextureRegion; } public ITextureRegion getButtonHighScoreTextureRegion() { return buttonHighScoreTextureRegion; } public ITextureRegion getBackgroundGameTypeTextureRegion() { return backgroundGameTypeTextureRegion; } public ITextureRegion getSmallGameTypeTextureRegion() { return smallGameTypeTextureRegion; } public ITextureRegion getMediumGameTypeTextureRegion() { return mediumGameTypeTextureRegion; } public ITextureRegion getBigGameTypeTextureRegion() { return bigGameTypeTextureRegion; } public ITextureRegion getLoadingTextureRegion() { return loadingTextureRegion; } public ITiledTextureRegion getSoundButtonsTiledTextureRegion() { return soundButtonsTiledTextureRegion; } public void loadLoadingResources() { if (loadingTextureAtlas != null) { loadingTextureAtlas.load(); return; } BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/loading/"); loadingTextureAtlas = new BitmapTextureAtlas(activity.getTextureManager(), 1024, 1024, TextureOptions.BILINEAR); loadingTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(loadingTextureAtlas, activity, "background.png", 0, 0); loadingTextureAtlas.load(); } public ITiledTextureRegion getAnimalTiledTexture(int animalId) { return animalTiledTextureRegionList.get(animalId); } public ITextureRegion getPlayButtonTextureRegion() { return playButtonTextureRegion; } public ITextureRegion getHighscoresButtonTextureRegion() { return highscoresButtonTextureRegion; } public Sound getStartGameSound() { return startGameSound; } public void loadAnimalsMusicAsynchronously() { soundLoaderAsyncTask = new SoundLoaderAsyncTask(animalSoundList, engine, activity); soundLoaderAsyncTask.execute(); } private void loadAboutGraphics() { BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/about/"); aboutTextureAtlas = new BuildableBitmapTextureAtlas(activity.getTextureManager(), 1024, 1024, TextureOptions.BILINEAR); aboutBackgroundTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(aboutTextureAtlas, activity, "background.jpg"); try { aboutTextureAtlas.build(new BlackPawnTextureAtlasBuilder<IBitmapTextureAtlasSource, BitmapTextureAtlas>(0, 0, 1)); aboutTextureAtlas.load(); } catch (ITextureAtlasBuilder.TextureAtlasBuilderException e) { Log.e(TAG, "Error during building atlasses"); } } private void loadMainMenuGraphics() { if (menuTextureAtlas != null) { menuTextureAtlas.load(); return; } BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/menu/"); menuTextureAtlas = new BuildableBitmapTextureAtlas(activity.getTextureManager(), 1024, 1024, TextureOptions.DEFAULT); menuBackgroundTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(menuTextureAtlas, activity, "background.jpg"); buttonHighScoreTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(menuTextureAtlas, activity, "menu_high.png"); playButtonTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(menuTextureAtlas, activity, "playButton.png"); hexagonTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(menuTextureAtlas, activity, "hexagon.png"); highscoresButtonTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(menuTextureAtlas, activity, "highscoresButton.png"); soundButtonsTiledTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(menuTextureAtlas, activity, "soundButtons.png", 2, 1); try { menuTextureAtlas.build(new BlackPawnTextureAtlasBuilder<IBitmapTextureAtlasSource, BitmapTextureAtlas>(0, 0, 0)); menuTextureAtlas.load(); } catch (ITextureAtlasBuilder.TextureAtlasBuilderException e) { Log.e(TAG, "Error during building atlasses"); } } private void loadWhiteFont() { if (menuFontTextureAtlas != null) { return; } FontFactory.setAssetBasePath("font/"); menuFontTextureAtlas = new BitmapTextureAtlas(activity.getTextureManager(), 512, 512, TextureOptions.BILINEAR); whiteFont = FontFactory.createStrokeFromAsset(activity.getFontManager(), menuFontTextureAtlas, activity.getAssets(), "ChalkPaint.ttf", 50, true, Color.WHITE, 2, Color.WHITE); menuFontTextureAtlas.load(); whiteFont.load(); } private void loadBlackFont() { if (gameFontTextureAtlas != null) { return; } FontFactory.setAssetBasePath("font/"); gameFontTextureAtlas = new BitmapTextureAtlas(activity.getTextureManager(), 512, 512, TextureOptions.BILINEAR); blackFont = FontFactory.createStrokeFromAsset(activity.getFontManager(), gameFontTextureAtlas, activity.getAssets(), "font1.ttf", 30, true, Color.BLACK, 1, Color.BLACK); gameFontTextureAtlas.load(); blackFont.load(); } private void loadGreenFont() { if (greenFontTextureAtlas != null) { return; } FontFactory.setAssetBasePath("font/"); greenFontTextureAtlas = new BitmapTextureAtlas(activity.getTextureManager(), 512, 512, TextureOptions.BILINEAR); greenFont = FontFactory.createStrokeFromAsset(activity.getFontManager(), greenFontTextureAtlas, activity.getAssets(), "ChalkPaint.ttf", 50, true, Color.GREEN, 2, Color.GREEN); greenFontTextureAtlas.load(); greenFont.load(); } private void loadChalkFont() { if (chalkFontTextureAtlas != null) { return; } FontFactory.setAssetBasePath("font/"); chalkFontTextureAtlas = new BitmapTextureAtlas(activity.getTextureManager(), 512, 512, TextureOptions.BILINEAR); chalkFont = FontFactory.createStrokeFromAsset(activity.getFontManager(), chalkFontTextureAtlas, activity.getAssets(), "ChalkPaint.ttf", 50, true, Color.BLACK, 2, Color.BLACK); chalkFontTextureAtlas.load(); chalkFont.load(); } private void loadGameGraphics() { if (gameTextureAtlas != null) { gameTextureAtlas.load(); for (BuildableBitmapTextureAtlas atlas : gameTextureAtlasList) { atlas.load(); } return; } gameTextureAtlas = new BuildableBitmapTextureAtlas(activity.getTextureManager(), 1024, 1024, TextureOptions.DEFAULT); gameTextureAtlasList = new ArrayList<>(); for (int i = 0; i < ContextConstants.NUMBER_OF_ANIMALS; i++) { gameTextureAtlasList.add(new BuildableBitmapTextureAtlas(activity.getTextureManager(), 512, 512, TextureOptions.DEFAULT)); } loadOterGameTextures(); loadAnimalsTextures(); loadGameAtlases(); } private void loadOterGameTextures() { BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/game/"); questionMarkGameTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(gameTextureAtlas, activity, "questionItem.png"); } private void loadAnimalsTextures() { animalTiledTextureRegionList = new ArrayList<>(); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/game/animals/"); for (int i = 0; i < ContextConstants.NUMBER_OF_ANIMALS; i++) { animalTiledTextureRegionList.add(BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(gameTextureAtlasList.get(i), activity, i + ".jpg", 2, 2)); } } private void loadGameAtlases() { try { for (int i = 0; i < ContextConstants.NUMBER_OF_ANIMALS; i++) { gameTextureAtlasList.get(i).build(new BlackPawnTextureAtlasBuilder<IBitmapTextureAtlasSource, BitmapTextureAtlas>(0, 0, 0)); gameTextureAtlasList.get(i).load(); } gameTextureAtlas.build(new BlackPawnTextureAtlasBuilder<IBitmapTextureAtlasSource, BitmapTextureAtlas>(0, 0, 0)); gameTextureAtlas.load(); } catch (ITextureAtlasBuilder.TextureAtlasBuilderException e) { Log.e(TAG, "Error during building atlasses"); } } private void loadMainMenuSounds() { if (startGameSound != null) { return; } SoundFactory.setAssetBasePath("mfx/animals/"); try { startGameSound = SoundFactory.createSoundFromAsset(getEngine().getSoundManager(), activity, "go.ogg"); } catch (IOException e) { Log.i(TAG, "Error during loading sounds"); } } private void loadEndGameGraphics() { if (endGameTextureAtlas != null) { endGameTextureAtlas.load(); } BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/endgame/"); endGameTextureAtlas = new BuildableBitmapTextureAtlas(activity.getTextureManager(), 1024, 512, TextureOptions.BILINEAR); endGameBackgroundTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(endGameTextureAtlas, activity, "background.png"); try { endGameTextureAtlas.build(new BlackPawnTextureAtlasBuilder<IBitmapTextureAtlasSource, BitmapTextureAtlas>(0, 0, 0)); endGameTextureAtlas.load(); } catch (ITextureAtlasBuilder.TextureAtlasBuilderException e) { Log.e(TAG, "Error during building atlasses"); } } private void loadHighScoreGraphics() { if (recordTextureAtlas != null) { recordTextureAtlas.load(); } BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/highscore/"); recordTextureAtlas = new BuildableBitmapTextureAtlas(activity.getTextureManager(), 1024, 1024, TextureOptions.DEFAULT); recordBackgroundTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(recordTextureAtlas, activity, "background.png"); highscoreSmallGameTypeTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(recordTextureAtlas, activity, "4x4.png"); highscoreMediumGameTypeTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(recordTextureAtlas, activity, "4x5.png"); highscoreBigGameTypeTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(recordTextureAtlas, activity, "4x6.png"); try { recordTextureAtlas.build(new BlackPawnTextureAtlasBuilder<IBitmapTextureAtlasSource, BitmapTextureAtlas>(0, 0, 0)); recordTextureAtlas.load(); } catch (ITextureAtlasBuilder.TextureAtlasBuilderException e) { Log.e(TAG, "Error during building atlasses"); } } private void loadGameTypeGraphics() { if (gameTypeTextureAtlas != null) { gameTypeTextureAtlas.load(); } BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/gametype/"); gameTypeTextureAtlas = new BuildableBitmapTextureAtlas(activity.getTextureManager(), 1024, 1024, TextureOptions.DEFAULT); backgroundGameTypeTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(gameTypeTextureAtlas, activity, "background.jpg"); smallGameTypeTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(gameTypeTextureAtlas, activity, "4x4.png"); mediumGameTypeTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(gameTypeTextureAtlas, activity, "4x5.png"); bigGameTypeTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(gameTypeTextureAtlas, activity, "4x6.png"); try { gameTypeTextureAtlas.build(new BlackPawnTextureAtlasBuilder<IBitmapTextureAtlasSource, BitmapTextureAtlas>(0, 0, 0)); gameTypeTextureAtlas.load(); } catch (ITextureAtlasBuilder.TextureAtlasBuilderException e) { Log.e(TAG, "Error during building atlasses"); } } }
JavaScript
UTF-8
1,398
3.09375
3
[]
no_license
function mashMap() { var size = 0 ; var entry = new Object(); this.put = function(key, value) { if(!this.has(key)) { size ++; } entry[key] = value; } this.pop = function(key) { if(this.has(key) && (delete entry[key])) { size --; } } this.has = function(key) { return (key in entry); } this.size = function() { return size; } this.parseStr = function() { var str = ""; var mod = ""; for(var key in entry) { var item = entry[key]; str = str + mod + (item.name + "=" + item.amount + "个") ; mod = ","; } return str; } this.parseArrayValue = function() { var str = ""; var mod = ""; for(var key in entry) { var item = entry[key]; str = str + mod + (item.id + "=" + item.amount) ; mod = ","; } return str; } //返回索引组成的字符串,用逗号分隔 //如: key1,key2,key3,... this.getKeysWithComma = function() { var str = ""; var mod = ""; for(var key in entry) { str = str + mod + key; mod = ","; } return str; } //返回值组成的字符串,用逗号分隔 //如: value1,value2,value3,... this.getValuesWithChacter = function(ch) { var str = ""; var mod = ""; for(var key in entry) { str = str + mod + entry[key]; mod = ch; } return str; } }
Swift
UTF-8
1,618
2.78125
3
[ "MIT" ]
permissive
import UIKit import MobileCoreServices public extension String { var localized: String { return NSLocalizedString(self, comment: "") } func localizedFormat(_ args: [CVarArg]) -> String { return String(format: self.localized, locale: Locale.current, arguments: args) } } public extension RawRepresentable where RawValue==String{ var localized: RawValue { return rawValue.localized } func localized(_ args: CVarArg...) -> RawValue { return rawValue.localizedFormat(args) } } public protocol OptionalString { } extension String: OptionalString { } public extension Optional where Wrapped: OptionalString { var isEmptyOrNil: Bool { return ((self as? String) ?? "").isEmpty } var isEmptyOrNilOrOnlySpaces: Bool { return isEmptyOrNil || ((self as? String)?.isOnlySpaces ?? false) } } public extension String { func tag(withClass: CFString) -> String? { return UTTypeCopyPreferredTagWithClass(withClass, self as CFString)?.takeRetainedValue() as String? } func uti(withClass: CFString) -> String? { return UTTypeCreatePreferredIdentifierForTag(withClass, self as CFString, nil)?.takeRetainedValue() as String? } var utiMimeType: String? { return tag(withClass: kUTTagClassMIMEType) } var utiFileExtension: String? { return tag(withClass: kUTTagClassFilenameExtension) } var mimeTypeUTI: String? { return uti(withClass: kUTTagClassMIMEType) } var fileExtensionUTI: String? { return uti(withClass: kUTTagClassFilenameExtension) } var isOnlySpaces: Bool { return trimmingCharacters(in: .whitespacesAndNewlines).count == 0 } }
Python
UTF-8
2,867
3.203125
3
[ "MIT" ]
permissive
""" Author: CaptCorpMURICA Project: 100DaysPython File: module3_day37_mouseKeyboard.py Creation Date: 7/2/2019, 8:17 PM Description: Python Automation Program 9: Mouse/Keyboard Manipulations """ # Anytime a program takes charge of the computer, it's critical that the user has a way to terminate the program. The # `pyautogui` package has a `.PAUSE` variable that can be set with the number of seconds the program will wait after # performing its action. Additionally, there is the `.FAILSAFE` variable that controls the option to force quit the # program by moving the mouse to the upper-left corner of the screen. import pyautogui import subprocess import sys import time pyautogui.PAUSE = 0.5 pyautogui.FAILSAFE = True # Execute the command to open the file and perform a sleep action to ensure the application has opened before # continuing. Depending on the hardware of the machine, the `.sleep()` timer can be extended or contracted. sys_platform = sys.platform if sys_platform == "win32" or sys_platform == "cygwin": subprocess.Popen(["start", ".\\ResumeTemplate.docx"], shell=True) elif sys_platform == "darwin": subprocess.Popen(["open", ".\\ResumeTemplate.docx"]) elif sys_platform == "linux": subprocess.Popen(["see", ".\\ResumeTemplate.docx"]) else: print(f"Unknown operating system: {sys_platform}") time.sleep(10) # After launching the Word file to be converted to a PDF, focus needs to be applied to the application. The application # first sends an `f12` command to try and open the `Save As` dialog box. If `pyautogui` locates the file type field by # using an image of the option and the `.locateOnScreen` function, then the program continues. Otherwise, it locates the # Microsoft Word icon on the taskbar and clicks on it. Once the focus is confirmed, the program selects the file type # field and types `p d f` and then presses enter once to accept the file type and a second time to save. Since the # `.locateOnScreen()` function returns more information than required for the `.click()` function, the `.center()` # function is used to only return the `left` and `top` values. try: pyautogui.press("f12") time.sleep(3) type_location = pyautogui.locateOnScreen(".\\icons\\TypeField.png") if type_location is None: try: word_icon = pyautogui.locateOnScreen(".\\icons\\WordLogo.png") word = pyautogui.center(word_icon) pyautogui.click(word) except TypeError: print("Word not found") raise else: pyautogui.press("f12") time.sleep(3) except TypeError: print("Save not found") raise else: type_loc = pyautogui.center(type_location) pyautogui.click(type_loc) pyautogui.typewrite(["p", "d", "f"]) pyautogui.press(["enter", "enter"])
C++
UTF-8
3,421
2.734375
3
[]
no_license
#ifndef RISA_PIXEL_PROPERTY_HPP_ #define RISA_PIXEL_PROPERTY_HPP_ #include <risa_gl/risa_types.hpp> #include <risa_gl/primitive/selector.hpp> namespace risa_gl { namespace primitive { /** * 何もしないsetter */ class nop_setter { public: template <typename result_itor_t> void operator()(result_itor_t, risa_gl::uint32) const { } }; /** * 実行時定数setter */ class dynamic_constant_setter { private: dynamic_constant_setter(); const risa_gl::uint32 value; public: dynamic_constant_setter(const dynamic_constant_setter& src): value(src.value) {} dynamic_constant_setter(const risa_gl::uint32 value_): value(value_) {} template <typename result_itor_t> void operator()(result_itor_t result, risa_gl::uint32) { result->set_bit_representation(value); } }; /** * set_bit_representationを使って値を設定する */ class bit_setter { public: template <typename result_itor_t> void operator()(result_itor_t result, risa_gl::uint32 value) const { result->set_bit_representation(value); } }; /** * 0値を取得するgetter */ class zero_getter { public: template <typename src_itor_t, typename dest_itor_t> risa_gl::uint32 operator()(src_itor_t, dest_itor_t) const { return 0; } }; /** * 実行時定数値を取得するgetter */ class dynamic_constant_getter { private: dynamic_constant_getter(); const risa_gl::uint32 value; public: dynamic_constant_getter(const dynamic_constant_getter& src): value(src.value) {} dynamic_constant_getter(const risa_gl::uint32 value_): value(value_) {} template <typename src_itor_t, typename dest_itor_t> risa_gl::uint32 operator()(src_itor_t, dest_itor_t) const { return value; } }; /** * selectorを利用して対象をbit_representationメソッドを使って * 値を取得するgetter */ template <typename selector> class bits_getter { public: template <typename src_itor_t, typename dest_itor_t> risa_gl::uint32 operator()(src_itor_t src, dest_itor_t dest) const { return selector()(src, dest)->get_bit_representation(); } }; /** * selectorを利用して対象をbit_representationメソッドを使って * 補値を取得するgetter */ template <typename selector> class invert_getter { public: template <typename src_itor_t, typename dest_itor_t> risa_gl::uint32 operator()(src_itor_t src, dest_itor_t dest) const { return ~selector()(src, dest)->get_bit_representation(); } }; template <typename function_t, typename stub_t> class functional_getter { public: typedef function_t function_type; typedef stub_t stub_type; private: function_type function; stub_type stub; public: functional_getter(const function_type& function_ = function_type(), const stub_type& stub_ = stub_type()): function(function_), stub(stub_) {} template <typename src_itor_t, typename dest_itor_t> risa_gl::uint32 operator()(src_itor_t src, dest_itor_t dest) const { typename src_itor_t::value_type temp; temp.set_bit_representation(stub(src, dest)); return function(temp); } }; } } #endif /* RISA_PIXEL_PROPERTY_HPP_ */
Markdown
UTF-8
2,402
2.859375
3
[]
no_license
### Задача 1 Да се напише рекурсивна функция, която приема като аргументи едномерен масив от цели числа, и размера на масива, и връща като резултат нов масив от онези елементи, които са [Pentagonal numbers](http://en.wikipedia.org/wiki/Pentagonal_number), тоест намират се по формулата Pn=n(3n−1)/2. ### Задача 2 Да се напише булева рекурсивна функция, която приема 2 масива от цели числа и размерите им, и връща дали вторият масив съдържа всички Pentagonal numbers от първия. ###Задача 3 [Шифърът на Цезар](http://en.wikipedia.org/wiki/Caesar_cipher) е прост начин за криптиране, при който криптотекста се получава чрез `shift` на всеки от символите на входния текст с определен `offset`. Да се напишат двойка функции encode и decode, които приемат като аргументи символен низ и цяло число `offset` и криптират или декриптират подаден текст чрез Шифър на Цезар, използвайки зададения `offset`. ###Задача 4 [Run-Length encoding](http://en.wikipedia.org/wiki/Run-length_encoding) е прост начин за компресия на текст, при който последователните срещания на един елемент се заменят с `<брой на срещанията><елемента>`, а в случай че тази замяна би заела повече символи, отколкото оригиналния текст (например, ако имаме само едно срещане на буквата `"а"` и го заменим с `"1а"`, то променения текст би заемал повече памет от изходния) се запазва оригиналния текст. Да се напише функция `lengthEncode`, която компресира низ по зададения метод и връща компресирания низ.