text:
Q: Tensorflow Lite and android Kotlin is unable to open .tflite I am trying to integrate .tflite with kotlin mobile application but this is giving me the following error.
I have tried multiple suggestions on internet but didnot work.
here is my error:
2022-06-09 20:01:26.489 23351-26611/com.example.miniproject E/ModelUtils: Failed to open model file
java.io.FileNotFoundException: detect.tflite: open failed: ENOENT (No such file or directory)
    at libcore.io.IoBridge.open(IoBridge.java:492)
    at java.io.FileInputStream.<init>(FileInputStream.java:160)
    at com.google.mlkit.common.internal.model.ModelUtils.getModelLoggingInfo(com.google.mlkit:common@@17.1.0:24)
    at com.google.mlkit.vision.objects.custom.internal.zzh.zzf(Unknown Source:10)
    at com.google.mlkit.vision.objects.custom.internal.zzg.tryLoad(com.google.mlkit:object-detection-custom@@16.3.0:1)
    at com.google.mlkit.common.sdkinternal.model.CustomModelLoader.load(com.google.mlkit:common@@17.1.0:3)
    at com.google.mlkit.vision.objects.custom.internal.zzh.load(com.google.mlkit:object-detection-custom@@16.3.0:2)
    at com.google.mlkit.common.sdkinternal.ModelResource.zza(Unknown Source:18)
    at com.google.mlkit.common.sdkinternal.zzn.run(Unknown Source:10)
    at com.google.mlkit.common.sdkinternal.zzp.run(com.google.mlkit:common@@17.1.0:2)
    at com.google.mlkit.common.sdkinternal.MlKitThreadPool.zze(com.google.mlkit:common@@17.1.0:4)
    at com.google.mlkit.common.sdkinternal.MlKitThreadPool.zzc(Unknown Source:8)
    at com.google.mlkit.common.sdkinternal.zzj.run(Unknown Source:2)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
    at com.google.mlkit.common.sdkinternal.MlKitThreadPool.zzd(Unknown Source:10)
    at com.google.mlkit.common.sdkinternal.zzk.run(Unknown Source:2)
    at java.lang.Thread.run(Thread.java:923)
 Caused by: android.system.ErrnoException: open failed: ENOENT (No such file or directory)
    at libcore.io.Linux.open(Native Method)
    at libcore.io.ForwardingOs.open(ForwardingOs.java:166)
    at libcore.io.BlockGuardOs.open(BlockGuardOs.java:254)
    at libcore.io.ForwardingOs.open(ForwardingOs.java:166)
    at android.app.ActivityThread$AndroidOs.open(ActivityThread.java:8514)
    at libcore.io.IoBridge.open(IoBridge.java:478)
    at java.io.FileInputStream.<init>(FileInputStream.java:160)
    at com.google.mlkit.common.internal.model.ModelUtils.getModelLoggingInfo(com.google.mlkit:common@@17.1.0:24)
    at com.google.mlkit.vision.objects.custom.internal.zzh.zzf(Unknown Source:10)
    at com.google.mlkit.vision.objects.custom.internal.zzg.tryLoad(com.google.mlkit:object-detection-custom@@16.3.0:1)
    at com.google.mlkit.common.sdkinternal.model.CustomModelLoader.load(com.google.mlkit:common@@17.1.0:3)
    at com.google.mlkit.vision.objects.custom.internal.zzh.load(com.google.mlkit:object-detection-custom@@16.3.0:2)
    at com.google.mlkit.common.sdkinternal.ModelResource.zza(Unknown Source:18)
    at com.google.mlkit.common.sdkinternal.zzn.run(Unknown Source:10)
    at com.google.mlkit.common.sdkinternal.zzp.run(com.google.mlkit:common@@17.1.0:2)
    at com.google.mlkit.common.sdkinternal.MlKitThreadPool.zze(com.google.mlkit:common@@17.1.0:4)
    at com.google.mlkit.common.sdkinternal.MlKitThreadPool.zzc(Unknown Source:8)
    at com.google.mlkit.common.sdkinternal.zzj.run(Unknown Source:2)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
    at com.google.mlkit.common.sdkinternal.MlKitThreadPool.zzd(Unknown Source:10)
    at com.google.mlkit.common.sdkinternal.zzk.run(Unknown Source:2)
    at java.lang.Thread.run(Thread.java:923)

My detect.tflite file is in assets folder in the src/main.
Here is my MainActivity.kt
class MainActivity : AppCompatActivity() {

private lateinit var objectDetector: ObjectDetector
private lateinit var binding: ActivityMainBinding
private lateinit var cameraProviderFuture: ListenableFuture<ProcessCameraProvider>

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    binding = DataBindingUtil.setContentView(this,R.layout.activity_main)
    cameraProviderFuture = ProcessCameraProvider.getInstance(this)

    cameraProviderFuture.addListener({
        val  cameraProvider = cameraProviderFuture.get()
        bindPreview(cameraProvider = cameraProvider)

    }, ContextCompat.getMainExecutor(this))
    val localModel = LocalModel.Builder()
        .setAbsoluteFilePath("detect.tflite")
        .build()

    val customObjectDetectorOptions = CustomObjectDetectorOptions.Builder(localModel)
        .setDetectorMode(CustomObjectDetectorOptions.STREAM_MODE)
        .enableClassification()
        .setClassificationConfidenceThreshold(0.5f)
        .setMaxPerObjectLabelCount(3)
        .build()

    objectDetector = ObjectDetection.getClient(customObjectDetectorOptions)

}

@SuppressLint("UnsafeOptInUsageError")
private fun bindPreview(cameraProvider: ProcessCameraProvider)
{
    val preview = Preview.Builder().build()
    val cameraSelector = CameraSelector.Builder()
        .requireLensFacing(CameraSelector.LENS_FACING_BACK)
        .build()
    preview.setSurfaceProvider(binding.previewView.surfaceProvider)

    val imageAnalysis = ImageAnalysis.Builder()
        .setTargetResolution(Size(1280,720))
        .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
        .build()

    imageAnalysis.setAnalyzer(ContextCompat.getMainExecutor(this),{ imageProxy ->
        val rotationDegrees= imageProxy.imageInfo.rotationDegrees
        val image = imageProxy.image
        if(image != null){
            val processImage = InputImage.fromMediaImage(image, rotationDegrees)
            objectDetector
                .process(processImage)
                .addOnSuccessListener { objects ->

                    for(i in objects){
                        if(binding.parentLayout.childCount >1) binding.parentLayout.removeViewAt(1)
                        val element = Draw(context=this,
                            rect =  i.boundingBox,
                            text = i.labels.firstOrNull()?.text ?: "Undefined")
                        binding.parentLayout.addView(element)
                    }
                    imageProxy.close()
                }.addOnFailureListener{
                    Log.v("MainActivity","error")
                    imageProxy.close()
                }
        }
    })
    cameraProvider.bindToLifecycle(this as LifecycleOwner,cameraSelector,imageAnalysis,preview)

}

}
This is my layout page:
<?xml version="1.0" encoding="utf-8"?>
<layout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".MainActivity">
<RelativeLayout
    android:id="@+id/parentLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <androidx.camera.view.PreviewView
        android:id="@+id/previewView"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </androidx.camera.view.PreviewView>
</RelativeLayout>

I have tried to add the following in my code but it still doesn't work.
 <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
    android:requestLegacyExternalStorage="true">

I am  using the following MlKit:
implementation 'com.google.mlkit:object-detection-custom:16.3.0'

A:
There is no "absolute path of the assets folder in [your] app". Assets are stored in the APK file.
https://stackoverflow.com/a/5030465/17737901

Since your model is in the asset folder, the
setAbsoluteFilePath("detect.tflite")

in your localModel declaration should be
setAssetFilePath("detect.tflite")

instead.


text:
Q: Are secondary indices always a bad idea in Cassandra even if I specify them in conjunction with the partitioning key in all my queries? I know that secondary indices in Cassandra are generally a bad idea because the index is stored locally in each node i.e. not distributed across the cluster which may result in a query scanning a huge number of nodes. However, I don't understand why they are still a bad idea if I always specify the partition key in my queries and only use the secondary index as a final filter. I've read that they don't scale with large amounts of data even if I specify the partition key. Is this true? and if it's then why?

A: In general secondary indexes are bad idea, not only for the distributed part, but also for the index size and the number of distinct value, so if you have a field with high or low cardinality,you will be spending time on scanning many rows or many columns.
Also you can have other issue while dealing with tombstones ...
To answer your question, secondary index in Cassandra doesn't scale that good, but if you use a partition key and by it you tell Cassandra which node have the data, it perform really better !
you can find more details here in section F :
https://www.datastax.com/blog/2016/04/cassandra-native-secondary-index-deep-dive
I hope this helps !

A: These guys have a nice write-up on the performance impacts of secondary indexes:
https://pantheon.io/blog/cassandra-scale-problem-secondary-indexes
The main impact (from the post) is that secondary indexes are local to each node, so to
 satisfy a query by indexed value, each node has to query its own records to build the
 final result set (as opposed to a primary key query where it is known exactly which node
 needs to be queried). So there's not just an impact on writes, but on read performance as
 well.

A: Cassandra on a ring of five machines, with a primary index of user IDs and a secondary index of user emails. If you were to query for a user by their ID or by their primary indexed key any machine in the ring would know which machine has a record of that user. One query, one read from disk. However to query a user by their email or their secondary indexed value each machine has to query its own record of users. One query, five reads from disk. By either scaling the number of users system wide, or by scaling the number of machines in the ring, the noise to signal-to-ratio increases and the overall efficiency of reading drops. In some cases to the point of timing out also.
Please refer below link for good explanation on secondary index.
https://dzone.com/articles/cassandra-scale-problem

redpajama_set_name: RedPajamaStackExchange


text:
Q: Setting variable to NULL after free In my company there is a coding rule that says, after freeing any memory, reset the variable to NULL. For example ...
void some_func ()
{
    int *nPtr;

    nPtr = malloc (100);

    free (nPtr);
    nPtr = NULL;

    return;
}

I feel that, in cases like the code shown above, setting to NULL does not have any meaning. Or am I missing something?
If there is no meaning in such cases, I am going to take it up with the "quality team" to remove this coding rule. Please advice.

A: Setting the pointer to the free'd memory means that any attempt to access that memory through the pointer will immediately crash, instead of causing undefined behavior. It makes it much easier to determine where things went wrong.
I can see your argument: since nPtr is going out of scope right after nPtr = NULL, there doesn't seem to be a reason to set it to NULL. However, in the case of a struct member or somewhere else where the pointer is not immediately going out of scope, it makes more sense. It's not immediately apparent whether or not that pointer will be used again by code that shouldn't be using it.
It's likely the rule is stated without making a distinction between these two cases, because it's much more difficult to automatically enforce the rule, let alone for the developers to follow it. It doesn't hurt to set pointers to NULL after every free, but it has the potential of pointing out big problems.

A: If you reach pointer that has been free()d, it might break or not. That memory might be reallocated to another part of your program and then you get memory corruption,
If you set the pointer to NULL, then if you access it, the program always crashes with a segfault. No more ,,sometimes it works'', no more ,,crashes in unpredictible way''. It's way easier to debug.

A: the most common bug in c is the double free. Basically you do something like that
free(foobar);
/* lot of code */
free(foobar);

and it end up pretty bad, the OS try to free some already freed memory and generally it segfault. So the good practice is to set to NULL, so you can make test and check if you really need to free this memory
if(foobar != null){
  free(foobar);
}

also to be noted that free(NULL) won't do anything so you don't have to write the if statement. I am not really an OS guru but I am pretty even now most OSes would crash on double free.
That's also a main reason why all languages with garbage collection (Java, dotnet) was so proud of not having this problem and also not having to leave to developers the memory management as a whole.

A: The idea behind this, is to stop accidental reuse of the freed pointer.

A: Recently I come across the same question after I was looking for the answer. I reached this conclusion:
It is best practice, and one must follow this to make it portable on all (embedded) systems.
free() is a library function, which varies as one changes the platform, so you should not expect that after passing pointer to this function and after freeing memory, this pointer will be set to NULL. This may not be the case for some library implemented for the platform.
so always go for
free(ptr);
ptr = NULL;

A: This (can) actually be important. Although you free the memory, a later part of the program could allocate something new that happens to land in the space. Your old pointer would now point to a valid chunk of memory. It is then possible that someone would use the pointer, resulting in invalid program state.
If you NULL out the pointer, then any attempt to use it is going to dereference 0x0 and crash right there, which is easy to debug. Random pointers pointing to random memory is hard to debug. It's obviously not necessary but then that's why it's in a best practices document.

A: From the ANSI C standard:
void free(void *ptr);

The free function causes the space
  pointed to by ptr to be deallocated,
  that is, made available for further
  allocation.  If ptr is a null pointer,
  no action occurs.  Otherwise, if the
  argument does not match a pointer
  earlier returned by the calloc ,
  malloc , or realloc function, or if
  the space has been deallocated by a
  call to free or realloc , the behavior
  is undefined.

"the undefined behavior" is almost always a program crash. So as to avoid this it is safe to reset the pointer to NULL. free() itself cannot do this as it is passed only a pointer, not a pointer to a pointer. You can also write a safer version of free() that NULLs the pointer:
void safe_free(void** ptr)
{
  free(*ptr);
  *ptr = NULL;
}

A: Most of the responses have focused on preventing a double free, but setting the pointer to NULL has another benefit.  Once you free a pointer, that memory is available to be reallocated by another call to malloc.  If you still have the original pointer around you might end up with a bug where you attempt to use the pointer after free and corrupt some other variable, and then your program enters an unknown state and all kinds of bad things can happen (crash if you're lucky, data corruption if you're unlucky).  If you had set the pointer to NULL after free, any attempt to read/write through that pointer later would result in a segfault, which is generally preferable to random memory corruption.
For both reasons, it can be a good idea to set the pointer to NULL after free().  It's not always necessary, though.  For example, if the pointer variable goes out of scope immediately after free(), there's not much reason to set it to NULL.

A: Setting a pointer to NULL after free is a dubious practice that is often popularized as a "good programming" rule on a patently false premise. It is one of those fake truths that belong to the "sounds right" category but in reality achieve absolutely nothing useful (and sometimes leads to negative consequences).
Allegedly, setting a pointer to NULL after free is supposed to prevent the dreaded "double free" problem when the same pointer value is passed to free more than once. In reality though, in 9 cases out of 10 the real "double free" problem occurs when different pointer objects holding the same pointer value are used as arguments for free. Needless to say, setting a pointer to NULL after free achieves absolutely nothing to prevent the problem in such cases.
Of course, it is possible to run into "double free" problem when using the same pointer object as an argument to free. However, in reality situations like that normally indicate a problem with the general logical structure of the code, not a mere accidental "double free". A proper way to deal with the problem in such cases is to review and rethink the structure of the code in order to avoid the situation when the same pointer is passed to free more than once. In such cases setting the pointer to NULL and considering the problem "fixed" is nothing more than an attempt to sweep the problem under the carpet. It simply won't work in general case, because the problem with the code structure will always find another way to manifest itself.
Finally, if your code is specifically designed to rely on the pointer value being NULL or not NULL, it is perfectly fine to set the pointer value to NULL after free. But as a general "good practice" rule (as in "always set your pointer to NULL after free") it is, once again, a well-known and pretty useless fake, often followed by some for purely religious, voodoo-like reasons.

A: I find this to be little help as in my experience when people access a freed memory allocation it's almost always because they have another pointer to it somewhere. And then it conflicts with another personal coding standard which is "Avoid useless clutter", so I don't do it as I think it rarely helps and makes the code slightly less readable.
However - I won't set the variable to null if the pointer isn't supposed to be used again, but often the higher level design gives me a reason to set it to null anyway. For example if the pointer is a member of a class and I've deleted what it points to then the "contract" if you like of the class is that that member will point to something valid at any time so it must be set to null for that reason. A small distinction but I think an important one.
In c++ it's important to always be thinking who owns this data when you allocate some memory (unless you are using smart pointers but even then some thought is required). And this process tends to lead to pointers generally being a member of some class and generally you want a class to be in a valid state at all times, and the easiest way to do that is to set the member variable to NULL to indicate it points to nothing now.
A common pattern is to set all the member pointers to NULL in the constructor and have the destructor call delete on any pointers to data that your design says that class owns. Clearly in this case you have to set the pointer to NULL when you delete something to indicate that you don't own any data before.
So to summarise, yes i often set the pointer to NULL after deleting something, but it's as part of a larger design and thoughts on who owns the data rather than due to blindly following a coding standard rule. I wouldn't do so in your example as I think there is no benefit to doing so and it adds "clutter" which in my experience is just as responsible for bugs and bad code as this kind of thing.

A: It is always advisable to declare a pointer variable with NULL such as,
int *ptr = NULL;

Let's say, ptr is pointing to 0x1000 memory address.
After using free(ptr), it's always advisable to nullify the pointer variable by declaring again to NULL.
e.g.:
free(ptr);
ptr = NULL;

If not re-declared to NULL, the pointer variable still keeps on pointing to the same address (0x1000), this pointer variable is called a dangling pointer.
If you define another pointer variable (let's say, q) and dynamically allocate address to the new pointer, there is a chance of taking the same address (0x1000) by new pointer variable. If in case, you use the same pointer (ptr) and update the value at the address pointed by the same pointer (ptr), then the program will end up writing a value to the place where q is pointing (since p and q are pointing to the same address (0x1000)).
e.g.
*ptr = 20; //Points to 0x1000
free(ptr);
int *q = (int *)malloc(sizeof(int) * 2); //Points to 0x1000
*ptr = 30; //Since ptr and q are pointing to the same address, so the value of the address to which q is pointing would also change.

A: Setting unused pointers to NULL is a defensive style, protecting against dangling pointer bugs. If a dangling pointer is accessed after it is freed, you may read or overwrite random memory. If a null pointer is accessed, you get an immediate crash on most systems, telling you right away what the error is.
For local variables, it may be a little bit pointless if it is "obvious" that the pointer isn't accessed anymore after being freed, so this style is more appropriate for member data and global variables. Even for local variables, it may be a good approach if the function continues after the memory is released.
To complete the style, you should also initialize pointers to NULL before they get assigned a true pointer value.

A: This rule is useful when you're trying to avoid the following scenarios:
1) You have a really long function with complicated logic and memory management and you don't want to accidentally reuse the pointer to deleted memory later in the function.
2) The pointer is a member variable of a class that has fairly complex behavior and you don't want to accidentally reuse the pointer to deleted memory in other functions.
In your scenario, it doesn't make a whole lot of sense, but if the function were to get longer, it might matter.
You may argue that setting it to NULL may actually mask logic errors later on, or in the case where you assume it is valid, you still crash on NULL, so it doesn't matter.
In general, I would advise you to set it to NULL when you think it is a good idea, and not bother when you think it isn't worth it.  Focus instead on writing short functions and well designed classes.

A: This might be more an argument to initialize all pointers to NULL, but something like this can be a very sneaky bug:
void other_func() {
  int *p; // forgot to initialize
  // some unrelated mallocs and stuff
  // ...
  if (p) {
    *p = 1; // hm...
  }
}

void caller() {
  some_func();
  other_func();
}

p ends up in the same place on the stack as the former nPtr, so it might still contain a seemingly valid pointer. Assigning to *p might overwrite all kinds of unrelated things and lead to ugly bugs. Especially if the compiler initializes local variables with zero in debug mode but doesn't once optimizations are turned on. So the debug builds don't show any signs of the bug while release builds blow up randomly...

A: Set the pointer that has just been freed to NULL is not mandatory but a good practice. In this way , you can avoid 1) using a freed pointed 2)free it towice

A: There are two reasons:
Avoid crashes when double-freeing
Written by RageZ in a duplicate question.

The most common bug in c is the double
  free. Basically you do something like
  that
free(foobar);
/* lot of code */
free(foobar);

and it end up pretty bad, the OS try
  to free some already freed memory and
  generally it segfault. So the good
  practice is to set to NULL, so you
  can make test and check if you really
  need to free this memory
if(foobar != NULL){
  free(foobar);
}

also to be noted that free(NULL)
  won't do anything so you don't have to
  write the if statement. I am not
  really an OS guru but I am pretty even
  now most OSes would crash on double
  free.
That's also a main reason why all
  languages with garbage collection
  (Java, dotnet) was so proud of not
  having this problem and also not
  having to leave to developer the
  memory management as a whole.

Avoid using already freed pointers
Written by Martin v. Löwis in a another answer.

Setting unused pointers to NULL is a
  defensive style, protecting against
  dangling pointer bugs. If a dangling
  pointer is accessed after it is freed,
  you may read or overwrite random
  memory. If a null pointer is accessed,
  you get an immediate crash on most
  systems, telling you right away what
  the error is.
For local variables, it may be a
  little bit pointless if it is
  "obvious" that the pointer isn't
  accessed anymore after being freed, so
  this style is more appropriate for
  member data and global variables. Even
  for local variables, it may be a good
  approach if the function continues
  after the memory is released.
To complete the style, you should also
  initialize pointers to NULL before
  they get assigned a true pointer
  value.

A: This is considered good practice to avoid overwriting memory. In the above function, it is unnecessary, but oftentimes when it is done it can find application errors.
Try something like this instead:
#if DEBUG_VERSION
void myfree(void **ptr)
{
    free(*ptr);
    *ptr = NULL;
}
#else
#define myfree(p) do { void ** p_tmp = (p); free(*(p_tmp)); *(p_tmp) = NULL; } while (0)
#endif

The DEBUG_VERSION lets you profile frees in debugging code, but both are functionally the same.
Edit: Added do ... while as suggested below, thanks.

A: To add to what other have said, one good method of pointer usage is to always check whether it is a valid pointer or not. Something like:

if(ptr)
   ptr->CallSomeMethod();

Explicitly marking the pointer as NULL after freeing it allows for this kind of usage in C/C++.

A: Settings a pointer to NULL is to protect agains so-called double-free - a situation when free() is called more than once for the same address without reallocating the block at that address.
Double-free leads to undefined behaviour - usually heap corruption or immediately crashing the program. Calling free() for a NULL pointer does nothing and is therefore guaranteed to be safe.
So the best practice unless you now for sure that the pointer leaves scope immediately or very soon after free() is to set that pointer to NULL so that even if free() is called again it is now called for a NULL pointer and undefined behaviour is evaded.

A: The idea is that if you try to dereference the no-longer-valid pointer after freeing it, you want to fail hard (segfault) rather than silently and mysteriously.
But... be careful. Not all systems cause a segfault if you dereference NULL. On (at least some versions of) AIX, *(int *)0 == 0, and Solaris has optional compatibility with this AIX "feature."

A: To the original question:
Setting the pointer to NULL directly after freeing the contents is a complete waste of time, provided the code meets all requirements, is fully debugged and will never be modified again. On the other hand, defensively NULLing a pointer that has been freed can be quite useful when someone thoughtlessly adds a new block of code beneath the free(), when the design of the original module isn't correct, and in the case of it-compiles-but-doesn't-do-what-I-want bugs.

In any system, there is an unobtainable goal of making it easiest to the right thing, and the irreducible cost of inaccurate measurements. In C we're offered a set of very sharp, very strong tools, which can create many things in the hands of a skilled worker, and inflict all sorts of metaphoric injuries when handled improperly. Some are hard to understand or use correctly. And people, being naturally risk averse, do irrational things like checking a pointer for NULL value before calling free with it…

The measurement problem is that whenever you attempt to divide good from less good, the more complex the case, the more likely you get an ambiguous measurement. If the goal is do keep only good practices, then some ambiguous ones get tossed out with the actually not good. IF your goal is to eliminate the not good, then the ambiguities may stay with the good. The two goals, keep only good or eliminate clearly bad, would seem to be diametrically opposed, but there is usually a third group that's neither one nor the other, some of both.

Before you make a case with the quality department, try looking through the bug data base to see how often, if ever, invalid pointer values caused problems that had to be written down. If you want to make real difference, identify the most common problem in your production code and propose three ways to prevent it

A: As you have a quality assurance team in place, let me add a minor point about QA. Some automated QA tools for C will flag assignments to freed pointers as "useless assignment to ptr". For example PC-lint/FlexeLint from Gimpel Software says
tst.c  8  Warning 438: Last value assigned to variable 'nPtr' (defined at line 5) not used
There are ways to selectively suppress messages, so you can still satisfy both QA requirements, should your team decide so.

A: Long story short: You do not want to accidentally (by mistake) access the address that you have freed. Because, when you free the address, you allow that address in the heap to be allocated to some other application.
However, if you do not set the pointer to NULL, and by mistake try to de-reference the pointer, or change the value of that address; YOU CAN STILL DO IT. BUT NOT SOMETHING THAT YOU WOULD LOGICALLY WANT TO DO.
Why can I still access the memory location that I have freed? Because: You may have free the memory, but the pointer variable still had information about the heap memory address. So, as a defensive strategy, please set it to NULL.


text:
Q: C# Increment array values by 1 using 2 threads? If you have the following problem to solve, how would you do it?
The goal is to create an array of 1000 integer values, initialized to 0 and then increment all the values using 2 threads, each thread will increment each array value by 1.
I did it with the following code but I'm really not sure my solution is ok...
static async Task Main(string[] args)
        {
            var count = 100;
            int[] array = new int[count];
            Array.Clear(array, 0, array.Length);

            await Task.WhenAll(IncrementArray(array, "Task 1"), IncrementArray(array, "Task 2"));
            Array.ForEach(array, Console.WriteLine);
        }

        static object obj = new object();

        static async Task IncrementArray(int[] array, string taskName)
        {
            for (var i = 0; i < array.Length; i++)
            {
                Console.WriteLine(taskName);
                await Task.Delay(100);
                lock (obj)
                {
                    array[i]++;
                }
            }
        }

Thanks for your help!

A: Your solution is not OK.  You have a race condition, i.e. the two threads may try to increment one element simultaneously and then produce incorrect results - an element of the array may remain 1, for example.
See Interlocked class, and also lock keyword.

A: You should use Interlocked.Increment that is like ++ but atomic to increse the value in one unit, keeping it thread safe


text:
Q: Migs Payment GateWay Always Return 400 Bad request im trying to integrate my website to Master card Payment gateway.
im trying to submit the form on Post man using the info from the document and the info they gave me from the website
but its always returns Bad request - 400 i just followed the documentation i have been stuck of three days now if some can help i'd appreciate that
here is an image of what i have tried
i have tried both post and get request deleted the cookies cleared the cache but with no luck

A: You need to pass the parameters as QueryString to the URL.
Here is an example:
https://migs.mastercard.com.au/vpcpay?Title={title}&vpc_AccessCode={accessCode}&vpc_Amount={amount}&vpc_Command={command}&vpc_Locale={locale}&vpc_MerchTxnRef={txnRef}&vpc_Merchant={merchantName}&vpc_OrderInfo={orderInfo}vpc_ReturnURL={returnUrl}&vpc_Version=1&vpc_SecureHash={hash}&vpc_SecureHashType={hashType}
Redirecting the customer to above constructed URL will lead to the Payment Gateway. Once the payment is completed, you'll receive the payment response on the returnUrl.


text:
Q: Optimize probability of success between k different flows I want to find a set of coefficients ($n \in R$) that solve the following optimization problem,
maximize $\prod_{i=1}^k(1-p_i)^{n_i}$    s.t. $\sum_{i=1}^k n_i = N$.
The $p$'s are known positive constants ($p \in (0,1)$). $N$ is some integer ($N>0$).
So far, I've tried the Lagrangian method but for $\frac{\partial{F}}{\partial{n_1}}$ I get an inter-dependent expression, i.e. $n_1=f(n_2,...,n_k,\lambda)$. Hence, I don't see how to derive $\lambda$ and find tractable expressions for $n_1,...,n_k$ which are purely functions of $\{p_1,...,p_k\}$.
I've also tried to maximize the $\exp(ln(f))$ but I end up with,
$\exp(n_1ln(1-p_1)+n_2ln(1-p_2)+...+n_kln(1-p_k))$
which doesn't seem to improve compared to the previous approach.
Please advise of an analytic (preferable) or numeric method to solve that, thanks!

A: Let $r_i = \ln(1-p_i)$.
You want to maximize $\prod_i (1-p_i)^{n_i}$. $\ln$ is monotonic, so we can instead maximize $\ln(\prod_i (1-p_i)^{n_i})$.
This simplifies to $\sum_i n_i \ln(1-p_i)$. Using my definition of $r_i$, this is $\sum_i n_i r_i$.
You want to maximize this subject to $\sum_i n_i = N$.
This is an LP with a trivial solution: Choose the $i$ corresponding to the largest $r_i$.
(If you don't trust me, you can write the dual of this LP and the answer is clear.)
Thus, the optimum solution to your original problem is to set $n_i=N$ corresponding to the index with the largest value of $\ln(1-p_i)$.
This is also equivalent to the index of the smallest value of $p_i$.


text:
Q: coffescript scope misunderstanding I'm trying to understand variable scopes in coffeescript and got confused a little bit, here's an example:
CoffeeScript code:
  x = "localscope"
  z = () ->
    x = "functionscope"
    console.log(x)

  console.log(x)

Javascript compiled result:
(function() {
  var x, z;

  x = "localscope";

  z = function() {
    x = "functionscope";
    return console.log(x);
  };

  console.log(x);

}).call(this);

As I know in pure javascript all variables wrapped in function acts in the same scope. So as I understood all variables written in coffescript are global?

A: To shadow a variable in coffeescript you need to do something like this:
x = "localscope"
z = ((x) -> () ->
    x = "functionscope"
    console.log(x)
)(x)
console.log(x)

Resulting javascript is:
var x, z;

x = "localscope";

z = (function(x) {
  return function() {
    x = "functionscope";
    return console.log(x);
  };
})(x);

console.log(x);

In your example, the x is not local to the innermost function, but referred to the same "global" x you declared at beginning. By "global", I mean accessible everywhere in the same file.

A: Javascript has a global scope as default scope. CoffeeScript has typically 'scope per file' by the anonymous function call as default scope. This prevents variable clash between script files in CoffeeScript.
I'm assuming you would like to create a global variable, wouldn't you? For that purpose you need to attach your variable to 'root object'.
For a browser script it will be window object. So you just need to:
window.x = 'globalscope'

...and done.
If you ment the opposite, so the variable isolation at function level. It will be created as such but you need to use different name. Please check the example from coffeescript.org (text search for 'scope'):
CoffeeScript
outer = 1
changeNumbers = ->
  inner = -1
  outer = 10
inner = changeNumbers()

Compiled to JavaScript
var changeNumbers, inner, outer;

outer = 1;

changeNumbers = function() {
  var inner;
  inner = -1;
  return outer = 10;
};

inner = changeNumbers();

A: It looks like you're confused about how CoffeeScript handles local scoping.
When a variable is defined, CoffeeScript hoists its variable definition to the top of the scope at which the variable is defined. Thus,
x = 'localscope'
z = ->
  x = 'functionscope'

gets parsed exactly as you described to
var x, z;
x = 'globalscope';
z = function () {
  x = 'localscope';
};

When the entire file is compiled, CoffeeScript wraps all of the code you've written into an anonymous function so that even your highest scoped variables do not bleed into the global namespace. That's the (function () { ... }).call(this) that you see at the top and bottom of the JavaScript version of your code.
If you're used to writing in Ruby, your expectation would be
> x = 5
> def z
>   x = 7
>   puts x
> end
> z # logs '7'
> x # still 5

Ruby automatically scopes every variable declaration locally unless the variable is defined otherwise (e.g. as an instance variable or a global variable).
JavaScript, on the other hand, scopes variables any time it sees the var prefix.
var x = 5;
function z () {
  var x = 7;
  console.log(x);
};
z(); // logs '7'
x; // still 5

CoffeeScript assumes that you might want your variables to permeate from higher scope to lower scope, and except for global variables (which can be set on the window object), there's no way to set an 'instance variable'-like variable that is scoped sort-of locally.
As @Esailija notes (although the solution isn't implemented quite perfectly), you can ensure that the x is scoped locally to the z function by passing in x as an argument, since JavaScript automatically scopes arguments only locally to the function that accepts them:
var x = 5;
function z (x) {
  x = 7;
  console.log(x);
};
z(); // logs '7' -- in JS, it's OK to execute a function without a named argument, which defaults to undefined
x; // still 5

or in CoffeeScript:
x = 5
z = (x) ->
  x = 7
  console.log x
z()
console.log x

As a side note, @Esailija 's solution is more idiomatically written using the do invocation:
x = "localscope"
z = do (x) -> () ->
  x = "functionscope"
  console.log(x)
console.log(x)


text:
Q: Angular Material how to align layout center I have this straight out of angular material website, because im having a lot of trouble with angular material flex layout.
According to the doc about layout container
Items arranged in a row. max-height = 100% and max-width is the width of the items in the container.
I tried the example provide at the doc page

one

two

three

my content is suppose to align vertically and horizontally at the center. but instead my content is aligning horizontally but not vertically.
I have the code example here

A:

one

two

three

please apply layout-fill on the containers that require to take up all the space


text:
Q: MySQL command Explain ignore LIMIT? I use MySQL server version 5.5.14 and now I am trying this simple SQL query with Explain command:
EXPLAIN SELECT id, name, thumb FROM `twitter_profiles` LIMIT 10;

and it shows me this result:
+----+-------------+-------+------+---------------+------+---------+------+-------+-------+
| id | select_type | table | type | possible_keys | key  | key_len | ref  | rows  | Extra |
+----+-------------+-------+------+---------------+------+---------+------+-------+-------+
|  1 | SIMPLE      | tp    | ALL  | NULL          | NULL | NULL    | NULL | 40823 |       |
+----+-------------+-------+------+---------------+------+---------+------+-------+-------+
1 row in set (0.02 sec)

My question is why it scans whole table instead of taking the first 10 rows as I specified in LIMIT clause?

A: here a good link of article about MySQL EXPLAIN limits and errors

LIMIT is not taken into account while estimating number of rows Even
  if you have LIMIT which restricts how many rows will be examined MySQL
  will still print full number

A: You need to use order by:
EXPLAIN SELECT id, name, thumb
FROM twitter_profiles ORDER BY LIMIT 10;


text:
Q: Problems with cinemachine by following Brackeys tutorial I followed everything in this video: https://www.youtube.com/watch?v=4HpC--2iowE&t=1s and I've got 2 problems:

*

*When I press play, the player object hovers over ground at the starting area and also causes the player to slowly rotate automatically in weird directions

*After I walk away from the staring position and don't hover over the ground anymore, my player character rotates around a point that isn't the center of my player - it's somewhere outside the player.
I feel like these 2 problems are caused by the same issue, but I have no idea how to fix it. I also noticed, that some people in the comments have this problem too, but didn't provide any fixes.


text:
Q: How can operators be used with phrases in MySQL's boolean mode? I've been looking through the examples for boolean full-text searches in the MySQL documentation, and they don't quite give me enough information to work confidently with operators (specifically +, - and *) in conjunction with phrases (as opposed to individual words).  There are plenty of questions on StackOverflow about using boolean mode, but they're all very specific.
There's nothing in the MySQL Boolean Full-Text Searches documentation that says whether (and if so, how) operators can be used in conjunction with phrases.  For example, MySQL doesn't complain when I use the following query:
SELECT * AS relevance FROM deliverables WHERE MATCH(title,description) AGAINST('+"customer engagement" vendor' IN BOOLEAN MODE)

This suggests that the syntax is valid, yet it returns matches that do not include the word 'customer' anywhere in the title or description!  So the plus sign is clearly not having the expected effect.
So my question could be rephrased: what are the rules for using operators with phrases?
Sub-questions include things like:

*

*Is +"some phrase" valid?  (My tests suggest so, but maybe the + is ignored.)

*Is -"some phrase" valid?  (My tests suggest so, and it seems to work as expected.)

*Is "som* phrase" valid?  (My tests suggest so, but it never matches anything.)

*Is "some phra*" valid?  (My tests suggest so, but it never matches anything.)

A: Use below syntax if want to match 3 words:
SELECT * FROM deliverables
WHERE MATCH(title,description)
AGAINST('+word1 +word2 +word3' IN BOOLEAN MODE);

Use below syntax if want to match 1 phrase:
AGAINST('"THIS IS MY"' IN BOOLEAN MODE);

Use below syntax if want results of either any one out of 2 phrase:
AGAINST('"THIS IS MY" "I AM NOT"' IN BOOLEAN MODE);

Please share if you want to get any specific results, if let me know the results what you want then I can help you in better way.

A: I was recently testing this out as well and came across your question.  Using MySQL 5.5 and testing your 4 conditions I see the following results:
Is +"some phrase" valid?
The + sign is ignored, the same result set is returned if it is included or not.
SELECT a.*
FROM company a
WHERE a.active = 1 AND MATCH(a.company) AGAINST('+"social media"' IN BOOLEAN MODE)

Is -"some phrase" valid?
The - sign is valid, but the search returns 0 results even when matching results are available.
SELECT a.*
FROM company a
WHERE a.active = 1 AND MATCH(a.company) AGAINST('-"social media"' IN BOOLEAN MODE)

Is "som* phrase" valid?
The * is valid, but the search returns 0 results even when matching results are available.
SELECT a.*
FROM company a
WHERE a.active = 1 AND MATCH(a.company) AGAINST('"socia* media"' IN BOOLEAN MODE)

Is "some phra*" valid?
The * is valid, but the search returns 0 results even when matching results are available.
SELECT a.*
FROM company a
WHERE a.active = 1 AND MATCH(a.company) AGAINST('"social medi*"' IN BOOLEAN MODE)


text:
Q: Make menu dissappear on click anywhere screen Hi i have this code which works perfect other than once i click anywhere on my screen to make the dropdown menu content disappear i can't reopen the menu. heres the code i'm using along with a jsfiddle demo below.

$(document).click(function (e)
{

  var container = $(".dropdown_content");

   if (!container.is(e.target) && container.has(e.target).length === 0)
  {
 container.fadeOut('slow');

   }

});
.dropdown {
    display: block;
    display: inline-block;
    margin: 0px 3px;
    position: relative;
}

/* ===[ For demonstration ]=== */

.dropdown { margin-top: 50px }

/* ===[ End demonstration ]=== */

.dropdown .dropdown_button {
    cursor: pointer;
    width: auto;
    display: inline-block;
    padding: 4px 5px;
    font-weight: bold;
    color: #000;
    line-height: 16px;
    text-decoration: none !important;
}

.dropdown input[type="checkbox"]:checked +  .dropdown_button {
    color: #000;
    padding: 4px 5px;
}

.dropdown input[type="checkbox"] + .dropdown_button .arrow {
    display: inline-block;
    width: 0px;
    height: 0px;
    border-top: 5px solid #fff;
    border-right: 5px solid transparent;
    border-left: 5px solid transparent;
}

.dropdown input[type="checkbox"]:checked + .dropdown_button .arrow { border-color: white transparent transparent transparent }

.dropdown .dropdown_content {
    position: absolute;
    border: 1px solid #fff;
    padding: 0px;
    margin: 0;
    display: none;
    padding: 7px;
    -webkit-transition: all 500ms ease-in-out;
    -moz-transition: all 200ms ease-in-out;
     -o-transition: all 500ms ease-in-out;
     -ms-transition: all 500ms ease-in-out;
      transition: all 500ms ease-in-out;
    -webkit-box-shadow: rgba(0, 0, 0, 0.58) 0px 12px 25px;
    -moz-box-shadow: rgba(0, 0, 0, 0.58) 0px 12px 25px;
    box-shadow: rgba(0, 0, 0, 0.58) 0px 12px 25px;
     background: #fff;
     font-size: 12px;
     -moz-border-radius: 0 0 4px 4px;
      -webkit-border-bottom-right-radius: 4px;
      -webkit-border-bottom-left-radius: 4px;
     border-radius: 0 0 4px 4px;
     min-width: 140px;
}

.dropdown .dropdown_content li {
    list-style: none;
    margin-left: 0px;
    line-height: 16px;
    border-top: 1px solid #FFF;
    border-bottom: 1px solid #FFF;
    margin-top: 2px;
    margin-bottom: 2px;
    -webkit-transition: all 0.2s ease-in-out;
    -moz-transition: all 0.2s ease-in-out;
}

.dropdown .dropdown_content li:hover {
    background: #d32d41;
    text-shadow: 1px 1px 0px #9e2635;
    -moz-background-clip: padding;
    -webkit-background-clip: padding-box;
    -webkit-box-shadow: inset 0 0 1px 1px #f14a5e;
    -moz-box-shadow: inset 0 0 1px 1px #f14a5e;
    box-shadow: inset 0 0 1px 1px #f14a5e;
    border: 1px solid #9e2635;
    color: #fff;
      -moz-border-radius: 2px;
    -webkit-border-radius: 2px;
    border-radius: 2px;

}

.dropdown .dropdown_content li a {
    display: block;
    padding: 2px 7px;
    padding-right: 15px;
    color: black;
    text-decoration: none !important;
    white-space: nowrap;
}

.dropdown .dropdown_content li:hover a {
    color: white;
    text-decoration: none !important;
}

.dropdown input[type="checkbox"]:checked ~ .dropdown_content { display: block }

.dropdown input[type="checkbox"] { display: none }

    <input type="checkbox" id="drop1" />
        click here

User panel

Log out

Edit profile

Edit options

Edit avatar

Edit signature

Buddy list

JSFIddle demo here
http://jsfiddle.net/andreas84x/x5wvnzt7/5/

A: It's because of the cascading order:

*

*Browser default

*External style sheet

*Internal style sheet

*Inline

When you click outside the dropdown it'll change the style attribute to display: none. Now when you trying to change the display to block/inline-block in css it doesn't take effect, because still inline display: none have priority.
The solution: use fadeIn on button click (remove this css fix) :)

A: Is this working. please check and reply.
check this FIDDLE
$(document).click(function (e){
var container = $(".dropdown_content");
if( container.is(':visible')) {
    if(e.target.id != "drop1"){
     $("#drop1").click();
    }
}
});

A:      .dropdown_content
        {
            display:none;
        }

 $(document).ready(function () {

            $(".dropdown_button").click(function (e) {
                e.preventDefault();
                $(".dropdown_content").show();
                });
            });

            $(document).click(function (e) {

                var container = $(".dropdown_content");
                if ($(e.target).closest(".dropdown_button").length > 0) {
                    return false;
                }
                if (!container.is(e.target) && container.has(e.target).length === 0) {
                    //e.preventDefault();
                    container.fadeOut();

                }
                //e.preventDefault();

            });

A: Write your JavaScript code into Anonymous function
    $(function(){
      $(document).click(function (e)
      {

      var container = $(".dropdown_content");

       if (!container.is(e.target) && container.has(e.target).length === 0)
      {
     container.fadeOut('slow');

       }

    });
  });


text:
Q: What is the ideal image to use to check connectivity in Kubernetes? I have used hello-world Docker image to create a deployment and test the pods running. But that image is meant to terminate after it's run once. Is there a light weight image I can use? Like a lightweight server?
Thanks.

A: You can use a nginx container. The apline images of NGINX are very small and lightweight.
https://hub.docker.com/_/nginx

A: You could replace the distroless base image with an Alpine based image.
It is a security-oriented, lightweight Linux distribution based on musl libc and busybox
A smaller image takes less disk size & less time to upload.
Recommendation is node:8-alpine


text:
Q: What are the pros and cons of synchronous versus asynchronous networking? I am quite frustrated at the amount documentation that says explicitly you should use asynchronous code for networking.
I even read an article which outright states 'Networking is an inherently asynchronous operation.'
https://react-native.org/doc/network.html
So first there is a difference between background processing and asynchronous code.
For example, running code asynchronously doesn't necessarily mean it is on the background.  For this we can actually use a background thread.
When you write an iOS app, and you have several view controllers, each accessing the same data which is downloaded by the Model, when you download the data for code asynchronously, you have a frustrating tangle of callbacks and asynchronous messages being passed throughout the application.
When I have multiple view controllers using the same data this poses a problem, how do I make sure I don't have the view controller which is opened accessing the data before it is downloaded?  You might not be able to tell which controller was opened first so this poses an issue, how do you make sure they don't access the data until it is finished downloading?
I suppose you solve this using a completion handler and a model which then fires off a Key Value Observing notification calling the controller when it is finished downloading (a push model).
But what happens if the said controller is not loaded when the notification is posted, does this mean it never gets the data?  Wouldn't it make more sense to use a pull model, so when the controller is loaded it can check if the data is available, if so how do you handle this with an async paradigm?
But any notification callback cannot access the outlying scope of the rest of the controller.
However I have written some entirely synchronous code which uses locks and semaphores.  The model downloads the data synchronously in a background thread.  The controller classes (if they are loaded) check the Model class to see if the data is available.  Locks mean that the code cannot access the data if the data is not downloaded.  The App signals when the data has finished downloading and while all controllers and models use the same shared synchronous DispatchQueue this prevents the controllers accessing the data arrays when they are empty or the data is being downloaded.
Async code commonly produces weakly coupled code that can't access the scope of the rest of the class and you have methods firing at different times and in different places in the app which i think is difficult to keep track of.  So why is networking 'an inherently asynchronous operation'?
Can anyone provide sound scientific reasons why asynchronous code is better, or reasons why I should not do what I have done with synchronous code, and also methods of how you can make asynchronous code safer, less spaghetti like, easier to work with and easier to read?
CODE:
Table View Controller
override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    if !fromSelectionCtrllr {

        let downloader = Downloader.sharedInstance
        let group = downloader.group

        group.notify(queue: .main, execute: {

            let defaults : UserDefaults = UserDefaults.standard
            let firstLaunch = defaults.bool(forKey: "firstLaunch")

            if firstLaunch {
                self.arrayOfData = Model.sharedInstance.provideData()
            } else {
                self.arrayOfData = Model.sharedInstance.provideNewData()
            }

            for object in self.arrayOfData {

                if let deviceName = object.chargeDeviceName {

                    let theSubscript = deviceName.prefix(1)

                    let theString = String(theSubscript)

                    if !self.sectionTitles.contains(theString) {

                        self.sectionTitles.append(theString)
                    }
                } else {

                    self.sectionTitles.append("")
                }

                if let deviceName = object.chargeDeviceName  {

                    let string = String(describing: deviceName.prefix(1))

                    var arry = self.chargingPointDict[string]

                    if arry == nil {

                        arry = []
                    }

                    arry?.append(object)

                    self.chargingPointDict.updateValue(arry!, forKey: string)

                } else {

                    self.chargingPointDict[" "]?.append(object)
                }
            }

            self.sectionTitles = self.removeDuplicates(array: self.sectionTitles)

            self.sectionTitles = self.sectionTitles.sorted( by: { $0 < $1 })

            DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
                self.myTableView.reloadData()
            }
        })

    }

    fromSelectionCtrllr = false

}

CellForRowAtIndexPath
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)

    if (searchController.searchBar.text?.isEmpty)! {

        if self.sectionTitles.isEmpty {

            cell.textLabel?.text = "Nothing to display"
            return cell

        } else {

            let mySectionIndex = self.sectionTitles[indexPath.section]

            if mySectionIndex != "" {

                let arrayOfPoints : [ChargingPoint] = self.chargingPointDict[mySectionIndex]!

                let object : ChargingPoint = arrayOfPoints[indexPath.row]

                cell.textLabel?.text = object.chargeDeviceName

                return cell

            } else {

                return cell
            }

        }

    } else {

        let object : ChargingPoint = self.filteredPoints[indexPath.row]

        cell.textLabel?.text = object.chargeDeviceName

        return cell
    }

}

Model Class
class Model: NSObject {

var currentChargingPointArray : [ChargingPoint] = []
var newChargingPointArray : [ChargingPoint] = []

var latitude : Double?
var longitude : Double?

var annotationArray : [ChargingPointAnnotation] = []
var newAnnotationArray : [ChargingPointAnnotation] = []

static let downloader = Downloader.sharedInstance

var savedRegion : MKCoordinateRegion? = nil

/* The model class is a singleton */
static let sharedInstance : Model = {
    let instance = Model()

    return instance
}()

fileprivate override init( ) {} //This prevents others from using the default '()' initializer for this class.

func setLocation(lat: Double, long: Double) {

    self.latitude = lat
    self.longitude = long
}

func returnData(array: Array<ChargingPoint>) {

    currentChargingPointArray = []

    var seen = Set<String>()
    var unique = [ChargingPoint]()
    for point in array {
        if !seen.contains(point.chargeDeviceId!) {
            unique.append(point)
            seen.insert(point.chargeDeviceId!)
        }
    }

    currentChargingPointArray = unique

}

func returnNewData(array: Array<ChargingPoint>) {

    newChargingPointArray = []

    var seen = Set<String>()
    var unique = [ChargingPoint]()
    for point in array {
        if !seen.contains(point.chargeDeviceId!) {
            unique.append(point)
            seen.insert(point.chargeDeviceId!)
        }
    }

    newChargingPointArray = unique

}

func provideData() -> [ChargingPoint] {

    return currentChargingPointArray

}

func provideNewData() -> [ChargingPoint] {

    return newChargingPointArray

}

func makeAnnotations() -> [ChargingPointAnnotation] {

    let queue = DispatchQueue(label: "com.jackspacie.ChargeFinder", qos: .background, attributes: [])

    queue.sync {

        self.annotationArray = []

        for chargingPoint in currentChargingPointArray {

            let location = CLLocationCoordinate2D( latitude: chargingPoint.latitude!, longitude: chargingPoint.longitude!)

            let annotation = ChargingPointAnnotation(location: location)
            annotation?.title = chargingPoint.chargeDeviceName
            annotation?.pointTitle = chargingPoint.chargeDeviceName

            annotation?.chargingPoint = chargingPoint

            self.annotationArray.append(annotation!)
        }

    }

    return self.annotationArray
}

func makeNewAnnotations() -> [ChargingPointAnnotation] {

    let queue = DispatchQueue(label: "com.jackspacie.ChargeFinder", qos: .background, attributes: [])

    queue.sync {

        self.newAnnotationArray = []

        for chargingPoint in newChargingPointArray {

            let location = CLLocationCoordinate2D( latitude: chargingPoint.latitude!, longitude: chargingPoint.longitude!)

            let annotation = ChargingPointAnnotation(location: location)
            annotation?.title = chargingPoint.chargeDeviceName
            annotation?.pointTitle = chargingPoint.chargeDeviceName

            annotation?.chargingPoint = chargingPoint

            self.newAnnotationArray.append(annotation!)
        }

    }

    return self.newAnnotationArray
}

Downloader Class
var group = DispatchGroup()
var model = Model.sharedInstance

/* The downloader class is a singleton */
static let sharedInstance : Downloader = {
    let instance = Downloader()

    return instance
}()

fileprivate override init() {} //This prevents others from using the default '()' initializer for this class.

func download(lat: Double, long: Double, dist: Int)  {

    func recursive(lat: Double, long: Double, dist: Int) {

        var chargeDeviceArray : [ChargingPoint] = []

        let url = URL(string: "https://www.blah.com/lat/\(lat)/long/\(long)/dist/\(dist)/")!

        let semaphore = DispatchSemaphore(value: 0)
        let task = URLSession.shared.dataTask(with: url) { data, response, error in

            if error != nil {
                print("urlSession Error")

                recursive(lat: lat, long: long, dist: dist)

                return
            } else {

                guard let unwrappedData = data else { return }
                do {
                    let jsonDict : [String: Any] = try JSONSerialization.jsonObject(with: unwrappedData, options: [] ) as! [String : Any]

                    let arrayOfDicts = jsonDict["ChargeDevice"] as? [[String: Any]]

                    for value in arrayOfDicts! {

                        let chargePoint = ChargingPoint()

                        // process data into objects.

                        chargeDeviceArray.append(chargePoint)

                    }

                    var seen = Set<String>()
                    var unique = [ChargingPoint]()
                    for point in chargeDeviceArray {
                        if !seen.contains(point.chargeDeviceId!) {
                            unique.append(point)
                            seen.insert(point.chargeDeviceId!)
                        }
                    }

                    if self.model.currentChargingPointArray.isEmpty {

                        self.model.returnData(array: unique)

                    } else {

                        self.model.returnNewData(array: unique)
                    }

                } catch {

                    print("json error: \(error)")
                }

                semaphore.signal()
            }

            //print(response)

        }
        task.resume()
        semaphore.wait(timeout: .distantFuture)
    }

    self.group.enter()

    let queue = DispatchQueue(label: "com.myapp.charge", qos: .background, attributes: [])

    queue.sync {

        recursive(lat: lat, long: long, dist: dist)

    }

    self.group.leave()

}

A: In short, when it comes to synchronous networking there are very limited cases where you would prefer this. Why?
Because 'A synchronous request blocks the client until operation completes' and in general you don't want the client to freeze. The user can't do anything at that time since we are waiting for all the synchronous actions to complete before enabling the client.
When using asynchronous requests you can build UI, show spinners and depending on whether you already cached older data or have other functionalities, still let the user use your client.

A:
When I have multiple view controllers using the same data this poses a problem, how do I make sure I don't have the view controller which
  is opened accessing the data before it is downloaded? You might not be
  able to tell which controller was opened first so this poses an issue,
  how do you make sure they don't access the data until it is finished
  downloading?
I suppose you solve this using a completion handler and a model which
  then fires off a Key Value Observing notification calling the
  controller when it is finished downloading (a push model).
But I ask this, what happens if the said controller is not loaded when
  the notification is posted, does this mean it never gets the data?
  Wouldn't it make more sense to use a pull model, so when the
  controller is loaded it can check if the dat is available, if so how
  do you handle this with an async paradigm?

Load UI-> Show Progress Dialog -> Perform ASYNC(LoadData,SetData intoController)-> DismissDialog
Idk if  this is what you're refering
I really dont see an oportunity where you will prefer block UI Thread and freeze App until it loads the data synchronically

A: The article states that "networking is an inherently asynchronous operation" because networking is an inherently asynchronous operation.
Synchronous means "happening at the same time".  Specifically in computing it means with reference to a specific time period or clock signal. For example, electrically, the CPU operates  synchronously, which is why we talk about the clock speed of a computer.
Synchronous does not mean "blocking" although that is a common (mis)interpretation.  In fact, Apple hasn't helped here with their function names. Technically they should be something like DispatchQueue.nonBlockingOperation() and DispatchQueue.blockingOperation() rather than async/sync.
Synchronous systems can operate at much higher speeds but require a very controlled environment, which is why you find synchronous operation at the core of a computer but not so much outside it.
Your code blocks a background queue waiting for the download to complete, but the download still completes asynchronously.  If it were completing synchronously you wouldn't need the semaphore.  You would know that the data would be available at the specified point in time (say 0.2 seconds from now or whatever).
Your Downloader class also still notifies the view controller about the available data asynchronously via the dispatch group notify.
From what I can see, you have added a bunch of complexity to the solution (By adding a dispatch group and a semaphore) and introduced the potential for deadlocks but you still have asynchronous code. You block the background queue waiting for the completion of the download, but you still notify the data consumers asynchronously.
The same outcome could be achieved using the standard delegation or completion handler patterns with much less complexity. If there are potentially multiple parties interested in knowing about the new data then you can use the NotificationCentre to "broadcast" that information.
By the way, loosely coupled code is generally considered more desirable.


text:
Q: Error Database Connection in CodeIgninter Currently I'm developing a project using:

*

*PHP Framework CodeIgniter (V.2..)

*Database SQL Server 2018

As usual it runs well, but sometimes if I refresh it many times or there are about 10 users accessing it in real time, suddenly I get error although my database setting is correct. The error says:

I'm just curious, it's a framework issue; can't handle a huge database so the server disconnected it automatically, perhaps the query is not effective, or bad scripting....
Maybe anyone can share the experiences due to this issue or solution?


text:
Q: How to auto-push changes to git whenever a directory is changed I want my repo's local directory to essentially trigger a commit/push whenever any file in the directory has been changed.
I have looked into inotify-tools, specifically this command:
inotifywait -q -m -e CLOSE_WRITE --format="git commit -m 'auto commit' %w && git push origin <<branch>>" <<file>> | bash

but it looks like that is file-specific, whereas I want it listening for any change in any file in the local directory. Ideas?

A: a git script listens to changes if get any changes the auto-commit
cd /Users/[username]/[project-path]

while true; do
  changes=$(git diff --name-only HEAD)

  if [ ! -z "$changes" ]; then
    git add .

    timestamp=$(date +%Y-%m-%d-%H-%M-%S)
    git commit -m "Auto-commit at $timestamp"

    git push origin
  fi

  sleep 5
done


text:
Q: EF Linq query with conditional include So I have the following Linq query:
var member = (from mem in
              context.Members.Include(m =>
              m.MemberProjects.Select(mp => mp.Project))
              where mem.MemberId == memberId
             select mem).FirstOrDefault();

This returns a Member entity, with a set of MemberProjects that have a Project child. I would like to limit the MemberProjects to only those for which the Project child has a property
ProjectIdParent == null.
One of my failed attempts might make the intent clearer:
var member = (from mem in context.Members
             .Include(m => m.MemberProjects
                            .Where(mp =>
                                   mp.Project.ProjectIdParent == null)
             .Select(proj => proj.Project))
             where mem.MemberId == memberId
             select mem).FirstOrDefault();

This of course complains of an invalid Include expression because of the Where clause.
Any thoughts on how to do this would be great :)

A: DISCLAIMER: I havent tested this. This is just an idea. If you let me know the results, I will update this accordingly. (Skip to the update part for the tested solutions)
var member = (from mps in context.MemberProjects
                                .Include(m => m.Members)
                                .Include(m => m.Projects)
              where mps.Project.ProjectIdParent == null
              select mps)
              .FirstOrDefault(mprojs => mprojs.Member.MemberId == memberId);

I'd also analyze the queries using something like EFProfiler to make sure the generated queries dont leave the realm of sanity.
You can also take a look at this post by Jimmy Bogard on Many to Many relationships with ORMs.
Update
I came up with multiple tested solutions for this with EF 6.1.3. My Edmx looked like below:

The setup data is like below:

I was able to run code below to get the MemberFive correctly
var member = context.Members.FirstOrDefault
                     (m => m.MemberId == memberId
                         && m.Projects.Any(p => p.ProjectParentId == null));

The generated SQL looked like this:
SELECT TOP (1) [Extent1].[MemberId]   AS [MemberId],
           [Extent1].[MemberName] AS [MemberName]
FROM   [dbo].[Members] AS [Extent1]
WHERE  ([Extent1].[MemberId] = 1)
   AND (EXISTS (SELECT 1 AS [C1]
                FROM   (SELECT [MemberProjects].[MemberId]  AS [MemberId],
                               [MemberProjects].[ProjectId] AS [ProjectId]
                        FROM   [dbo].[MemberProjects] AS [MemberProjects])
           AS [Extent2]
                       INNER JOIN [dbo].[Projects] AS [Extent3]
                         ON [Extent3].[ProjectId] = [Extent2].[ProjectId]
                WHERE  ([Extent1].[MemberId] = [Extent2].[MemberId])
                       AND ([Extent3].[ProjectParentId] IS NULL)))

If you dont like the generated query you can use this:
 var memberQuery = @"Select M.* from Members M
                            inner join MemberProjects MP on M.MemberId = Mp.ProjectId
                            inner join Projects P on MP.ProjectId = P.ProjectId
                            where M.MemberId = @MemberId and P.ProjectParentId is NULL";
 var memberParams = new[]
                     {
                      new SqlParameter("@MemberId", 1)
                     };
 var member3 = context.Members.SqlQuery(memberQuery, memberParams)
               .FirstOrDefault();

The later consistently returned under 20ms vs the other one hovered around 60ms (if that matters to you).
I hope this helps.


text:
Q: NSXMLParser and Geonames I'm trying to parse a call from Geonames with NSXMLParser in the iPhone SDK. I've used this before but for some reason I'm getting an empty dictionary back even though I get results back in a web browser. Can someone please point out what I may be doing wrong.
Below is the code I'm using and the results that comes back pasting it in a browser.
Thanks in advance
 #pragma mark -
#pragma mark - Parcer Services

-(void)beginLoadingFeed{
 //[self startLoadingWithMessage:@"Loading Results...."];
 NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(loadFeed) object:nil];
 [operationQueue addOperation:operation];
 [operation release];
}

- (void)loadFeed{
 NSString *path = [NSString stringWithFormat:@"http://ws.geonames.org/postalCodeSearch?placename=%@&long&maxRows=20",self.location];
 [Logger log:@"Geonames Query: %@",path];
 [self parseXMLFileAtURL:path];
 [self performSelectorOnMainThread:@selector(didfinishedLoadingFeed) withObject:nil waitUntilDone:YES];
}

-(void)didfinishedLoadingFeed{

}

- (void)parserDidStartDocument:(NSXMLParser *)parser{
 [Logger log:@"found file and started parsing"];
}

//Called when the parser runs into an open tag (<tag>)
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {

 if ([elementName isEqualToString:@"code"]) {
  currentResult = [NSMutableDictionary dictionary];
 } else {
  currentElement = [elementName copy];
 }

}

//This is just to resolve random HTML entities
- (NSData *)parser:(NSXMLParser *)parser resolveExternalEntityName:(NSString *)entityName systemID:(NSString *)systemID {
 return [entityName dataUsingEncoding:NSASCIIStringEncoding];
}

- (void)parseXMLFileAtURL:(NSString *)URL{
 self.results = [[[NSMutableArray alloc] init] autorelease];
 NSURL *xmlURL = [NSURL URLWithString:URL];
 NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:xmlURL];
 [parser setDelegate:self];
 [parser parse];
 [parser autorelease];
}

- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError {
 NSString * errorString = [NSString stringWithFormat:@"Unable to connect to web site (Error code %i )", [parseError code]];
 [Logger log:@"error parsing : %@", errorString];
 [self stopLoadingView];
 [self showMessage:@"Error loading content" withTitle:@"Error Loading"];
}

/*** Called when the parser runs into a close tag (</tag>). If it is the Result tag that is closing, we should add the currentResult to the array, and then forget about it ***/
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
 if ([elementName isEqualToString:@"code"]) {
   [self.results addObject:currentResult];
   currentResult = nil;
 }
}

- (void)parserDidEndDocument:(NSXMLParser *)parser {
 [Logger log:@"all done!"];
 [Logger log:@"results array has %d items", [self.results count]];
 [Logger log:@"Results:%@",results];
 [theTableView reloadData];
 [self stopLoadingView];
}

Below is the result that comes back in a browser using the same call above when doing the search for the term "boston":
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<geonames>
<totalResultsCount>2808</totalResultsCount>

<postalcode>02101</postalcode>
<name>Boston</name>
<countryCode>US</countryCode>
<lat>42.370567</lat>
<lng>-71.026964</lng>
<adminCode1>MA</adminCode1>
<adminName1>Massachusetts</adminName1>
<adminCode2>025</adminCode2>
<adminName2>Suffolk</adminName2>
<adminCode3/>
<adminName3/>

<postalcode>02108</postalcode>
<name>Boston</name>
<countryCode>US</countryCode>
<lat>42.357603</lat>
<lng>-71.068432</lng>
<adminCode1>MA</adminCode1>
<adminName1>Massachusetts</adminName1>
<adminCode2>025</adminCode2>
<adminName2>Suffolk</adminName2>
<adminCode3/>
<adminName3/>

<postalcode>02109</postalcode>
<name>Boston</name>
<countryCode>US</countryCode>
<lat>42.360027</lat>
<lng>-71.054495</lng>
<adminCode1>MA</adminCode1>
<adminName1>Massachusetts</adminName1>
<adminCode2>025</adminCode2>
<adminName2>Suffolk</adminName2>
<adminCode3/>
<adminName3/>

<postalcode>02110</postalcode>
<name>Boston</name>
<countryCode>US</countryCode>
<lat>42.357636</lat>
<lng>-71.051417</lng>
<adminCode1>MA</adminCode1>
<adminName1>Massachusetts</adminName1>
<adminCode2>025</adminCode2>
<adminName2>Suffolk</adminName2>
<adminCode3/>
<adminName3/>

<postalcode>02111</postalcode>
<name>Boston</name>
<countryCode>US</countryCode>
<lat>42.350348</lat>
<lng>-71.0629</lng>
<adminCode1>MA</adminCode1>
<adminName1>Massachusetts</adminName1>
<adminCode2>025</adminCode2>
<adminName2>Suffolk</adminName2>
<adminCode3/>
<adminName3/>

<postalcode>02114</postalcode>
<name>Boston</name>
<countryCode>US</countryCode>
<lat>42.361111</lat>
<lng>-71.06823</lng>
<adminCode1>MA</adminCode1>
<adminName1>Massachusetts</adminName1>
<adminCode2>025</adminCode2>
<adminName2>Suffolk</adminName2>
<adminCode3/>
<adminName3/>

<postalcode>02115</postalcode>
<name>Boston</name>
<countryCode>US</countryCode>
<lat>42.342706</lat>
<lng>-71.092215</lng>
<adminCode1>MA</adminCode1>
<adminName1>Massachusetts</adminName1>
<adminCode2>025</adminCode2>
<adminName2>Suffolk</adminName2>
<adminCode3/>
<adminName3/>

<postalcode>02116</postalcode>
<name>Boston</name>
<countryCode>US</countryCode>
<lat>42.349201</lat>
<lng>-71.076798</lng>
<adminCode1>MA</adminCode1>
<adminName1>Massachusetts</adminName1>
<adminCode2>025</adminCode2>
<adminName2>Suffolk</adminName2>
<adminCode3/>
<adminName3/>

<postalcode>02118</postalcode>
<name>Boston</name>
<countryCode>US</countryCode>
<lat>42.336162</lat>
<lng>-71.072854</lng>
<adminCode1>MA</adminCode1>
<adminName1>Massachusetts</adminName1>
<adminCode2>025</adminCode2>
<adminName2>Suffolk</adminName2>
<adminCode3/>
<adminName3/>

<postalcode>02128</postalcode>
<name>Boston</name>
<countryCode>US</countryCode>
<lat>42.364197</lat>
<lng>-71.025694</lng>
<adminCode1>MA</adminCode1>
<adminName1>Massachusetts</adminName1>
<adminCode2>025</adminCode2>
<adminName2>Suffolk</adminName2>
<adminCode3/>
<adminName3/>

<postalcode>02199</postalcode>
<name>Boston</name>
<countryCode>US</countryCode>
<lat>42.347873</lat>
<lng>-71.082543</lng>
<adminCode1>MA</adminCode1>
<adminName1>Massachusetts</adminName1>
<adminCode2>025</adminCode2>
<adminName2>Suffolk</adminName2>
<adminCode3/>
<adminName3/>

<postalcode>02210</postalcode>
<name>Boston</name>
<countryCode>US</countryCode>
<lat>42.348921</lat>
<lng>-71.046511</lng>
<adminCode1>MA</adminCode1>
<adminName1>Massachusetts</adminName1>
<adminCode2>025</adminCode2>
<adminName2>Suffolk</adminName2>
<adminCode3/>
<adminName3/>

<postalcode>02215</postalcode>
<name>Boston</name>
<countryCode>US</countryCode>
<lat>42.347088</lat>
<lng>-71.102689</lng>
<adminCode1>MA</adminCode1>
<adminName1>Massachusetts</adminName1>
<adminCode2>025</adminCode2>
<adminName2>Suffolk</adminName2>
<adminCode3/>
<adminName3/>

<postalcode>22713</postalcode>
<name>Boston</name>
<countryCode>US</countryCode>
<lat>38.538241</lat>
<lng>-78.142285</lng>
<adminCode1>VA</adminCode1>
<adminName1>Virginia</adminName1>
<adminCode2>047</adminCode2>
<adminName2>Culpeper</adminName2>
<adminCode3/>
<adminName3/>

<postalcode>24592</postalcode>
<name>South Boston</name>
<countryCode>US</countryCode>
<lat>36.696335</lat>
<lng>-78.918829</lng>
<adminCode1>VA</adminCode1>
<adminName1>Virginia</adminName1>
<adminCode2>083</adminCode2>
<adminName2>Halifax</adminName2>
<adminCode3/>
<adminName3/>

<postalcode>02102</postalcode>
<name>Boston</name>
<countryCode>US</countryCode>
<lat>42.338947</lat>
<lng>-70.919635</lng>
<adminCode1>MA</adminCode1>
<adminName1>Massachusetts</adminName1>
<adminCode2>025</adminCode2>
<adminName2>Suffolk</adminName2>
<adminCode3/>
<adminName3/>

<postalcode>02103</postalcode>
<name>Boston</name>
<countryCode>US</countryCode>
<lat>42.338947</lat>
<lng>-70.919635</lng>
<adminCode1>MA</adminCode1>
<adminName1>Massachusetts</adminName1>
<adminCode2>025</adminCode2>
<adminName2>Suffolk</adminName2>
<adminCode3/>
<adminName3/>

<postalcode>02104</postalcode>
<name>Boston</name>
<countryCode>US</countryCode>
<lat>42.338947</lat>
<lng>-70.919635</lng>
<adminCode1>MA</adminCode1>
<adminName1>Massachusetts</adminName1>
<adminCode2>025</adminCode2>
<adminName2>Suffolk</adminName2>
<adminCode3/>
<adminName3/>

<postalcode>02105</postalcode>
<name>Boston</name>
<countryCode>US</countryCode>
<lat>42.338947</lat>
<lng>-70.919635</lng>
<adminCode1>MA</adminCode1>
<adminName1>Massachusetts</adminName1>
<adminCode2>025</adminCode2>
<adminName2>Suffolk</adminName2>
<adminCode3/>
<adminName3/>

<postalcode>02106</postalcode>
<name>Boston</name>
<countryCode>US</countryCode>
<lat>42.354318</lat>
<lng>-71.073449</lng>
<adminCode1>MA</adminCode1>
<adminName1>Massachusetts</adminName1>
<adminCode2>025</adminCode2>
<adminName2>Suffolk</adminName2>
<adminCode3/>
<adminName3/>

</geonames>

A: You're getting a null dictionary because currentResult is never given any data.  The didStartElement and didEndElement methods don't actually give you what's inside the <foo>bar</foo> tag.
To get the actual content of an element, use the - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string method.


text:
Q: Alternative proof that $f(x) = $ sin $\frac{1}{x^x}$ is not uniformly continuous on (0,1]? My idea is to make use of this theorem:
"A real-valued funtion $f$ on $(a,b)$ is uniformly continuous on $(a,b)$ if and only if it can be extended to a continuous function $f$ on $[a,b]$."
My reasoning is that since sin $\frac{1}{x^x}$ oscillates infinitely near the origin, it cannot be made continuous by extending $f$ by assigning any value to $f(x)$ for the case when $x = 0$.
Is this a valid line of reasoning? How could I make it mathematically precise?

A: It will not work, since$$\lim_{x\to0^+}\sin\left(\frac1{x^x}\right)=\sin\left(\lim_{x\to0^+}\frac1{x^x}\right)=\sin(1).$$Actually, it follows from this that your function is continuous on $(0,1]$, since you can extend it to a continuous function from $[0,1]$ into $\Bbb R$.


text:
Q: Can a Drawable be used as a Shader somehow? I'm aiming to update an SVG library I've written to support the use of pattern fills. In one particular SVG file I'm looking at that makes use of a pattern fill, the pattern is itself defined in terms of shapes (as opposed to an external or embedded bitmap).
To be able to handle this, what I considered doing is to have the parser create a Drawable that draws the shapes defined by the pattern, and then to somehow use that Drawable as a Shader for the Paint.
Unfortunately it seems that no such thing as a DrawableShader exists, and to implement something like this myself would mean delving into native code from what I can see from the source of existing Shader classes.
I think the only solution for me is to render the pattern tile to a Bitmap and then use BitmapShader. This is okay, though to avoid potential quality issues of scaling Bitmaps I prefer to keep absolutely everything as a set of vectors.
Before I go down the Bitmap and BitmapShader route, is there another way I have overlooked?

A: It seems that the answer is "no". For this reason, I used BitmapShader in the end.


text:
Q: failed to import numpy as np when I worked with jupyter notebook In Jupyter, there is an ImportError:
import numpy as np

ImportError                                 Traceback (most recent call last)
ipython-input-1-4ee716103900 in module()
----> 1 import numpy as np
ImportError: No mudule named numpy

But in Python, there is no error:
import numpy as np

A: Usually this happens because your python is one Python environment and whatever you're running your notebook with is another. Try running import sys; sys.executable in both environments and seeing whether or not they match. If they don't, that's your problem: whatever jupyter is running in is borrowing numpy from the root environment.

A: For ubunutu environment
in jupyter, run:
import sys; sys.executable

This will display the python location eg
/home/paul/notepad_vm/notepad_vm/bin/python

switch to bash shell
cd /home/paul/notepad_vm/notepad_vm/bin/python

./pip install numpy

switch back to Jupyter, run:
import numpy as np


text:
Q: Split result in to Strings I'm using a google function to return the Long/lat of a location based on an address, however when I try to split it out the results come back as undefined (it works if i alert results[0].geometry.latitude out) - but myLatLong does not get set
function getLatLong(address){
    var geo = new google.maps.Geocoder;
geo.geocode({'address':address},function(results, status){
    var myLatLong;
    if (status == google.maps.GeocoderStatus.OK) {

        myLatLong = results[0].geometry.latitude;
        localStorage.setItem("SearchLat", myLatLong.split("," ,0));
        localStorage.setItem("SearchLong", myLatLong.split("," ,1));

    } else {
        alert("Geocode was not successful for the following reason: " + status);
    }

});

}

A: The geometry.location is an object, not a string.  From the API:

location contains the geocoded latitude,longitude value. Note that we return this location as a LatLng object, not as a formatted string.

I think you need:
myLatLong = results[0].geometry.location;
localStorage.setItem("SearchLat", myLatLong.lat());
localStorage.setItem("SearchLong", myLatLong.lng());

Note that you can also convert a LatLng object to a string "lat,lng" using toUrlValue, so I guess you could also use this:
var myLatLong = results[0].geometry.location.toUrlValue();
localStorage.setItem("SearchLat", myLatLong .split(",")[0]);
localStorage.setItem("SearchLong", myLatLong.split(",")[1]);


text:
Q: How to rename the IBOutlet property without lose the connection I work with old project and in some part of the project, the naming convention is not good so I want to change it.
For example:
@property (weak, nonatomic) IBOutlet UIButton *btnRequestCode;
rename it to -> @property (weak, nonatomic) IBOutlet UIButton *requestCodeButton;

I know that I can delete the IBOutlet then reconnect but it may take many time and easy make error if careless
Any safe and fast way to do it?
I have tried Refactor -> Rename but it doesn't work and give me an warning

Any help or suggestion would be great appreciated.

A: This is what I usually do

*

*Right Click the IBOutlet name,then selected Find Selected Text in Workspace

*Click find,then selected replace

3.Replace to the name you want

4.You can click Replace All if you are sure. You can also to click preview to Replace every single change

A: I put my two cents in. I tried to refactor several similar IBOutlet-s and ended to complete successfully only one - the first one.
All others outlets of this type throw me the error on refactoring:

Project and XCode reloading doesn't solve the problem. I checked *.xib source - the first one is fine:

My XCode ver 9.2(9C40b)

A: Xcode 9, Refactor > Rename
New in Xcode 9 you can rename an outlet (or action) in the code and storyboard at the same time.
*DISCLAIMER: This feature only works in Xcode 9 (released September 2017) and above. Make sure to backup your project before using it. After making outlet name changes, test the affected screen(s) to make sure there are not issues. I tested this in a sample Objective C project successfully but it could cause problems in existing, more complex projects.
To rename an outlet...

 1. Navigate to outlet in the header file
@property (weak, nonatomic) IBOutlet UIButton *btnRequestCode;

 2. Right click on outlet, select "Refactor > Rename...".

 3. Change the outlet name
 4. Select the "Rename" button or the Enter key

The outlet is renamed in the code and storyboard
@property (weak, nonatomic) IBOutlet UIButton *requestCodeButton;

A: If you are using Xcode Version 9.0 (release 9A235 or earlier beta) and you don't want to crash at UIApplicationMain() you will need to perform the following steps in order to rename an IBOutlet instance variable. (see below)
Steps:

*

*Right-click the outlet instance variable

*Select "Refactor -> Rename..."

*Enter a new name Change all of them

do

*Right-click the related '.xib' file (or files) in project file list

*Select "Open As -> Source Code" (it will show you the XML then...)

*Search and replace old variable name with new in .xib

while ( untouched related .xib files exist)
I wasted hours trying to figure out why the app was crashing in UIApplicationMain() after doing some mass refactoring of variable names. No logic changes, just hours of documenting, cleaning up structure for readability and just cleaning up names... not worth testing normally but when I decided to run.. BOOM
As it turns out, the (ahem) "release" of Xcode 9 does not manage to actually refactor IBOutlet instance variable names so you relegated to hand-jamming the .xib files. True refactoring would make all the necessary changes in the project...
Here is a regression tested example of how and what to do.
Example:
Select the IBOutlet instance variable, then right-click, select Refactor -> Rename... :
(step 1 and 2)

Now change the name. (for the example from textFieldController to editTextFieldController) :
(step 3)

Now for the critical part that Xcode neglects, change the custom outlet property in the XML:
(steps 4, and 5)

and then find the original variable (eg textFieldController) and change it to the new variable name (eg editTextFieldController)
(step 6)

... and then when you compile and run, it doesn't throw an exception / assertion in UIApplicationMain() ...


text:
Q: How to exit ExecutorService after all the threads have done their execution? This is the code which is working but I am specifying the wait time explicitly. Is there any way to exit ExecutorService when all the threads have completed their execution.
    ExecutorService es = Executors.newCachedThreadPool();
    {
      for(final List<String> list:partitions){

       es.execute(new Runnable() {
         public void run() {
      try{
            System.out.println(list);
            new CallAPI().make_call(list, access_token);

        }catch(Exception e){
        System.out.println(e);
        }
      }
     });
    Thread.sleep(5000);
   }
   boolean finshed = es.awaitTermination(15, TimeUnit.MINUTES);
   es.shutdown();

boolean finshed = es.awaitTermination(15, TimeUnit.MINUTES);==>I am giving here wait time but I don't want this because I don't know when the thread will finish execution

A: *

*use Future<?> f = executor.submit(new Runnable(...));

*store the futures in a list

*after the loop, iterate over the futures and call f.get()
This will block until all the tasks have been executed.
You can then call executor.shutdown().

A: It sounds like you want ExecutorService.invokeAll. All you have to do is convert your collection of lists to a collection of Callables.
List<Callable<String>> tasks = partitions.stream()
    .map(list->{
         System.out.println(list);
         new CallAPI().make_call(list, access_token);
         return "finished";
    }).collect(Collectors.toList());

List<Future<String>> futures = es.invokeAll(tasks);
es.shutdown();

Then you have the futures, you can use them to check for exceptions, or if the task completed ok.

A: The following method shuts down an ExecutorService in two phases, first by calling shutdown to reject incoming tasks, and then calling shutdownNow, if necessary, to cancel any lingering tasks:
 void shutdownAndAwaitTermination(ExecutorService pool) {
   pool.shutdown(); // Disable new tasks from being submitted
   try {
     // Wait a while for existing tasks to terminate
     if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
       pool.shutdownNow(); // Cancel currently executing tasks
       // Wait a while for tasks to respond to being cancelled
       if (!pool.awaitTermination(60, TimeUnit.SECONDS))
           System.err.println("Pool did not terminate");
     }
   } catch (InterruptedException ie) {
     // (Re-)Cancel if current thread also interrupted
     pool.shutdownNow();
     // Preserve interrupt status
     Thread.currentThread().interrupt();
   }
 }

boolean awaitTermination(long timeout, TimeUnit unit)
Blocks until all tasks have completed execution after a shutdown request, or the timeout occurs, or the current thread is interrupted, whichever happens first.

A: To terminate the ExecutorService when all tasks are finished, just call es.shutdown(). Your own thread will continue the execution, while the task-threads will process all queued tasks.
From Java Doc:

shutdown
  Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted. Invocation has no additional effect if already shut down.
  This method does not wait for previously submitted tasks to complete execution. Use awaitTermination to do that.

You need awaitTermination, when you want to block your own thread.


text:
Q: How is it that Summit at Oak Ridge National Lab has 2,414,592 cores? Top500 says that Summit has 2,414,592 cores: https://www.top500.org/system/179397.
But they have 4608 nodes, 9216 chips (each node has 2 chips), and 22 cores per chip. This is 202,752 cores. Where exactly does the number 2,414,592 come from?
Likewise, the webpage of Sierra clearly says that there's 190,080 cores: https://computation.llnl.gov/computers/sierra. But top500 says they have over 1 million.
This is my first question here, so please accept my apologies if this is not a "server" question. I have asked on Meta where to ask HPC questions: https://meta.stackexchange.com/questions/327714/where-should-hpc-questions-about-schedulers-go-stackoverflow-superuser-comput, but there is not yet a stack exchange just for HPC.

A: Validate the number with a rough order of magnitude estimate. 20 two socket servers in a rack, 20 CPU cores per socket. 300 racks is enormous for one computer, that's many MW of power draw. So, in excess of 200,000 CPU cores is possible.
GPU streaming multiprocessors also count as cores, at least to Linpack. The Next Platform peeled the covers off the Summit supercomputer:

The Power9 chips used in Summit have 22 cores running at 3.1 GHz, and
  there are a pair of them in each node for a total of 202,752 cores
  across those 4,608 nodes. There are six Volta GPU accelerators on the
  machine, for a total of 2.21 million SMs. Add it all up, and there are
  2.41 million "cores" as the Linpack folk count them in the Summit machine.

Gone are the days when one simple multiplication will get you the performance of a machine.


text:
Q: Android Studio autocomplete shows same layout view ID twice When using the autocompletion feature, I suddenly see every layout view ID twice. How can I only show each ID one time in the autocomplete popup?
Note, I am importing the activity_main.xml layout like this:
import kotlinx.android.synthetic.main.activity_main.*
Autocomplete two instances of each ID

A: Maybe doing a Clean and Rebuild would help (in the Build menu), or Invalidate Caches and Restart in the File menu.
But just so you know, Kotlin Android Extensions (including the synthetics you're using) is deprecated and unsupported, so it's possible you might see screwy behaviour like this in the tooling. You might just have to put up with it if you continue to use it - the recommended replacement is View Binding, and there's some info about it here (and how to migrate from synthetics) here


text:
Q: Add login page to an existing angular2 application I am new to angular2, and we have a basic running application and I need to write a new login page for this application.
I looked at this tutorial and pretty much am able to replicate this same as standalone:
http://4dev.tech/2016/03/login-screen-and-authentication-with-angular2/
but when I looked to integrate with existing application, I see already different home page defined in app.component, should I rename this app.component to a new component and redirect to it from login component.
what would be the best way to integrate this with minimal changes..best practices around this

A: you have to create a loging component and  define the the login in route configuration like this
export const routes:RouterConfig = [
  {path: 'login', component: LoginComponent},
  {path: '', component: LoginComponent}] //default to login page

in login component. i code like
 export class LoginComponent implements OnInit {
  private jwtHelper:JwtHelper = new JwtHelper();
  messages:String[] = [];
  localUser = {
    username: '',
    password: ''
  }
  constructor(private _service:LoginService, private _router:Router) {
  }
  login() {
    this._service.login(this.localUser).then((data) => {
        if (data) {
          this._router.navigate(['/companies']);
        }
      },
      (error) => {
        this.messages = error;
      });
  }
  clearfields() {
    this.localUser.username = '';
    this.localUser.password = '';
    this.messages = [];
  }
 ngOnInit():any {
    if (window.localStorage.getItem('auth_key') === undefined) {
      console.log("window.localStorage.getItem('auth_key'): " + window.localStorage.getItem('auth_key'));
    }
    else if (window.localStorage.getItem('auth_key') != null &&    !this.jwtHelper.isTokenExpired(window.localStorage.getItem('auth_key'))) {
      this._router.navigate(['/companies']);
    }
  }

after login you can navigate to any page abased on your need


text:
Q: "one down, three to go"
Marcia Howard, a former teacher and organizer who can be found at the square nearly every day, led the crowd in chanting Floyd's name and "one down, three to go," in reference to the other officers charged in Floyd's death. Behind her, a calendar hanging on a gas pump at the Speedway is marked with the date Thomas Lane, J. Kueng and Tou Thao will be arraigned.

Source: USAToday
I couldn't feel the power of the slogan "one down, three to go" but simply understand it as "one criminal has been sentenced, three others will be sentenced too."  Am I on the right track?
Lacking sensitivity to the English slogan appears to be a regret to me. Does this slogan sound contemptible (towards the criminals)? Or does it sound powerful to uphold the law? I have no clue at all.

A: The expression '[first number] down, [second number] to go' simply expresses that a step has been completed in a sequence. In the context you provided, one criminal out of four has been convicted, and the remaining three still need to be convicted. We generally use the expression about situations where completion is desired.


text:
Q: How Can I create an iPod playlist for someone else? (without itunes) My girlfriend is leaving for college this weekend, and I thought I'd make her a playlist (because really, who uses CDs anymore?).
I consider myself quite computer savvy, but I have almost zero experience with an ipod.
Is there a simple way to create a playlist for her ipod? (I'll probably load it via iTunes on her PC, but I want to make the playlist on mine, and then copy it over via a flash drive).
So I believe will need to copy the MP3s, and the "playlist file" over.
How can I create the playlist file without using itunes?

A: The simplest method, if you don't want to use any software, would be to gather your "playlist" into a folder with your MP3s. You should be able to create a new playlist in iTunes, select all your songs, then drag-and-drop them into the playlist. They'll automatically be added to the iTunes library as well as the playlist.


text:
Q: Test fails under prove if it writes to stdout without newline When I run a perl test using the prove utility, it fails if the method under test contains print statements that are not terminated by newlines.
use Test::More tests=>1;

ok(foo(), "calling foo");

sub foo{
    print "A";
    1;
}

This results in
Bad plan.  You planned 1 tests but ran 0.

If I append a newline: print "A\n"; the test passes.
(Note that if I simply execute the test perl mytest.t rather than using prove it passes either way).
Any ideas why this might be, and how to work around it?

A: I found a quick workaround:
$|=0;     # no auto-flush

...but I have no idea (yet) why this works.