Posts

Showing posts from September, 2018

Flutter boot receiver

Trying to make a practice app using flutter. Is there a way to schedule task when the phone has been rebooted via boot receiver? I've been searching for it but I couldn't find an example where I could call a method from flutter and be called via boot receiver on native android? Thanks

Refactor Java using inheritance between subclass and superclass

I would like to refactor some code using inheritance between my superclass and subclasses. These are my classes: public class Animal { int a; int b; int c; } public class Dog extends Animal { int d; int e; } public class Cat extends Animal { int f; int g; } This is my current code: ArrayList<Animal> listAnimal = new ArrayList(); if (condition) { Dog dog = new Dog(); dog.setA(..); dog.setB(..); dog.setC(..); dog.setD(..); dog.setE(..); listAnimal.add(dog); } else { Cat cat = new Cat(); cat.setA(..); cat.setB(..); cat.setC(..); cat.setF(..); cat.setG(..); listAnimal.add(cat); } I would like refractor the commons attributes. I know this doesn't work. I could use constructor in subclass for create an instance with Animal class in parameter, but it doesn't use inheritance... I would like something like that: Animal animal = new Animal(); animal.setA(..); animal.setB(..); animal.setC(..); if (...

How to use line break argument

I wrote the most simple Hello, World! application: public class Helloworld { public static void main(String[] args) { System.out.println("Hello\nHello"); } } When it runs, the result is: Hello Hello But if I use Hello\nHello as arguments, public class Helloworld { public static void main(String[] args) { System.out.println(args[0]); } } the result is Hello\nHello. How do I get the two-line result? When you define a String as "Hello\nHello" in Java, it contains no '\' character. It is an escape sequence for the line break: "\n" is just one character. When you use this string as an argument to your program, however (so the string is defined outside), "\n" is interpreted as two characters: '\' and 'n'. You have to replace these two characters with the line break, knowing that to match '\' you have to escape it with '\': System.out.println(args[0].replace("\\n", ...

Unable to resolve module `@babel/runtime/helpers/interopRequireDefault`

When creating a new react native project using the standard react-native init MyApp and running react-native run-ios for the first time I'm seeing the following error error: bundling failed: Error: Unable to resolve module `@babel/runtime/helpers/interopRequireDefault` from `/Users/chrisedgington/Development/ReactNative/SixNationsPredictor/index.js`: Module `@babel/runtime/helpers/interopRequireDefault` does not exist in the Haste module map This might be related to https://github.com/facebook/react-native/issues/4968 To resolve try the following: 1. Clear watchman watches: `watchman watch-del-all`. 2. Delete the `node_modules` folder: `rm -rf node_modules && npm install`. 3. Reset Metro Bundler cache: `rm -rf /tmp/metro-bundler-cache-*` or `npm start -- --reset-cache`. 4. Remove haste cache: `rm -rf /tmp/haste-map-react-native-packager-*`. at ModuleResolver.resolveDependency (/Users/chrisedgington/Development/ReactNative/MyApp/node_modules/metro/src/node-haste/...

Multiple assignments in python

I need a clear explanation here. Why does the following code work ? foo1 = foo1[0] = [0] Ok, I know assignments are done left to right. How does python understand foo1 is a list? Btw I know foo1 ends up as [[...]] its first element being itself. Because foo1 = foo1[0] = [0] is equivalent to temp = [0] foo1 = temp foo1[0] = temp it first evaluates expression and then assigns from left to right. Analyzing this line by line you'll get what's going on: - first a list is created in temp - then list temp is assigned to foo1 making it a list (answers your actual question) - 3rd line just makes an assignment of first element to the list itself (thus [[...]] in output) Update 2: changed related question as per @blhsing comment to a more related discussion: Python Multiple Assignment Statements In One Line Python variables know their types based on the type of variable assigned to it. It is a dynamically types language. In your code, the interpreter sees foo1 = foo1[0] = [0] an...

reinterpret_cast bug or UB? [duplicate]

This question already has an answer here: Observing weird behavior with 'auto' and std::minmax 1 answer structured bindings with std::minmax and rvalues 2 answers Consider following code: #include <cstdint> #include <algorithm> std::uintptr_t minPointer(void *first, void *second) { const auto pair = std::minmax( reinterpret_cast<std::uintptr_t>(first), reinterpret_cast<std::uintptr_t>(second) ); return pair.first; } and the assembly generated by GCC8 with -O3 on https://godbolt.org/z/qWJuV_ for minPointer: minPointer(void*, void*): mov rax, QWORD PTR [rsp-8] ret which clearly does not do what is intended by the code creator. Is this code causing some UB or is it GCC(8) bug? This is UB, but not for the reason you might think. The relevant signature o...

std::is_floating_point returns false for float in some cases

In some cases, see one example below, std::is_floating_point is returning false for float. #include <iostream> #include <type_traits> #include <vector> int main() { ::std::cout << typeid(decltype(::std::vector< float >()[::std::vector< float >().size()])).name() << ::std::endl; if (::std::is_floating_point< decltype(::std::vector< float >()[::std::vector< float >().size()]) >::value) { ::std::cout << "floating point" << ::std::endl; } else { ::std::cout << "not floating point" << ::std::endl; } return 0; } Output from GCC f not floating point In this example, one can see that typeid considers ::std::vector< float >()[::std::vector< float >().size()] as a float as it returns the correct name. One can also check that typeid(decltype(::std::vector< float >()[::std::vector< float >().size()])) == typeid(flat) returns...

delete[] with different type undefined behaviour?

I am wondering if this is undefined behavior: #include <stdint.h> int main() { auto* p = new uint8_t[32]; float* c = reinterpret_cast<float*>(p); delete[] c; } In the standard there is If not, the behavior is undefined. In the second alternative (delete array), the value of the operand of delete may be a null pointer value or a pointer value that resulted from a previous array new-expression.79 If not, the behavior is undefined. [ Note: this means that the syntax of the delete-expression must match the type of the object allocated by new, not the syntax of the new-expression. — end note ] So interpreting the somewhat unclear phrase this means that the syntax of the delete-expression must match the type of the object allocated by new, not the syntax of the new-expression I can say the above is Undefined Behavior, correct? Yes, the behaviour is undefined. The pointer passed to delete[] must be the same type as the one you get back from new[]. Note that for del...

Why is it invalid for a union type declared in one function to be used in another function?

When I read ISO/IEC 9899:1999 (see:6.5.2.3), I saw an example like this (emphasis mine) : The following is not a valid fragment (because the union type is not visible within function f): struct t1 { int m; }; struct t2 { int m; }; int f(struct t1 * p1, struct t2 * p2) { if (p1->m < 0) p2->m = -p2->m; return p1->m; } int g() { union { struct t1 s1; struct t2 s2; } u; /* ... */ return f(&u.s1, &u.s2); } I found no errors and warnings when I tested. My question is: Why is this fragment invalid? The example attempts to illustrate the paragraph beforehand1 (emphasis mine): 6.5.2.3 ¶6 One special guarantee is made in order to simplify the use of unions: if a union contains several structures that share a common initial sequence (see below), and if the union object currently contains one of these structures, it is permitted to inspect the common initial part of any of them anywh...

Periodically replacing values in a list

Suppose I have the following list in Python: my_list = [10] * 95 Given n, I want to replace any other m elements with zero in my list, while keeping the next n elements. For example, if n = 3 and m = 2, I want my list to look like: [10, 10, 10, 0, 0, 10, 10, 10 ,0, 0, ..., 10, 10, 10 , 0, 0] If it can't be filled perfectly, as is the case with n = 4 and m = 2, then it's OK if my list looks like this: [10, 10, 10, 10, 0, 0, ..., 10, 10, 10, 10, 0] How should I try to solve this problem? my_list = [10] * 95 n = 3 m = 2 for i in range(m): my_list[n+i::m+n] = [0] * len(my_list[n+i::m+n]) This just needs m assignments to do the job (and m probably is small). If you really just have two possible values (e. g. 10 and 0), you can do it even simpler: my_list = [ 10 if i % (n+m) < n else 0 for i in range(95) ] But that iterates in Python over the whole range of 95, so probably is not very fast. A bit more complex but probably more efficient (especially for huge lists and larg...

Could not find method create() for arguments - Crashlytics issue

Could not find method create() for arguments [crashlyticsStoreDeobsDebug, class com.crashlytics.tools.gradle.tasks.StoreMappingFileTask, com.android.build.gradle.internal.scope.BuildArtifactsHolder$FinalBuildableArtifact@2ac9ac29] on task set of type org.gradle.api.internal.tasks.DefaultTaskContainer. Project was in working state but since today build is failing with above error. Android Studio 3.2 Preview. It looks like Fabric released a new version thats breaks the build for some apps. If you have the line io.fabric.tools:gradle:1.+ (which is recommended by Fabric, but not ideal) you will automatically use the new version. In the meantime you can replace 1.+ with the latest "stable" version which is 1.25.4. io.fabric.tools:gradle:1.25.4 For me, the problem appeared when I updated to AS 3.2-RC02 which requires the Android plugin 3.2.0-rc02. So I had to roll back to AS 3.1.4 which is the current stable version so I could downgrade my version of the Android plugin. I...

Error in Kotlin but using only Java - Class kotlin.reflect.jvm.internal.FunctionCaller$FieldSetter

I get this error when try to run my Android application and I am not using Kotlin at all, application is written in Java... Class kotlin.reflect.jvm.internal.FunctionCaller$FieldSetter can not access a member of class com.android.build.gradle.tasks.ManifestProcessorTask with modifiers "private" I solved this way. 1. Delete all the .gradle folders 2. Invalidate caches / restart everything is OK for me. Settings -> Languages & Frameworks -> Kotlin Updates -> Update channel -> Early Access Preview/Stable -> Update -> Restart Or: Tools -> Kotlin -> Configure Kotlin Plugin Update -> Update channel -> Early Access Preview/Stable -> Update -> Restart Delete and rebuild is working for me as well Install the latest Gradle version (1.10.2 at the moment of writing). Install the latest version of Kotlin plugin: go to Settings [Ctrl]+[Alt]+[S] > Languages & Frameworks > Kotlin Updates > select Update channel > cli...

Round a decimal to the first decimal position that is not zero

I want to shorten a number to the first significant digit that is not 0. The digits behind should be rounded. Examples: 0.001 -> 0.001 0.00367 -> 0.004 0.00337 -> 0.003 0.000000564 -> 0.0000006 0.00000432907543029 -> 0.000004 Currently I have the following procedure: if (value < (decimal) 0.01) { value = Math.Round(value, 4); } Note: numbers will always be positive the number of significant digits will always be 1 values larger 0.01 will always be rounded to two decimal places, hence the if < 0.01 As you can see from the examples above, a rounding to 4 Decimal places might not be enough and the value might vary greatly. I would declare precision variable and use a loop iteration multiplies that variable by 10 with the original value it didn't hit, that precision will add 1. then use precision variable be Math.Round second parameter. static decimal RoundFirstSignificantDigit(decimal input) { int precision = 0; var val = input; while (Math.A...

Is std::string guaranteed not to give back memory spontaneously?

Is it guaranteed by the standard that std::string will not give back allocated memory spontaneously if reassigned from a string of a smaller size? In other words: std::string str = "Some quite long string, which needs a lot of memory"; str = ""; str = "A new quite long but smaller string"; // Guaranteed to not result in a heap allocation? I ask because i'm depending on this to avoid heap fragmentation. No guarantee whatsoever. [string.cons]/36 defines assigning a const char* to an std::string in term of a move-assignment, whose definition is: [string.cons]/32 basic_string& operator=(basic_string&& str) noexcept(/*...*/) Effects: Move assigns as a sequence container, except that iterators, pointers and references may be invalidated. This shows that the Committee let the implementation choose freely between an invalidating operation and a more conservative one. CPP reference states that assignment to a pointer-to-char Repla...

Combining every 2 string to 1 string

I have a list a list = ['247400015203223811', 'DPF', '247400015203223813', 'ZPF'] I want to get a list of strings like ["247400015203223811, DPF", "247400015203223813, ZPF"] combining every 2 strings to 1 string I tried like list2 = [] list = ['247400015203223811', 'DPF', '247400015203223813', 'ZPF'] for i in range(0, len(list), 2): list2.append(list[i] + list[i]) is this even possible? You almost had it, you can use this list comprehension: mylist = ['247400015203223811', 'DPF', '247400015203223813', 'ZPF'] mylist2 = [mylist[i]+', '+mylist[i+1]for i in range(0,len(mylist),2)] >>> mylist2 ['247400015203223811, DPF', '247400015203223813, ZPF'] Make sure you don't use the keyword list as a variable name, because it masks the python built-in type (I changed it to mylist instead) Of course is possible, and you...

C++ greater than or equal to operator

In C++, for the operator greater than or equal to (">="), is it enough to have the operators equal ("=") and greater (">") overloaded to have functionality for the greater than or equal to (">=")? Or do I need to overload the operator (">=") to have functionality for it? Using an obvious notation, ">" || "==" is actually an over-requirement for ">=". Although note that for all the relational operators, you only actually need "<", since equivalence is established if a < b and b < a are both false. In fact this is one of the concepts used in ordered C++ standard library containers. is it enough to have the operators equal ("=") Equal operator in c++ is == OR do I need to overload the operator (">=") to have functionality for it? It depends what you mean by functionality. If you mean that if you define operator== and operator> will co...

Call function without optional arguments if they are None

There's a function which takes optional arguments. def alpha(p1="foo", p2="bar"): print('{0},{1}'.format(p1, p2)) Let me iterate over what happens when we use that function in different ways: >>> alpha() foo,bar >>> alpha("FOO") FOO,bar >>> alpha(p2="BAR") foo,BAR >>> alpha(p1="FOO", p2=None) FOO,None Now consider the case where I want to call it like alpha("FOO", myp2) and myp2 will either contain a value to be passed, or be None. But even though the function handles p2=None, I want it to use its default value "bar" instead. Maybe that's worded confusingly, so let me reword that: If myp2 is None, call alpha("FOO"). Else, call alpha("FOO", myp2). The distinction is relevant because alpha("FOO", None) has a different result than alpha("FOO"). How can I concisely (but readably) make this distinction? One possibility ...

How to find average value of a list in python [duplicate]

This question already has an answer here: number of values in a list greater than a certain number 6 answers I want to return a function which gives the average of all the marks which are 50 or more. When I run my code, it always returns an empty list. Here is what I have tried: def get_pass_average(marks): average = [] for count in marks: if count >= 50: average = sum(count) / len(count) return round(average,2) def test_get_pass_average(): list1 = [50, 83, 26, 65, 92, 29, 77, 64] print('%.2f' % (get_pass_average(list1))) Please helps me to figure out the problems in my code, and the output should be 71.83. Many thanks. In addition to U9-Forward's answer, one using filter and mean: from statistics import mean list1 = [50, 83, 26, 65, 92, 29, 77, 64] average = mean(filter((50).__le__, list1)) print('%.2f' % average) ...

Null coalescing operator IList, Array, Enumerable.Empty in foreach

In this question I found the following: int[] array = null; foreach (int i in array ?? Enumerable.Empty<int>()) { System.Console.WriteLine(string.Format("{0}", i)); } and int[] returnArray = Do.Something() ?? new int[] {}; and ... ?? new int[0] In a NotifyCollectionChangedEventHandler I wanted to apply the Enumerable.Empty like so: foreach (DrawingPoint drawingPoint in e.OldItems ?? Enumerable.Empty<DrawingPoint>()) this.RemovePointMarker(drawingPoint); Note: OldItems is of the type IList And it gives me: Operator '??' cannot be applied to operands of type 'System.Collections.IList' and System.Collections.Generic.IEnumerable<DrawingPoint> However foreach (DrawingPoint drawingPoint in e.OldItems ?? new int[0]) and foreach (DrawingPoint drawingPoint in e.OldItems ?? new int[] {}) works just fine. Why is that? Why does IList ?? T[] work but IList ?? IEnumerable<T> doesn't? When using this expression: a ?? b Then b e...

Java method can't be applied with Lambda expression

I've watched and read https://caveofprogramming.com/java/whats-new-in-java-8-lambda-expressions.html and I follow the same pattern I did for runner object which works fine. Runner runner = new Runner(); runner.run(() -> System.out.println("Print from Lambda expression")); Then, I try to create a simple interface and class to apply what I learned. I just want to replace the anonymous class with a lambda expression. My understanding is a lambda expression is a shorter code for the anonymous class and improve readability. So, I tried to initiate another instance called eucalyptus1 and try to @Override the grow() method, but my IDE error message said: grow() in com.smith.Eucalyptus cannot be applied to (lambda expression) Could anyone point me out what I misunderstand here? The code is below: // a simple interface interface Plant { public void grow(); } // apply interface to class class Eucalyptus implements Plant { @Override public void grow() { Syst...

Destructor of typedef alias

#include <iostream> struct A { ~A(); }; A::~A() { std::cout << "Destructor was called!" << std::endl; } typedef A AB; int main() { AB x; x.AB::~AB(); // Why does this work? x.AB::~A(); } The output of the above program is: Destructor was called! Destructor was called! Destructor was called! I assume the first two lines belonging to user destructor calls, while the third line is due to the destructor being called when exiting the scope of main function. From my understanding a typedef is an alias for a type. In this case AB is an alias for A. Why does this apply for the name of the destructor too? A reference to the language specification is very much appreciated. Edit: This was compiled using Apple LLVM version 9.1.0 (clang-902.0.39.1) on macOS High Sierra Version 10.13.3. Why does this apply for the name of the destructor too? Because standard says: [class.dtor] In an explicit destructor call, the destructor is specified by a ~ ...

Two threads executing synchronized block simultaneously

Below is the code where a Thread enters a synchronized block, waits for 5seconds and then exits. I have started two Thread instances simultaneously. The expectation was one of the threads will own the lock on the synchronized object & the other will wait. After 5 seconds, when the lock owner exits, the waiting thread will execute. But, in actual, both the threads are executing the synchronized block simultaneously and also exiting at the same time. Expected Output: Thread-X <timeX> received the lock. Thread-X <timeX+5s> exiting... Thread-Y <timeY> received the lock. Thread-Y <timeY+5s> exiting... Actual Output: Thread-X <time> received the lock. Thread-Y <time> received the lock. Thread-X <time+5s> exiting... Thread-Y <time+5s> exiting... Any explanation of the above behavior will be really helpful. Am I missing something here? import java.text.SimpleDateFormat; import java.util.Date; public class Test2 { public static void main(S...

Detect differences between two strings

I have 2 strings string a = "foo bar"; string b = "bar foo"; and I want to detect the changes from a to b. What characters do I have to change, to get from a to b? I think there must be a iteration over each character and detect if it was added, removed or remained equal. So this is my exprected result 'f' Remove 'o' Remove 'o' Remove ' ' Remove 'b' Equal 'a' Equal 'r' Equal ' ' Add 'f' Add 'o' Add 'o' Add class and enum for the result: public enum Operation { Add,Equal,Remove }; public class Difference { public Operation op { get; set; } public char c { get; set; } } Here is my solution but the "Remove" case is not clear to me how the code has to look like public static List<Difference> CalculateDifferences(string left, string right) { int count = 0; List<Difference> result = new List<Difference>(); foreach (char ch in left) {...